Lesson · Concurrent Collections
CopyOnWriteArrayList: snapshot reads, copy-per-write
14 min readCopyOnWriteArrayList
CopyOnWriteArrayList puts all the cost of change on the writer: every mutation copies the whole array and publishes it, while reads and iterators never take a lock. It is the right list for registries that are read on every event and written a few times a day.
The mechanism: copy, swap, publish
All the state of a CopyOnWriteArrayList is one array behind a volatile reference. A mutation takes an internal lock, copies the current array into a new one with the change applied, and publishes the new array through that volatile reference. A reader takes the reference and indexes into it, so it never takes a lock and never blocks.
The lock exists so writers do not overwrite each other while copying. It is not needed by readers at all, and that asymmetry is the entire design: the write side pays for coordination, the read side pays nothing.
The consequence to internalize is that no array is ever modified in place. A version of the list that has been published stays exactly as it was, which is what makes a stable read possible while writes are happening.
// A sketch of the mechanism, not the JDK source, in the same shape. private volatile Object[] array = new Object[0]; // readers see one version private final Object lock = new Object(); // writers take turns here void add(Object element) { synchronized (lock) { Object[] current = array; Object[] next = Arrays.copyOf(current, current.length + 1); next[current.length] = element; array = next; // the volatile publish } }
- Writes serialize among themselves. One internal lock, held only for the duration of a copy.
- Reads take no lock at all.
get,size,containsand iteration read the published array. - One new array per mutation. Never an in-place edit, so a published version is immutable for as long as it is held.
- The publish is the synchronization. The volatile write and the volatile read of the reference are what make a finished copy visible.
Writes copy the whole array; reads never wait. The lock is on the write side, and the read side sees whichever version was current when it looked.
CopyOnWriteArrayList · versioned arrays
one volatile reference, one fresh array per write
reader · snapshot iterator
Captured the reference when the iterator was created, and reads only from it.
The walk finishes having seen exactly these elements, and no write can make it throw.
volatile array reference
Points at the newest complete version. A read takes it and is done.
Creating an iterator is O(1): it captures this reference and nothing else.
the writer, in time order
lock, copy the current array, publishEvery arrow allocates a new array and copies the old one. A published version is never modified, so v1 and v2 stay valid for anyone still holding them, and the collector reclaims them when the last reader lets go.
The asymmetry is the design: writers pay for coordination by copying under a lock, and readers pay nothing because every version they can reach is already complete and frozen. That is what makes iteration snapshot-stable without ever blocking a write.
O(n) writes, O(1) reads, and the sweet spot
A write is proportional to the current size: copying an array of n elements costs n work and one allocation. A read is a volatile read plus an index, and creating an iterator is also O(1) because it only captures the reference.
That ratio sets the workload this class is for. When reads outnumber writes by orders of magnitude, the total cost is dominated by cheap reads and the copies disappear into the noise. When writes are frequent, every mutation copies everything, and a loop of adds becomes quadratic.
Bursts of writers compound the effect. The lock serializes them, but each one still copies from the latest version, so k writes in a burst allocate k arrays whose sizes grow with the list. Nothing is shared between those copies, and nothing can be, because a published version must stay intact.
| Operation | ArrayList | Collections.synchronizedList | CopyOnWriteArrayList |
|---|---|---|---|
| get(i) | O(1), unsynchronized | O(1) under one mutex | O(1), no lock |
| add(e) | amortized O(1) with occasional array growth | amortized O(1) under one mutex | O(n): build a fresh array and publish it |
| iterate | fail-fast, single thread | must hold the lock or risk ConcurrentModificationException | snapshot: never throws, never sees later writes |
| concurrent reads | unsafe | serialized on the mutex | parallel and lock-free |
| write-heavy loop | fine for one thread | correct but serialized | the wrong tool: O(n) per write |
The trade is explicit: writes get more expensive as the list grows, reads never care. That is the right shape for data read on every event and written a few times a day.
A snapshot iterator is a photograph
Starting an iterator copies nothing; it captures the array reference that is current at that moment. Every next() afterwards reads from that array, so the walk shows exactly the elements that existed when the iterator was created. Later writes are invisible to it, and no traversal can ever throw ConcurrentModificationException.
That is also why the iterator is read-only. remove, set and add on it throw UnsupportedOperationException, because the array it walks is shared with everyone else who captured the same version; writing in place would corrupt all of those readers.
The list still supports conditional removal. removeIf, replaceAll, sort and addAllAbsent are methods on the list rather than on the iterator, so each can take the lock, apply the change during one scan, and publish a single new version. removeIf is the tool for what iterator.remove() refuses to do.
- The snapshot is fixed at creation. An element added mid-walk is not in that walk, and an element removed mid-walk is still in it.
- Never a ConcurrentModificationException. Fail-fast iterators detect change; snapshot iterators ignore it entirely.
- `iterator.remove()` throws. So do
setandaddon the iterator: they would have to mutate a shared, published array. - `removeIf` works. It runs as one locked pass over the current version and publishes the result.
A snapshot iterator is a photograph, not a window. It shows the list exactly as it was when the photo was taken, and it cannot write on the list it photographed.
CopyOnWriteArrayList player · one array per write
volatile array reference
v1 · [a, b, c, d]
reader iterator holds
v1 (captured)
iterator over v1
idle
The list holds [a, b, c, d] as version 1. A reader calls iterator(), and the iterator captures the array reference that is current: that capture is the whole of the setup, and no lock is taken.
Scene 1 is a walk that survives two writes without noticing them. Scene 2 is the write the iterator refuses. Scene 3 is the same change done as a list method.
Bulk operations, priced honestly
The methods that modify several elements at once are declared on the list so they can amortize the copy. Each takes the lock, works on one private copy of the current array, and publishes once, so removeIf over ten thousand elements is one copy rather than ten thousand.
The membership helpers are the ones to price carefully. addIfAbsent(e) scans the whole list for an equal element, O(n), and when the element is absent it still copies the array as well. addAllAbsent(c) compares every candidate against the list and against the rest of the batch, so it is O(n) per element examined, and only the first occurrence of a repeated element is added.
- `removeIf(predicate)` removes every match in one locked scan and one publish.
- `replaceAll(operator)` replaces every element in one locked scan and one publish.
- `sort(comparator)` sorts a private copy and publishes it, so readers never see a half-sorted list.
- `addIfAbsent` and `addAllAbsent` scan before they write. Membership checks are linear, and the copy happens only when something is actually added.
- `forEach` walks a snapshot, so an action that also modifies the list does not affect the traversal in progress.
Versioning, churn and no size limit
Every version that is created stays in memory until the last reference to it is dropped. That includes the reference an iterator holds: a long-lived iterator pins the whole array it captured, however much the list has grown since. Readers are cheap to start and can be expensive to keep.
Throughput of writes buys garbage, not just time. A burst of writers allocates one array per mutation, all of them live at once, and the collector has to reclaim the versions nobody is holding. That is a cost measured in pauses rather than in a complexity table, so measure before adopting this class for anything with regular mutation.
There is no capacity knob and no bound either. The list grows as long as elements are added, and each write is proportional to everything currently kept, so the cost model degrades with size in a way ArrayList does not. If growth is unbounded, bound the data at the design level or use a queue with a capacity.
- Old versions are retained by their readers. An iterator you forget to finish keeps its whole array alive.
- Write bursts create garbage proportional to list size times number of writes.
- No capacity, no bound. Nothing stops growth, and growth makes each write larger.
- Short-lived iterators are the intended use. Walk the registry for the current event, then let the snapshot go.
Every version you publish lives until the last reader drops it. Snapshot reads are free to take and can be costly to hold.
equals, hashCode and other O(n) habits
It is still a List, so the List contract applies: equals compares element by element in order, and hashCode follows the list formula of folding the element hashes. Both are computed on each call with no caching, because the contents can change; using a large copy-on-write list as a key in a hash map is therefore an expensive mistake on top of being a mutable one.
The comparison reads through its own iterator, so in the OpenJDK implementation it compares against a version rather than a live view: a concurrent write during equals neither throws nor appears midway through the comparison. That is a stability guarantee, not an atomicity one, so any equality that matters should be taken from one quiescent list or from a copied plain list.
The other linear habits follow from the data structure: contains, indexOf and lastIndexOf scan, toArray returns a fresh copy, and size, isEmpty and get are constant time. If membership is the hot operation, a set is the structure you want, which is exactly what the next topic builds on top of this list.
List semantics with list costs: equals, hashCode, contains and indexOf all scan. Nothing is cached, and nothing should be, because the contents are designed to change.
Choosing it, and not choosing it
The class earns its place where a small collection is read constantly and changed rarely: listener and handler registries, filter chains, feature configuration snapshots, the list of active middleware. Writes there are configuration events, and reads happen on every request or every event.
It is the wrong answer for write-heavy data, for queues, and for stacks. A producer that adds faster than readers walk should use a ConcurrentLinkedQueue, a LinkedBlockingDeque or an ArrayBlockingQueue depending on whether it needs blocking, because those designs move a link per operation rather than copying an array.
- Count the ratio. Reads per write in the thousands: this class. Reads and writes in the same order of magnitude: reach for something else.
- Check what mutation looks like. Occasional add, remove or replace is fine; a loop that adds in bulk is not, because every iteration copies.
- Check who holds iterators. A snapshot is cheap to create and pins a version while it lives, so long-lived walks deserve a copy of their own.
- Check membership operations. If
containsoraddIfAbsentdominates, a concurrent set or map is the structure you actually want. - Check for a bound. If the list can grow without limit, decide what stops it, because nothing in the class will.
Read-mostly registry with writes measured in minutes: yes. Anything busier: a queue or a concurrent map.
The remove button that throws
A snapshot iterator cannot remove. remove(), set() and add() on it throw UnsupportedOperationException, because the array it walks is shared with every other holder of that version and writing in place would corrupt all of them. The same design also means a write during a walk is simply invisible: add an element mid-iteration and the walk finishes without it, which is correct and surprising in equal measure. When the change is meant to affect the data rather than one walk, use removeIf, replaceAll or sort, which the list implements as one locked copy.
Interview angles
How does CopyOnWriteArrayList give lock-free reads?+
All state is one array behind a volatile reference. A read takes the reference and indexes into it, so it sees one consistent version without any lock. A write takes an internal lock, copies the array with the change applied, and publishes the new array; the publish is the only synchronization a reader ever interacts with.
What does remove() on its iterator do?+
Throws UnsupportedOperationException, along with set and add. The iterator holds an array shared with every other holder of that version, so it cannot be written in place. removeIf and replaceAll work because they are list methods: one lock, one scan, one copy.
Common misconception: That snapshot iterators are strictly more capable than fail-fast ones. They are safer to read and unable to write.
When is it the right collection?+
Read-mostly data with rare writes: listener registries, configuration snapshots, anything iterated on every event and written on every deployment. Reads are a volatile read plus an index; writes copy the array under a lock.
When is it the wrong collection?+
Write-heavy workloads, queues and stacks. Each write copies the entire array, so a loop of adds is quadratic. A queue is better served by ConcurrentLinkedQueue, LinkedBlockingDeque or ArrayBlockingQueue depending on whether the consumer should block.
What do addIfAbsent and removeIf cost?+
addIfAbsent scans for an equal element, O(n), and copies the array when it does add. removeIf is a list method: one lock acquisition, one scan, one publish, which is why it can do what iterator.remove cannot.
Does it have a size limit?+
No. There is no capacity to configure and no bound to reach; every write builds an array one element longer, so cost tracks size and the memory bill grows until you stop adding. If growth is unbounded, bound the data at the design level or use a queue with a capacity.