class BoundedBlockingQueue {
int capacity = 0;
ReentrantLock lk = new ReentrantLock();
Condition full = lk.newCondition();
Condition empty = lk.newCondition();
private Queue<Integer> queue = new LinkedList<>();
public BoundedBlockingQueue(int capacity) {
this.capacity = capacity;
}
public void enqueue(int element) throws InterruptedException {
lk.lock();
try{
while(queue.size() == capacity) {
full.await();
}
queue.add(element);
empty.signal();
} finally {
lk.unlock();
}
}
public int dequeue() throws InterruptedException {
lk.lock();
int res = -1;
try {
while(queue.size() == 0) {
empty.await();
}
res = queue.poll();
full.signal();
} finally {
lk.unlock();
}
return res;
}
public int size() {
return queue.size();
}
}