...
This noncompliant code example uses a shutdown()
method to set a non-volatile done
flag that is checked in the run()
method. If some one thread invokes the shutdown()
method to set the flag, it is possible that another thread might not observe this change. Consequently, it may be forced to sleep even though the condition variable (or flag) disallows thisthe second thread may still observe that done
if false and incorrectly invoke the sleep()
method.
Code Block | ||
---|---|---|
| ||
final class ControlledStop implements Runnable {
private boolean done = false;
public void run() {
while(!done) {
try {
// ...
Thread.currentThread().sleep(1000); // Do something
} catch(InterruptedException ie) {
// handle exception
}
}
}
protected void shutdown(){
done = true;
}
}
|
Compliant Solution
This compliant solution declares qualifies the done
flag as volatile
so that updates by one thread are immediately visible to another thread.
...