Consider this example:
int i = 5;
System.out.println(i);
The compiler may optimize this to just print 5, like this:
System.out.println(5);
However, if there is another thread which can change i
, this is the wrong behaviour. If another thread changes i
to be 6, the optimized version will still print 5.
The volatile
keyword prevents such optimization and caching, and thus is useful when a variable can be changed by another thread.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…