According to the Java Language Specification [JLS 2011] , §17.3, "Sleep and Yield" [JLS 2011],
It is important to note that neither
Thread.sleep
norThread.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 toThread.sleep
orThread.yield
, nor does the compiler have to reload values cached in registers after a call toThread.sleep
orThread.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 | ||
---|---|---|
| ||
final class ControlledStop implements Runnable { private volatile boolean done = false; // ... @Override public void run() { //... } } |
...
Related Guidelines
CWE ID -821, " Incorrect Synchronization"synchronization |
Bibliography
...