Command Palette

Search for a command to run...

Back to the lesson: Topic 13.4 — volatile and the Java Memory Model
Core Java · Example 1 of 3

A volatile stop flag

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.

01

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

01

What problem does the Java Memory Model solve, and what is happens-before?

02

What exactly does volatile guarantee, and what doesn't it?

03

Why does double-checked locking need volatile?

A volatile stop flag
Sign in to run this example in your browser.

Expected output

worker saw running = false and stopped
main: worker finished