The Java Memory Model (JMM)
KOTLIN › Concurrency
The rulebook for thread memory sync: visibility, atomicity, ordering, and happens-before.
Thread and memory synchronisation has a searchable name: the Java Memory Model. Each thread may work on its own cached copy of shared data, and the compiler and CPU are allowed to reorder instructions for speed, so one thread's writes are not guaranteed to be seen by another thread, or seen in the order you wrote them. The JMM is the rulebook for when writes become visible. Learn it properly and volatile, synchronized, atomics, locks and ConcurrentHashMap stop being memorised facts and become obvious consequences: they all exist to create happens-before edges.
What this covers
- The core idea: threads can keep cached copies of shared data and compilers/CPUs reorder independent instructions, so nothing is visible across threads, or in order, unless the JMM says so
- Problem 1, visibility: thread A sets a flag, thread B loops forever on a stale cached value; a volatile write publishes so later reads must see it
- Problem 2, atomicity: count++ is three steps (read, add, write) and interleaving loses updates; volatile does NOT fix this, AtomicInteger or a lock does. Knowing that is a senior signal
- Problem 3, ordering: reordering can publish an object reference before its constructor's writes, so another thread observes a half-built object; volatile, synchronized or final forbid the reorder
- happens-before is the unifying rule: if A happens-before B, A's writes are visible to B; a volatile write happens-before every later read of that field, and releasing a lock happens-before the next acquire of it
- Other edges: Thread.start() publishes everything before it into the thread, Thread.join() publishes the thread's writes to the joiner, and edges compose transitively
- final fields: an object whose reference doesn't escape construction publishes its final fields safely to all threads with no sync, which is why immutable objects are inherently thread-safe
- Everything sits on top: volatile, synchronized, atomics, locks and concurrent collections exist to create happens-before edges; ConcurrentHashMap is a map with them baked in
Study this topic
- The Java Memory Model (JMM) explained: the guided lesson
- 14 practice quiz questions
- 9 revision flashcards
- The Java Memory Model (JMM) interview questions and answers