synchronized, monitors, wait and notify question 29 of 180 mid
When should you prefer notifyAll() over notify()?
- Always use
notify(), it is faster - Correct: Use
notifyAll()whenever waiters wait for different conditions on the same monitor, otherwise a wakeup can be delivered to a thread that cannot use it and the useful waiter sleeps on - They are identical
notifyAll()releases the lock,notify()does not
notify() wakes one arbitrary waiter. In a bounded buffer where producers and consumers wait on the
same monitor, the JVM may wake a producer when a consumer was needed. The producer rechecks its
condition, finds the buffer still full, waits again, and the consumer who could have proceeded was
never told. The system stops with work available: a lost wakeup.
notify() is safe only when every waiter waits for the same condition and any one of them can make
progress. Otherwise notifyAll(), and pay the thundering herd. The better answer to the follow-up is
that ReentrantLock with two Condition objects, one per role, gets you single-waiter wakeups back
without the hazard.
Quiz yourself on synchronized, monitors, wait and notify Suggest a correction