The Java Memory Model
Learn the single rule that makes every other concurrency tool in Java trustworthy.
Open this lesson in the learning hubKey points
- Compilers and CPUs reorder code freely. Your own thread always sees a sensible order. Other threads have no such promise.
- happens-before is that promise: if A happens-before B, then everything A wrote is visible to B, in order.
- You get an edge from unlocking then locking the same lock, writing then reading the same
volatile,Thread.start(), andThread.join(). - Library handoffs create edges too: putting into a queue, counting down a latch, completing a future, publishing into a concurrent map.
finalfields are special. As long asthisdoes not escape the constructor, other threads always see them fully built.- No edge means no guarantee, not “usually fine”. A data race is undefined behaviour, and it stays invisible until production load.
Every safe handoff between threads is a happens-before edge. Find yours.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Multithreading course, and every lesson in it is listed on the Multithreading contents page.