Home/Labs/Race Conditions & Atomic CAS
All 280 Labs
INTERACTIVE LAB🛡️

Multithreading & Thread Safety Lab (Interactive)

Interleave read-modify-write windows against a shared counter, then fix it with mutex or CAS. A deterministic event simulation of lost updates: widen the stale-read window, compare unsynchronized, locked, and lock-free strategies.

Race Conditions & Lock-Free CAS Simulator

N threads hammer a shared counter with read-modify-write windows. Corrupt it, serialize it, or fix it with hardware Compare-And-Swap.

4
500
8
Shared heap: balance counter500 / 2,000
DATA CORRUPTION: 1,500 updates silently lost (75.0%). Each blind write overwrote a concurrent thread's increment.
Aggregate throughput
0.40 ops/tick
Lost updates
1,500
CAS retries
0
Completion tick
5,005

Thread insecurity = shared state ∧ mutable state. Widen the read→write window or add threads to expose more races; mutexes trade throughput for correctness while CAS stays fast until contention drives retries up.

How It Works Under the Hood

Thread insecurity is shared state combined with mutable state. A read-modify-write that lapses for even a few cycles lets another core’s write get silently clobbered — the balance shows $130 instead of $180. Mutexes serialize correctness at a throughput price, while hardware Compare-And-Swap (LOCK CMPXCHG) validates the snapshot in one indivisible instruction and retries on conflict, never sleeping in the kernel. This is how LMAX’s Disruptor hits millions of orders per second.

Core Architectural Principles

  • Lost updates = total increments minus final counter; they grow with the read-to-write window and thread count.
  • CAS succeeds only when memory still equals the snapshot; conflicts cost a retry, not a context switch.
  • Mutexes guarantee correctness via serialization, trading throughput and adding kernel sleep on contention.
Interview Round Script

Lead with the golden rule: "races require shared AND mutable state, so immutability or message passing eliminates them structurally." Then show mechanics: explain CAS’s compare-and-swap loop, mention volatile/memory barriers for visibility, and cite AtomicLong counters over coarse global locks in metrics paths.

Key Trade-Offs

Locks are simple but serialize parallelism; lock-free CAS is fast yet burns retries under contention and is hard to get provably correct.

Related Curriculum Chapter

Multithreading & Thread Safety

Read Full Chapter Blueprint

Explore More Interactive Labs

View All 280 Labs