Spurious wakeup in Java

If a waiting thread wakes up without notify being called it is called Spurious wakeup.
synchronized (obj) {
while (<condition does not hold>)
… // Perform action appropriate to condition



This is the standard idiom to use wait() method.  In above scenario if a notify() is sent by any other thread then the condition will not hold and wait() will be skipped. Consider if there is no while loop and some other thread calls notify before wait() is called by this thread, then it may happen that it could wait forever or till next notify is called.

The javadoc of wait method in JDK 5 has also been updated

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops

Src : Effective Java By Joshua Bloch