Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Threads that invoke Object.wait() expect to wake up and resume execution when their condition predicate becomes true. To be compliant with rule THI03-J. Always invoke wait() and await() methods inside a loop, waiting threads must test their condition predicates upon receiving notifications and must resume waiting if the predicates are false.

...

This noncompliant code example violates the liveness property. Each thread has a different condition predicate because each requires step to have a different value before proceeding. The Object.notify() method wakes only one thread at a time. Unless it happens to wake the thread that is required to perform the next step, the program will deadlock.

...

This compliant solution uses the signalAll() method to notify all waiting threads. Before await() returns, the current thread reacquires the lock associated with this condition. When the thread returns, it is guaranteed to hold this lock [API 2006]. The thread that is ready can perform its task while all the threads whose condition predicates are false resume waiting.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

THI02-J

low

unlikely

medium

P2

L3

Related Guidelines

Bibliography

[API 2006]

java.util.concurrent.locks.Condition interface

[JLS 2005]

Chapter 17, Threads and Locks

[Goetz 2006]

Section 14.2.4, Notification

[Bloch 2001]

Item 50. Never invoke wait outside a loop

...