The Object.wait()
method is used to temporarily cede possession of a lock so that another requesting thread can proceed. It must always be used inside a synchronized
block or method. To resume activity, the requesting thread must notify the waiting thread. Moreover, the wait()
method should be invoked in a loop that checks if a condition predicate holds.
The invocation of notify()
or notifyAll()
in another thread cannot pin point precisely determine which waiting thread must be resumed. A condition predicate statement is used so that the correct thread is notifiedresumes 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 cannot proceed without obtaining some data from an input stream.
...
To guarantee liveness, the while
loop condition should be tested before invoking the wait()
method. This is because the condition might have already be true been made true by some other thread which indicates that 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 actually resuming execution. This thread can change the state of the object leaving it inconsistent. This is akin to the a "time of check, time of use" (TOCTOU) condition.
- Malicious notifications: There is no guarantee that a random notification will not be sent received when the condition does not hold. This means that the invocation of
wait()
is 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 blocked. - Spurious wakeups: Certain JVM implementations are vulnerable to spurious wakeups that result in waiting threads waking up even without a notification.
...