Publishing data through a volatile write
The Java Memory Model (JMM) says when one thread is guaranteed to see another thread's writes. The answer is "when there's a happens-before relationship", created by locks, volatile variables, Thread.start/join and the concurrent utilities. Without one, a thread may see stale or reordered values.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class that publishes an immutable Settings record to readers through a volatile field and lets a writer replace it.
Explain it without notes
What problem does the Java Memory Model solve, and what is happens-before?
What exactly does volatile guarantee, and what doesn't it?
Why does double-checked locking need volatile?
Expected output
reader sees data = 42