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>)
obj.wait();
… // 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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s