Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing

...

Wiki Markup
To guarantee _safety_, the {{while}} loop condition must be tested even after the call to {{wait()}}. While {{wait()}} is meant to block indefinitely tilluntil a notification is received, this practice is recommended because: \[[Bloch 01|AA. Java References#Bloch 01]\] 

  • 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]\].

Because of these reasons, it is indispensable to check the condition using a loop, after wait() is called.

...

When waiting upon a Condition, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a Condition should always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop.

Newer code must almost always should use the java.util.concurrent concurrency utilities as opposed to the wait/notify mechanism, however, legacy code may require use of these methods.

...