Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added 'happens-before'

...

Wiki Markup
This noncompliant code example declares a 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 {BB. Definitions#happens-before order|happens-before relation] offered by {{Thread.sleep()}}.

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

...

This compliant solution declares the flag volatile to ensure that updates to it are seen immediately across multiple threads. The volatile flag provides a {BB. Definitions#happens-before order|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);
}

...