Interview Prep Zoneby CuriouserLabs

Question 3 of 5 · staff level

What does volatile actually guarantee? Explain visibility and happens-before in the Java Memory Model.

🎤 Say this first

volatile guarantees visibility (a write is seen by subsequent reads on other threads) and ordering (no reordering across the volatile access), but not atomicityvolatile int x; x++ still races. Formally, a volatile write happens-before every later read of that variable, and that edge also publishes every ordinary write the writer did before it. Without a happens-before edge, the JMM allows each thread to observe stale values indefinitely.

The full picture

🎬 volatile & the visibility problem

1 / 5
Core 1 · Writer ✍️flag = true; done = …cache: flag=falseCore 2 · Reader 👀while (!flag) { }cache: flag=falseMain memory · flag = falsestill false…maybe laterstale cache hitWithout a happens-before edge, the JMM lets each core see its own version of reality.

Writer thread runs on Core 1, reader spins on Core 2 (while (!flag) {}). Each core has its own cache; flag = false lives in main memory.

The spin-loop that never ends — and how volatile creates the missing happens-before edge.

The Java Memory Model exists because compilers, JITs and CPUs aggressively reorder and cache. The JMM's contract is: if you want thread B to see what thread A wrote, there must be a happens-before chain from A's write to B's read. The main edges: program order within a thread; monitor unlock → subsequent lock; volatile write → subsequent read; Thread.start() → first action of the thread; last action of a thread → join() returning; and everything before submitting to an executor → the task running.

The canonical broken example
// Thread A                    // Thread B
data = 42;                     while (!ready) { }   // may spin forever,
ready = true;                  use(data);           // or see ready==true but data==0 (reordering!)

// Fix: make 'ready' volatile.
// The volatile write publishes data=42 as well (piggybacking).

🔄 Likely follow-up questions

  • Why is double-checked locking broken without volatile — and how do final fields make safe publication possible?
  • What reordering does the JMM permit for two plain writes?
  • What are VarHandle acquire/release modes, and when would you drop below volatile?