Java - notify() vs notifyAll() - possible deadlock?
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()开发者_如何学JAVA
, all threads will be notified to run and one of them in its turn will unlock that object for sure.
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: My Produce Consumer Hangs
精彩评论