Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: reworded a bit and moved text to below the NCE/CS

...

Noncompliant Code Example

Wiki MarkupThis noncompliant code example declares a nonvolatile Boolean flag.

Code Block
bgColor#FFCCCC

private Boolean done;
while (!this.done) {
  Thread.sleep(1000);
}

Wiki Markup
 nonvolatile {{Boolean}} flag. "The compiler is free to read the field {{this.done}} just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of {{this.done}}." \[[JLS 05|AA. Java References#JLS 05]\]. This occurs because there is no{{Thread.sleep()}} does not establish a [happens-before|BB. Definitions#happens-before order] relation offered by {{Thread.sleep()}}.

...

bgColor#FFCCCC

...

Compliant Solution

This compliant solution declares the flag volatile to ensure that updates to it are seen immediately made visible across multiple threads. The volatile flag provides a happens-before relation between this thread and any thread that sets done.

Code Block
bgColor#ccccff
private volatile Boolean done;
while (!this.done) {
  Thread.sleep(1000);
}

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

Risk Assessment

Relying on the synchronization semantics of Thread.yield() and Thread.sleep() methods can cause unexpected behavior.

...