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 let the waiting thread resume activity, the requesting thread must notify the waiting threadit. MoreoverFurthermore, the wait()
method should be invoked in a loop that checks if a condition predicate holds.
...
Two properties come into the picture:
- Liveness: Every operation or method invocation executes to completion without interruptions, even if it goes against safety.
Wiki Markup Safety: Its main goal is to ensure that all objects maintain consistent states in a multi-threaded environment. \[[Lea 00|AA. Java References#Lea 00]\]
- Liveness: Every operation or method invocation executes to completion without interruptions, even if it goes against safety.
To guarantee liveness, the while
loop condition should be tested before invoking the wait()
method. This is because the condition might have already 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 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 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. 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]\].
...