Consider a volatile int sharedVar
. We know that the JLS gives us the following guarantees:
w
precedi
I think the volatile
in Java is expressed in terms of "if you see A you will also see B".
To be more explicit, Java promises that when you thread reads a volatile variable foo
and sees value A, you have some guarantees as to what you will see when you read other variables later on the same thread. If the same thread that wrote A to foo
also wrote B to bar
(before writing A to foo
), you're guaranteed to see at least B in bar
.
Of course, if you never get to see A, you can't be guaranteed to see B either. And if you see B in bar
, that says nothing about the visibility of A in foo
. Also, the time that elapses between the thread writing A to foo
and another thread seeing A in foo
is not guaranteed.