In Effective Java: item 66, Joshua Bloch gave an example about life failure:
// Broken! - How long would you expect this program to run
class StopTh
Since you are not telling the thread that stopRequested
is a value that can be modified from outside that thread there are no guarantees that the while
will evaluate to the most recent value of the variable.
This is why the volatile
keyword is useful in this situation, because it will explicitly enforce that stopRequested
value, when read, will be the most recent value set by any thread.
There are further considerations, actually from the point of view of the thread, stopRequested
is a loop invariant, since it is never set by only read, so optimization choices should be considered too: if a value is thought not to be modified then there is no reason to evaluate it on each iteration.