I recently saw the following implementation of enqueue for a BlockingQueue (source)
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);
}
Why is the while loop necessary, and can the while be replaced by if (this.queue.size() == this.limit)
It seems the method enqueue is synchronized so only 1 thread at a time can be executing in the method body and make the call to wait(). Once the thread is notified, can't it just continue onward without checking the this.queue.size() == this.limit condition again?