Is a write to a volatile a memory-barrier in Java

末鹿安然 提交于 2019-11-26 16:24:15

问题


I recently heard in a talk that a write to a volatile triggers a memory-barrier for each variable that the thread has written to. Is that really correct? From the JLS, it seems that only the variable concerned gets flushed out, but not others. Does anybody know what is actually correct? Can one point me a concrete location in the JLS?


回答1:


Yes, it will initiate a barrier. You can read more here. There are 4 types, LoadLoad LoadStore StoreStore StoreLoad.

As far as your question

From the JLS, it seems that only the variable concerned gets flushed out, but not others. Does anybody know what is actually correct?

All writes that occur before a volatile store are visible by any other threads with the predicate that the other threads load this new store. However, writes that occur before a volatile load may or may not be seen by other threads if they do not load the new value.

For a practical example

volatile int a =0;
int b = 0;

Thread-1
b = 10;
a = 3;

Thread-2
if(a == 0){
  // b can b 10 or 0
} 
if(a == 3){
   // b is guaranteed to be 10 (according to the JMM)
}



回答2:


The reference to Volatile variables and other variables was correct. I did not realize that the transitivity of happens-before is something that must be implemented by the VM, not something that follows from the definition. I am still puzzled why something with so far-reaching consequences is not stated clearly but actually a corollary from some definition. To wrap it up: Suppose you have 4 actions like this:

thread1        thread2
a1
a2
                a3
                a4

where a2 is a write to a volatile variable v and a3 is a read from the same volatile variable v. It follows from the definiton of happens-before (hb) that hb(a1,a2) and hb(a3,a4). Also, for volatiles we have hb(a2,a3). It follows now from the required transitivity of hb that hb(a1,a3). So the write and subsequent read of the volatile variable v functions as a memory barrier.



来源:https://stackoverflow.com/questions/13688697/is-a-write-to-a-volatile-a-memory-barrier-in-java

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