Copy-On-Write Collections
What you'll learn: How copy-on-write collections optimize thread-safe access for workloads dominated by reads rather than writes.
The Core Idea
Copy-on-write (COW) is a concurrency strategy that sacrifices write performance to make reads blazingly fast and lock-free. Instead of locking a data structure for every read operation, COW collections allow unlimited concurrent reads without synchronization. When a write occurs, the implementation creates a complete copy of the underlying storage, modifies the copy, and atomically swaps it in place of the old version.
When This Makes Sense
Imagine a shared configuration object read by thousands of threads every second but updated only once per hour. Locking every read would create massive contention. With COW, all those reads proceed simultaneously without any locks, while the rare write pays the cost of copying.
The Trade-Off
Reads: Lightning fast—no locks, no waiting, no contention. You're always reading a stable snapshot.
Writes: Expensive—every modification requires duplicating the entire underlying array or structure. This is why COW only shines in read-heavy scenarios (often 90%+ reads).
Memory Consistency
Copy-on-write relies on atomic reference updates. When the new version is ready, a single atomic operation (like compare-and-swap) publishes it. Readers either see the old version completely or the new version completely—never a half-modified mess. This leverages the happens-before guarantees you've learned to ensure visibility across threads.
Real-World Use
Languages like Java provide CopyOnWriteArrayList for exactly this pattern: configurations, observer lists, or any collection where iteration vastly outnumbers modification.
Key Takeaway:
Copy-on-write collections optimize read-heavy workloads by making reads lock-free while deferring all synchronization cost to writes, which create and atomically install new versions.