Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
What is the difference between notify() and notifyAll()?
Both methods are called on an object whose monitor the current thread holds, and both wake threads that are blocked in wait() on that same object.
notify() wakes exactly one waiting thread, chosen arbitrarily by the JVM; there's no way to control or predict which one. notifyAll() wakes every thread currently waiting on that object's monitor, and they then compete to reacquire the lock one at a time.
Using notify() is riskier: if multiple threads are waiting for different conditions on the same monitor, the JVM might wake a thread whose condition still isn't satisfied, while a thread that could actually proceed stays asleep, a form of missed signal or starvation.
Because of that risk, notifyAll() is the safer default; each woken thread re-checks its condition in a loop (while (!condition) wait();) and goes back to waiting if it isn't the right one. notify() is only appropriate when you're certain every waiting thread is waiting for the identical condition.
More Related questions...