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.