Java Concurrency Interview

The Java memory model question 20 of 180 senior

Where do memory barriers come into this, and which ones does the JVM emit?

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.

memory-model hardware

Quiz yourself on The Java memory model Suggest a correction