import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class BoundedBlockingQueue {
private AtomicInteger size = new AtomicInteger(0);
private static final ReentrantLock lock = new ReentrantLock();
private final Condition isEmpty = lock.newCondition();
private final Condition isFull = lock.newCondition();
private final LinkedList<Integer> list = new LinkedList<Integer>();
private final int capacity;
public BoundedBlockingQueue(int capacity) {
this.capacity = capacity;
}
public void enqueue(int element) throws InterruptedException {
lock.lock();
try {
while (size.get() == capacity) {
isFull.await();
}
list.addFirst(element);
size.incrementAndGet();
isEmpty.signal();
} finally {
lock.unlock();
}
}
public int dequeue() throws InterruptedException {
lock.lock();
try{
while(size.get() == 0){
isEmpty.await();
}
int last = list.getLast();
list.removeLast();
size.decrementAndGet();
isFull.signal();
return last;
} finally {
lock.unlock();
}
}
public int size() {
return size.get();
}
}