Oracle's documentation on atomic access (at http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html) says this:
"a volatile variable establishes a happens-before relationship... . This means that ... when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change."
I'm having trouble wrapping my head around that. I understand how volatile variables work (in >= Java 5), but I'm wondering how the java decides what side-affect "led up" to the change of a volatile variable.
So I guess my question is: What side-effects are given this guarantee?
EDIT:
So I've learned that if thread A modifies a volatile variable, and then thread B reads it, all writes from thread A that happened before the write to the volatile variable are "made coherent" with respect to thread B (ie the cached values of variables subject to the afore mentioned writes by thread A are invalidated in thread B). Correct me if I'm wrong.
a
andb
b being volatile. Our code executesif (b) read a
. In "asm": Instead ofld r0, b; jnz r0, ...; ld r0, a
the processor could dold r1, a; ld r0, b; jnz r0, ...;
And now we have an obvious race condition: We could read an old value of a and the new value of b and never bother checking whether a changed. – Bielefeld