I have two threads:
Thread:1
a = 1;
x = b;
Thread:2
b = 1
y = a
Here a and b are declared volatile. I did not understand how a “happens-before” edge is created between a = 1; and y = a; and between x = b; and b = 1;
I understand that by using volatile variable one can prevent reading stale values from thread cache. But how can a volatile variable ensure happens-before ordering.
Specifically, I did not understand this:
a write to a volatile field happens
before every subsequent read of the
same field.
Hoe does it work?
The important word here is “subsequent”.
Here’s the relevant bit of the Java Language Specification 17.4.4 Synchronization Order:
Note the last part. So it’s saying that if you consider any total ordering of the actions of the program, any read of a volatile variable which comes later in that total ordering than a write can’t “miss” the write.