问题
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?
回答1:
The answer to your question is in JLS #17.4.5:
A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field.
So if in one thread you have
aNonVolatileVariable = 2 //w1
aVolatileVariable = 5 //w2
And subsequently in another thread:
someVariable = aVolatileVariable //r1
anotherOne = aNonVolatileVariable //r2
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):
If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
[...]
If hb(x, y) and hb(y, z), then hb(x, z).
In my example:
- hb(w1, w2) and hb(r1, r2) (intra thread semantics)
- hb(w2, r1) because of the volatile guarantee
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.
回答2:
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.
来源:https://stackoverflow.com/questions/12438464/volatile-variables-and-other-variables