The Java memory model question 20 of 180 senior
Where do memory barriers come into this, and which ones does the JVM emit?
- The JVM emits a full barrier for every field access
- Correct: Volatile and lock operations compile to load/store fences, with the exact instruction depending on the CPU architecture
- Barriers are a C++ concept and do not exist in the JVM
synchronizeduses no barriers, only OS locks
The JMM is written in terms of happens-before so that it is portable, but a real CPU implements it with fences. Conceptually there are four: LoadLoad, LoadStore, StoreStore and StoreLoad. A volatile write is StoreStore before, StoreLoad after; a volatile read is LoadLoad and LoadStore after.
The costs differ by architecture, which is why "it works on my machine" is so misleading here. x86 is
total-store-order: ordinary loads and stores are already mostly ordered, and only the StoreLoad after
a volatile write needs a real instruction (lock addl or mfence). ARM and POWER are weakly ordered
and need explicit dmb-class instructions at almost every edge, so races that are invisible on x86
surface immediately there.