views:

67

answers:

1

Is there any situation in which notify() can cause deadlock, but notifyAll() - never?

For example, in case of multiple locks. notify() notifies only one thread to run, which checks for lock to some object and becomes waiting again, though another thread could unlock that object. In case of using notifyAll(), all threads will be notified to run and one of them in its turn will unlock that object for sure.

+2  A: 

Yes. Imagine you implement the Producer - Consumer problem with synchronize, wait, and notify. (edit) In which 2 Producers and 2 Consumers all wait on the same object monitor (end edit).The Producer calls notify in this implementation. Now suppose you have two Threads running the Producer's code path. It is possible that Producer1 calls notify and wakes Producer2. Producer2 realizes he can not do any work and subsequently fails to call notify. Now you are deadlocked.

(edit) Had notifyAll been called, then both Consumer1 and Consumer2 would have woken up in addition to Producer2. One of the Consumers would have consumed the data and in turn called notifyAll to wake up at least one Producer, thus allowing the very broken implementation to limp along successfully.

Here is the reference question I base my scenario off of: http://stackoverflow.com/questions/3067877/my-produce-consumer-hangs

Tim Bender
Does notifyAll() solve the problem in this case?
WarGoth
Why would Producer2 be waiting on the object that Producer1 notifies? That doesn't make any sense.
Mark Peters
Oh, that's odd, everybody just waits on the queue in your "reference question." That's a broken producer/consumer example then I'd say...typically you have a "empty" monitor and a "full" monitor; producers wait on the full monitor and notify the empty monitor, consumers wait on the empty monitor and notify the full monitor. But you did succeed in giving an example.
Mark Peters
@Mark Peters, yes well, nobody said anything about the code being of any type of quality. I assume whatever code inspired such a generic question from the OP is easily as confused/confusing as the code from my reference question.
Tim Bender