Any thread that invokes wait()
expects to wake up and resume execution when some condition predicate becomes true. As recommended by CON18-J. Always invoke wait() and await() methods inside a loop, waiting threads should test their condition predicates upon receiving notifications and resume waiting if they are false (that is, when the condition expression in the loop evaluates to true).
The methods notify()
and notifyAll()
of package java.lang.Object
are used to waken waiting thread(s). These methods must be invoked from code that holds the same object lock as the waiting thread(s). The notifyAll()
method wakes up all threads and allows ones whose condition predicate is true (loop expression is false), to resume execution. Furthermore, if all the threads whose condition predicate now evaluates to true previously held a specific lock before going into the wait state, only one of them will reacquire the lock upon being notified, and the others may, presumably, resume waiting. The notify()
method wakes up only one thread, and makes no guarantees as to which thread is notified. If the thread's condition predicate doesn't allow, the chosen thread may not awaken, defeating the purpose of the notify()
callnotification.
The notify()
method may only be invoked if all the following conditions are met:
...
This noncompliant code example violates the liveness property. Each thread has a different condition predicate, as each requires step
to have a different value before proceeding. The Object.notify()
method wakes up only one thread at a time. Unless it happens to wake up the thread that is required to perform the next step, the program deadlocksstalls.
Compliant Solution (notifyAll()
)
In this compliant solution, all threads that have performed their own step use notifyAll()
to notify other waiting threads. Consequently, the respective threads that are ready can perform the task, while all other threads whose condition predicate evaluates to trueis false (loop condition expression is true), promptly go back to sleep.
...
This noncompliant code example derives from the previous noncompliant code example but uses the Condition
interface. Field condition
is used to let threads allows the threads to wait on different condition predicates.
...
This compliant solution assigns each thread its own Condition
condition, and makes them all the Condition
objects accessible to all the threads.
...
Even though signal()
is used, it is guaranteed that only one thread will awaken because each condition predicate corresponds to a unique Condition
variable. All threads perform the same operations. This compliant solution is only safe if untrusted code cannot create a thread with an instance of this class.
Risk Assessment
...