I was going through this bounding queue code online trying to understand it
public class BlockingQueue {
private List queue = new LinkedList();
private int limit = 10;
public BlockingQueue(int limit){
this.limit = limit;
}
public synchronized void enqueue(Object item)
throws InterruptedException {
while(this.queue.size() == this.limit) {
wait();
}
if(this.queue.size() == 0) {
notifyAll();
}
this.queue.add(item);
}
public synchronized Object dequeue()
throws InterruptedException{
while(this.queue.size() == 0){
wait();
}
if(this.queue.size() == this.limit){
notifyAll();
}
return this.queue.remove(0);
}
}
My understanding is this:
But what happens to the requests that we call wait() on. Do they only get notified on the notifyAll() call? Why do they not get notified as soon as their is space in the queue?
You only need to notify when adding to an empty queue, because dequeuers are only waiting on an empty queue.
Similarly you only need to notify when dequeueing from a full queue, because enqueuers are only waiting on a full queue.