Java Reference
In-Depth Information
Flush cached registers,
Reload any values,
Or provide any happens-before relationships when execution resumes.
is incorrect and is consequently disallowed. Programs must ensure that communication
between threads has proper synchronization, happens-before, and safe publication se-
mantics.
Noncompliant Code Example (
sleep()
)
This noncompliant code attempts to use the nonvolatile primitive Boolean member
done
asaflagtoterminate execution ofathread.Aseparate threadsets
done
to
true
bycalling
the
shutdown()
method.
final class ControlledStop implements Runnable {
private boolean done = false;
@Override public void run() {
while (!done) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Reset interrupted status
Thread.currentThread().interrupt();
}
}
}
public void shutdown() {
this.done = true;
}
}
The compiler, in this case, 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 2013]. This error could have resulted from the programmer incorrectly
assuming that the call to
Thread.sleep()
causes cached values to be reloaded.