Versions Compared

Key

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

According to the Java Language Specification, §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.

...

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 2011]. This error could have resulted from the programmer incorrectly assuming that the call to Thread.sleep() would cause cached values to be reloaded.

...

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

Related Guidelines

MITRE CWE

CWE-821, Incorrect synchronization

Bibliography

...