...
The notification mechanism notifies the waiting thread and lets it check its condition predicate. The invocation of notify()
or notifyAll()
in another thread cannot precisely determine which waiting thread must be resumed. A condition predicate statement is used so that the correct thread resumes when it receives a notification. A condition predicate also helps when a thread is required to block until a condition becomes true, for instance, when it should not proceed without reading some data from an input stream.
Two When using the wait/notify mechanism, two properties come into the picture:
...
To guarantee liveness, the while
loop condition should be tested before invoking the wait()
method. This is because the condition predicate might have already been made true by some other thread which indicates that with a good chance that the same thread also sent out a notify signal may have already been sent from the other thread. Invoking the wait()
method after the notify signal has been sent is futile and results in an infinitely blocked state.
...
- Thread in the middle: A third thread can acquire the lock on the shared object during the interval between a notification being sent and the receiving thread resuming execution. This thread can change the state of the object, leaving it inconsistent. This is a time of check, time of use (TOCTOU) condition.
- Malicious notifications: There is no guarantee that a random notification will not be received when the condition predicate evaluates to is false. This means that the invocation of
wait()
may be nullified by the notification. - Mis-delivered notification: Sometimes on receipt of a
notifyAll()
signal, an unrelated thread can start executing and it is possible for its condition predicate to be true. Consequently, it may resume execution whilst it was required to remain dormant. Wiki Markup Spurious wakeups: Certain JVM implementations are vulnerable to _spurious wakeups_ that result in waiting threads waking up even without a notification \[[API 06|AA. Java References#API 06]\].
Because of these reasons, it is indispensable to check the condition predicate after wait()
is invoked. A while loop is the best choice to check the condition predicate before and after invoking wait()
.
...
Similarly, if the await()
method of the java.util.concurrent.locks.Condition
interface is implementedused, it should be enclosed in a loop.
...