Search code examples
javaconcurrencyvolatilejls

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


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?


Solution

  • 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.