tags:

views:

667

answers:

5

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

+5  A: 

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

Norbert Hartl
+5  A: 
Mork0075
+1  A: 

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.

mP
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.
Michael Borgwardt
I eliminated Thread to keep things as simple as possible.
mP
+1  A: 

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.

fforw
+2  A: 

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.

Michael Borgwardt