...
If one thread invokes the shutdown()
method to set the flag, it is possible that another thread might not observe this change. Consequently, the second thread may observe that done
is still false
and incorrectly invoke the sleep()
method. In fact, a compiler is allowed to optimize the code if it determines that the value of done
is never modified by the same thread, so that the loop never terminates.
Compliant Solution (volatile
)
...