The following is from classical Concurency in Practice
:
When thread A writes to a volatile variable and subsequently thread B reads the same variable, the values of all variables that were visible to A prior to writing to the volatile variable, become visible to B after reading the volatile variable.
I am not sure I can really understand this statement. For example, what is the meaning of all variables in this context? Does this mean that using volatile
also has side-effects to the usage of non-volatile variables?
It seems to me that this statement has some subtle meaning that I can not grasp.
Any help?
The answer to your question is in JLS #17.4.5:
So if in one thread you have
And subsequently in another thread:
You have the guarantee that
anotherOne
will be equal to 2, even if that variable is not volatile. So yes, using volatile also has side-effects to the usage of non-volatile variables.In more details, this is due to 2 other guarantees provided by the Java Memory Model (JMM) in that same section: intra thread order and transitivity (hb(x,y) means x happens before y):
In my example:
so you can conclude that hb(w1, r2) by transitivity.
And the JMM guarantees that all executions of a program will be sequentially consistent (i.e. will look like nothing has been reordered) if it is correctly synchronized with happens-before relationships. So in this specific case, the non-volatile read is guaranteed to see the effect of the non-volatile write.
It means if you write to ten non-volatile variable and write to a volatile one, all the non-volatile variables must be set before the volatile one.
If you read the volatile variable and all the non-volatile ones you can be sure that the order won't be swapped around.