Thursday, May 5, 2011

Java - wait and notifyAll

What happens when you call notifyAll method on an object that is not waiting? Should there be exception or is it normal situation?

From stackoverflow
  • It is completely normal. You can only notify all that waiting on one single monitor. Everybody else is not interested. The object on which you call notifyAll is just the monitor on which others are waiting. If nobody is waiting nobody has to be notified

  • As you can see here, calling notifyAll() on an not waiting object does not have any effect.

    alt text

  • Only waiting Objects get notified. Object.wait() blocks until a timeout or notify - so the question remains how or why would you think non waiting Objects would ever get notified ? it makes no sense.

    Michael Borgwardt : Objects do not wait or are notified - threads do. And it's perfectly possible and normal to call notifyAll() on a monitor object without knowing whether or not there are threads waiting on it. For example, in a producer/consumer scenario with a queue, the consumer might have emptied the queue and still be occupied with processing when the producer adds a new element to the queue and notifies all consumers who are waiting (i.e. none) about this.
    mP : I eliminated Thread to keep things as simple as possible.
  • The object is "waited on", not waiting itself. The thread is the one who is waiting. If no one is waiting, no one will wake up and nothing special will happen.

  • Perfectly normal situation.

    Let's say you have a queue with a producer thread putting elements into it and a consumer threads removing elements from it.

    Now the consumer might have emptied the queue and still be occupied with processing, so nobody is waiting for the queue to become non-empty. Now the producer adds a new element to the queue. He has to call notifyAll() to wake up the consumer if it were waiting. Adding additional logic to check if anyone is waiting and only calling notifyAll() in that case would add considerable (and very failur-prone) complexity to the scenario - it's much easier to just call notifyAll() every time.


Post a Comment