Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed to Applicability, corrected some links, and updated the references to Java 7

According to Section 17.9the Java Language Specification [JLS 2011] §17.3, "Sleep and Yield," of the Java Language Specification [JLS 2005],

It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.

...

  • flush cached registers
  • reload any values
  • provide any any happens-before relationships when execution resumes
    is incorrect and is consequently disallowed. Programs must ensure that communication between threads has proper synchronization, happens-before, and visibility semantics.

...

However, the compiler is free to read the field this.done once and to reuse the cached value in each execution of the loop. Consequently, the while loop might never terminate, even when another thread calls the shutdown() method to change the value of this.done [JLS 20052011]. This error could have resulted from the programmer incorrectly assuming that the call to Thread.sleep() would cause cached values to be reloaded.

...

The volatile flag establishes a happens-before relationship between this thread and any other thread that sets done.

...

Code Block
bgColor#ccccff
public class Waiter {
  // ...
  private Thread thread;
  private volatile boolean flag;
  private final Object lock = new Object();

  public boolean stop() {
    if (thread != null) {
      flag = true;
      synchronized (lock) {
        lock.notifyAll();
      }
      return true;
    }
    return false;
  }
}

...

Applicability

Relying on the Thread class's sleep(), yield(), and getState() methods for synchronization control can cause unexpected behavior.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

CON51-JG

low

probable

medium

P4

L3

Related Guidelines

MITRE CWE

CWE ID 821, "Incorrect Synchronization"

Bibliography

Issue Tracking

...

 
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name|| 

 

...