Can a reordering happen in the presence of a volatile variable? [duplicate]

浪尽此生 提交于 2019-12-11 03:38:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!