Concurrency FundamentalsMemory Models & OrderingEasy⏱️ ~2 min

What is a Memory Model?

Definition
A memory model defines the rules for how memory operations (reads and writes) can be observed across threads. It answers: when does a write by one thread become visible to others?

The Problem It Solves

CPUs and compilers reorder operations for performance. Thread A writes X then Y. Thread B might see Y before X. Without rules, concurrent code is impossible to reason about.

Why Memory Models Matter
Thread AThread Bdata = 42ready = truereordered?if (ready)use(data)data = 0 ?!
B sees ready=true but data=0 if writes are reordered

Sources of Reordering

Compiler: Moves code around for optimization. May hoist loads out of loops or sink stores.

CPU: Executes instructions out of order. Has store buffers that delay writes.

Caches: Different cores see updates at different times due to cache coherency protocols.

The Contract

A memory model is a contract between programmers and hardware/compiler. Follow the rules, and your concurrent code will work correctly on any conforming implementation.

Key Point: Without proper synchronization, you cannot assume anything about the order other threads see your writes.
💡 Key Takeaways
A memory model defines visibility rules: when writes by one thread become visible to other threads.
Compilers reorder code for optimization. x = 1; y = 2 might execute as y = 2; x = 1 if there is no dependency.
CPUs reorder instructions for performance. Out of order execution can make writes visible in unexpected order.
Each CPU core has its own cache. Writes may be visible in core 1 cache but not yet in core 2.
Without synchronization, you have no guarantees about the order other threads see your writes.
📌 Examples
1Flag pattern broken: done = true; data = result; Another thread might see done == true but data still uninitialized.
2Publication idiom: object = new Object(); Another thread might see non null reference but partially constructed object.
← Back to Memory Models & Ordering Overview
What is a Memory Model? | Memory Models & Ordering - System Overflow