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

โ† Back to The Java memory model and volatile

๐Ÿ—’๏ธ The Java memory model and volatile: cheat sheet

๐ŸŽจ The analogyWorkers copy the main board onto private notepads; marking an item "main board only" keeps everyone up to date.
๐ŸŽ“ The regular explanationWhy 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.
The private notepadStep 3 of 3
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ—’๏ธ Ana's notepadrunning = false๐Ÿ—’๏ธ Ben's notepadrunning = true๐Ÿ“‹ Main boardrunning = true
  1. The main board says running = yes. Ben copies it to his notepad and keeps checking his notepad, because it's quicker than walking to the board.
  2. Ana decides to stop and writes running = no, on her own notepad. She'll copy it to the board later, maybe.
  3. Ben keeps reading his own notepad, which still says yes. He might go on forever.
Always use the main boardStep 3 of 3
๐Ÿ‘ฉAna๐Ÿ‘จBenstopped๐Ÿ“‹ Main boardrunning = false
  1. Mark the item "always on the main board". Now nobody keeps private copies of it.
  2. Ana writes "no" straight on the main board.
  3. Ben's next check looks at the main board, sees "no", and he stops.
Notes out of orderStep 3 of 3
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ“„ Recipe42๐Ÿšฉ Ready flagtrue
  1. Ana means to write the recipe first and then raise the ready flag. But to save time, the flag could go up first.
  2. Ben sees the flag, rushes to read the recipe, and finds it empty.
  3. Making the flag a main-board item fixes it. Everything written before raising it is guaranteed to be there when someone sees it up.

๐Ÿงฉ Key questions

Ana changes "running" to "no" on her notepad. Why does Ben never stop?
He keeps checking his own notepad, which still says "yes". Nobody did anything wrong; they just never looked at the main board.
What does marking an item "main board only" do?
Every read and write happens on the main board, so everyone sees the latest. Ana's "no" is seen by Ben on his very next check.
Ana writes the recipe, then raises the "main board only" ready flag. What does Ben see when he sees the flag up?
The recipe, because everything written before the flag is there. The flag can't jump ahead of what was written before it.