Java Concurrency Interview

synchronized, monitors, wait and notify question 29 of 180 mid

When should you prefer notifyAll() over notify()?

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.

wait-notify

Quiz yourself on synchronized, monitors, wait and notify Suggest a correction