Manan Mehta
Manan Mehta

Reputation: 37

Java Blocking Queue why we have notifyall in enqueue with condition if queue.size==0?

Here is a simple implementation:

  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);}

Upvotes: 0

Views: 124

Answers (1)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

Because if you look at a typical dequeue, it looks like this

public synchronized Object dequeue() throws InterruptedException 
{ 
    while (this.queue.size() == 0) { 
        wait();  // look here
    } 
    if (this.queue.size() == this.limit) { 
        notifyAll(); 
    } 

    return this.queue.remove(0); 
} 

It is to notify the locks waiting while queue size is 0.

Upvotes: 1

Related Questions