The full picture
🎬 volatile & the visibility problem
1 / 5Writer 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 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.
// 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).