Versions Compared

Key

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

...

  • 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 must execute 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 predicate might have already been made true by some other thread with a good chance that the same thread also sent out a notify signal. Invoking the wait() method after the notify signal has been sent is futile and results in an infinitely blocked stateindefinite blocking.

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

...

Because of these reasons, it is indispensable to check the condition predicate after wait() is invoked. A while loop is the best choice to check for checking the condition predicate before and after invoking wait().

...

This noncompliant code example invokes the wait() method inside a traditional if block and fails to check the post condition after the notification (accidental or malicious) is received. This means that the thread can wake up when it is not supposed to do so.

Code Block
bgColor#FFcccc
synchronized(object) {
  if(<condition does not hold>)
    object.wait();
  // Proceed when condition holds
}

...

Code Block
bgColor#ccccff
synchronized (object) {
  while (<condition does not hold>) {
    object.wait(); 
  }

  // Proceed when condition holds
}

Similarly, if invocations of the await() method of the java.util.concurrent.locks.Condition interface is used, it should always be enclosed in a loop.

Risk Assessment

To guarantee liveness and safety, the wait() and await() methods should always be called invoked inside a while loop.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON18- J

low

unlikely

medium

P2

L3

...