Video in progress
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 nextlockof the same monitor; - a
volatilewrite → the next read of that variable; t.start()→ every action insidet; the end oft→ the return oft.join();executor.submit(task)→ the task running; the task finishing → the return ofFuture.get();ConcurrentHashMap.put→ agetof 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.
Sign up to mark studied questions and save your progress.