Video in progress

Strong Middle 🧵 Concurrency

What is the happens-before relationship in the Java memory model, and which operations create it?

Happens-before is the guarantee that "all of A's writes are visible to B, and A is ordered before B". It arises through operations like releasing/acquiring a monitor, a volatile write/read, Thread.start/join, and submitting to an executor, and it is transitive.

📖 Answer

The JMM answers the question "when must one thread see another thread's write?". Without happens-before, it is legal for a reader to see an old value, because of CPU caches, store buffers and JIT reordering.

The main rules:

  • within a single thread: program order;
  • a monitor unlock → the next lock of the same monitor;
  • a volatile write → the next read of that variable;
  • t.start() → every action inside t; the end of t → the return of t.join();
  • executor.submit(task) → the task running; the task finishing → the return of Future.get();
  • ConcurrentHashMap.put → a get of the same key.

Transitivity is the most useful part in practice:

int payload;              // a plain field
volatile boolean ready;

// writer
payload = 42;
ready = true;             // volatile write

// reader
if (ready) {              // volatile read
    System.out.println(payload);   // 42 is guaranteed
}

Even though payload is not volatile, it was written before the volatile write, so a thread that sees ready as true also sees payload correctly.

A common mistake in interviews is understanding happens-before as "earlier in time". Being earlier in time doesn't guarantee visibility; only the chains above give the guarantee.