Let's say I have a static int that affects behaviour of the class.
class A{
public static int classFlag = 0;
private int myFlag = 0;
public void doSomething(){
if(myFlag != classFlag){
myFlag = classFlag:
}
/*myFlag-dependent behaviour*/
}
}
There's exactly one thread in the system that changes classFlag, and /*myFlag-dependent behaviour*/ does not require that an update to classFlag is immediately visible to all threads.
I would therefore like to keep the classFlag non-volatile to avoid introducting a costly and completely unnecessary memory barrier.
Can I rely on an update to classFlag being eventually visible?
The reader thread that executes a piece of code based on myFlag will not be able to see your update, which can result in 1) very uncertain behavior 2) a missed update (you never know when will this ::doSomething be called again)
I think cost of volatile is low enough to warrant it's correct usage rather than leaving code with such bugs.