...
Noncompliant Code Example
This noncompliant code example declares a nonvolatile Wiki Markup Boolean
flag.
Code Block | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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.
...