问题
I am doing as follows, there's only 2 threads in my program.
// Thread 1
write a = 0
write a = 1
write volatile b = 1
// Thread 2
read volatile b // this I always do after write volatile b in the 1st thread
read a
I've read on Java Memory Model and from what I understand in thread 2 read a will ALWAYS give me 1.
I would like to know if this my understanding is correct or not.
In particular CAN A REORDERING still HAPPEN so I see a = 0 in the 2nd thread?
回答1:
Your assumptions are mostly correct. However, i would restate it slightly to match what the JMM guarantees.
If Thread 2 reads b and sees value 1, then the subsequent read of a will be 1. Like you said, if Thread 2 always reads b "after" Thread 1 finishes writing it, then Thread 2 will see the value 1 and the read of a will be as you expect.
来源:https://stackoverflow.com/questions/25548547/can-a-reordering-happen-in-the-presence-of-a-volatile-variable