Notify () vs notifyAll () - possible deadlock?

Is there a situation in which it notify()can cause a dead end, but notifyAll()never?

For example, in the case of several locks. notify()notifies only one thread to start, which checks the lock on an object and comes back to life, although another thread can unlock this object. In case of use, notifyAll()all threads will be notified of the launch, and one of them, in turn, will certainly unlock this object.

+3
source share
1 answer

Yes. Imagine that you are implementing the "Producer - Consumer" problem p synchronize, wait, and notify. (change) . For 2 manufacturers and 2 users, everyone is waiting on one object monitor (final editing) . The producer calls notifyin this implementation. Now suppose you have two threads that start the manufacturer code path. It is possible that Producer1 calls notifyand wakes up Producer2. Manufacturer2 understands that he cannot perform any work and subsequently cannot call notify. Now you are at an impasse.

() notifyAll , Consumer1 Consumer2 Producer2. , , notifyAll, , , .

, :

+6

Source: https://habr.com/ru/post/1766849/


All Articles