Concurrency Fundamentals • Memory Models & OrderingMedium⏱️ ~2 min
Happens Before and Synchronizes With
Key Insight
Happens-before is the core relationship in memory models. If A happens-before B, then A effects are guaranteed visible to B.
Within a Single Thread
Program order establishes happens-before. Line 1 happens-before line 2. This is intuitive - your code runs in order (even if internally reordered, the effect is as-if sequential).
Happens-Before Chain
Synchronizes-With
This creates happens-before across threads. An unlock synchronizes-with a subsequent lock of the same mutex. A write to an atomic synchronizes-with a read that sees that value.
Building the Chain
Within thread: A happens-before B (program order).
Synchronizes-with: Unlock M happens-before Lock M (cross-thread).
Transitivity: If A happens-before B and B happens-before C, then A happens-before C.
This chain lets you prove: Thread A write is visible to Thread B read.
Why This Matters: To share data safely, you must establish a happens-before chain from the write to the read.
💡 Key Takeaways
✓Happens before is a partial order. If A happens before B, B sees all effects of A. Otherwise, no guarantees.
✓Lock release happens before lock acquire (of same lock). This is how mutexes provide visibility.
✓Volatile write happens before volatile read (of same variable). Volatile provides visibility without locking.
✓Thread start/join establish happens before. Parent thread writes visible to child after start, child writes visible after join.
✓Happens before is transitive. If A happens before B happens before C, then A happens before C.
📌 Examples
1Safe publication: volatile boolean ready = false; ... ready = true (after setup). Reader: if (ready) { use safely initialized data }.
2Lock based visibility: lock(); x = 1; unlock(); ... lock(); print(x); unlock(); Second lock sees x == 1.