Versions Compared

Key

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

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

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.

Code that depends on thread suspension or yielding that yields to

  • flush cached registers
  • reload any values
  • provide any happens-before relationships when execution resumes

...

This noncompliant code attempts to use the nonvolatile primitive Boolean member done as a flag to terminate execution of a thread. A separate thread sets done to true by calling the shutdown() method.

...

This compliant solution declares the flag field volatile to ensure that updates to its value are made visible across multiple threads.:

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private volatile boolean done = false;

  // ...
  @Override public void run() {
  //...
  }
}

...

Related Guidelines

MITRE CWE

CWE ID -821, " Incorrect Synchronization"synchronization

Bibliography

 

...