TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท java ยท concurrency ยท jvm

The Java memory model and volatile

Why one thread's writes may not be seen by another, or may be seen out of order, and how volatile, locks and final fields create the happens-before guarantees that make them visible.

10 min3 animations

๐Ÿ“š Builds on๐Ÿ–Š๏ธ Threads, locks and race conditions

๐Ÿ–จ๏ธ Cheat sheet

Private notepads

A team shares a main board. Walking to it is slow, so each person copies what they need onto a private notepad and checks that instead. Ana changes "running" to "no" on her notepad. Ben keeps checking his own notepad, which still says "yes". Nobody did anything wrong, but Ben never stops.

Visibility

CPU cores have their own caches and store buffers, and the JIT compiler keeps values in registers. So without synchronisation, a write by one thread may never be seen by another:

1private boolean running = true;2 3void worker() {4    while (running) { doWork(); }   // may loop forever5}6void stop() { running = false; }

The JIT can legally hoist the read of running out of the loop. Tests rarely catch it.

The private notepad3 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ—’๏ธ Ana's notepad๐Ÿ—’๏ธ Ben's notepad๐Ÿ“‹ Main board
Press play and watch it happen!

Main board only

The fix is to mark that item "main board only". Nobody keeps a private copy; every read and write happens on the board. Ana's "no" is seen by Ben on his very next check.

volatile

A volatile field is always read from and written to shared memory, and the compiler and CPU may not reorder other memory operations across it in ways that break that guarantee. private volatile boolean running = true; fixes the loop.

volatile gives visibility, not atomicity: volatile int count; count++ is still a race. Use a lock or AtomicInteger for compound actions.

Always use the main board3 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ“‹ Main board
Press play and watch it happen!

Notes out of order

People also reorder their jobs to save time. Ana means to write the recipe and then raise the ready flag, but if the flag goes up first, Ben rushes in and finds an empty recipe. Marking the flag "main board only" also means everything written before it is there by the time anyone sees it.

Happens-before

The Java Memory Model defines when a write is guaranteed visible: if write W happens-before read R. Edges come from:

  • a volatile write and a later read of the same field,
  • unlocking a monitor and a later lock of the same monitor,
  • Thread.start() and join(),
  • the end of a constructor, for final fields (safe publication),
  • the java.util.concurrent classes, which document their guarantees.

Everything a thread did before the edge is visible after it. Without one, reordering is fair game.

Notes out of order3 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ“„ Recipe๐Ÿšฉ Ready flag
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 3 questions about The Java memory model and volatile, told the same way as the story.
  1. Ana changes "running" to "no" on her notepad. Why does Ben never stop?
  2. What does marking an item "main board only" do?
  3. Ana writes the recipe, then raises the "main board only" ready flag. What does Ben see when he sees the flag up?
Answer every question to check.Passing marks The Java memory model and volatile as done.
Got the hang of The Java memory model and volatile? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜• Java concurrencyStep 2 of 5

โ† Previous on the path๐Ÿ–Š๏ธ Threads, locks and race conditionsNext on the path โ†’๐Ÿ“Ÿ CompletableFuture and async