← Lessons

quiz vs the machine

Silver1130

Concurrency

The Copy On Write Collections

Snapshot semantics that make reads lock free by rebuilding the whole array on every write.

4 min read · intro · beat Silver to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. Why can readers iterate without a lock?

2. When is copy on write a poor choice?