Cheap reads, expensive writes
A copy on write collection holds its elements in an immutable array. Readers grab the current array reference and iterate it freely with no lock, because that array never changes. Every mutation creates a brand new array with the change applied and swaps in the new reference.
How a write works
- Take the write lock so only one mutation happens at a time
- Copy the entire backing array into a new one
- Apply the insertion or removal to the copy
- Publish the new array by an atomic reference swap
A reader that captured the old array keeps iterating the old snapshot safely, never seeing a half applied change.
When it fits
This design shines when reads vastly outnumber writes and the collection is small, such as a list of event listeners. It is a poor fit for write heavy or large collections, because each write costs a full copy proportional to the size.
Key idea
Copy on write gives readers a stable lock free snapshot by rebuilding the entire array on every write, ideal only when reads dominate.