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?
volatile in most programming languages does not imply a real CPU read memory barrier but an order to the compiler not to optimize the reads via caching in a register. This means that the reading process/thread will get the value "eventually".
Memory barriers, or fences, are a set of processor instructions used to apply ordering limitations on memory operations.
For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.
Unlike synchronized methods or blocks, it does not make other threads wait while one thread is working on a critical section. Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With