← Lessons

quiz vs the machine

Platinum1780

Concurrency

Memory Visibility and Happens Before

Why one thread may not see another thread's writes without ordering.

6 min read · advanced · beat Platinum to climb

Memory Visibility and Happens Before

Modern CPUs and compilers reorder and cache memory operations for speed. As a result, a write by one thread is not guaranteed to be visible to another thread immediately, or even in program order.

The memory model of a language defines the rules. The central concept is the happens before relation. If action X happens before action Y, then the effects of X are visible to Y. Without such a relation, there is no guarantee about what a thread observes.

Happens before edges are created by synchronization:

  • Releasing a lock happens before another thread acquires the same lock.
  • A volatile or atomic write happens before a later read of the same variable.
  • Thread start happens before any action in the started thread.

This is why publishing data through a plain field is unsafe. A reader might see the reference but stale or partially constructed contents. Using proper synchronization establishes the ordering that makes writes visible.

Reordering is legal as long as it does not break a single thread's own logic, so cross thread visibility needs explicit synchronization.

Key idea

Without a happens before relationship from synchronization, one thread has no guarantee of seeing another thread's writes correctly.

Check yourself

Answer to earn rating on the learn ladder.

1. What guarantees one thread sees another thread's write?

2. Which action establishes happens before?