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

后端 未结 2 1348
失恋的感觉
失恋的感觉 2020-12-03 03: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 se

相关标签:
2条回答
  • 2020-12-03 03:24

    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.

    0 讨论(0)
  • 2020-12-03 03:47

    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)
    }
    
    0 讨论(0)
提交回复
热议问题