โ 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 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.
- Ana decides to stop and writes running = no, on her own notepad. She'll copy it to the board later, maybe.
- Ben keeps reading his own notepad, which still says yes. He might go on forever.
- Mark the item "always on the main board". Now nobody keeps private copies of it.
- Ana writes "no" straight on the main board.
- Ben's next check looks at the main board, sees "no", and he stops.
- Ana means to write the recipe first and then raise the ready flag. But to save time, the flag could go up first.
- Ben sees the flag, rushes to read the recipe, and finds it empty.
- 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.