Here we have hb(w, r) but that doesn't mean that c will contain value 3 after assignment. How do I enforce that c is assigned with 3? Does synchronization order provide such guarantees?
And your example
public volatile int v;
public int c;
Actions:
Thread A
v = 3; //w
Thread B
c = v; //r
You don't need volatile
for v
in your example. Let's take a look at a similar example
int v = 0;
int c = 0;
volatile boolean assigned = false;
Actions:
Thread A
v = 3;
assigned = true;
Thread B
while(!assigned);
c = v;
assigned
field is volatile.
- We will have
c = v
statement in Thread B
only after assigned
will be true
(while(!assigned)
is responsible for that).
- if we have
volatile
— we have happens before
.
happens before
means that, if we see assigned == true
— we will see all that happened before a statement assigned = true
: we will see v = 3
.
- So when we have
assigned == true
-> we have v = 3
.
- We have
c = 3
as a result.
What will happen without volatile
int v = 0;
int c = 0;
boolean assigned = false;
Actions:
Thread A
v = 3;
assigned = true;
Thread B
while(!assigned);
c = v;
We have assigned
without volatile
for now.
The value of c
in the Thread B
can be equal 0 or 3 in such situation. So there is not any guaranties
that c == 3
.