The Java Memory Model

Multithreading · lesson 16 of 38 · 4 min read

Learn the single rule that makes every other concurrency tool in Java trustworthy.

Open this lesson in the learning hub

Key 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(), and Thread.join().
  • Library handoffs create edges too: putting into a queue, counting down a latch, completing a future, publishing into a concurrent map.
  • final fields are special. As long as this does 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.