Lesson · Concurrent Collections
CopyOnWriteArraySet: the read-mostly Set
11 min readCopyOnWriteArraySet
A Set built on an array: membership is an equals scan, and every write replaces the whole array. It is exactly right for a subscriber list that is read on every event and written almost never, and exactly wrong once the set grows or contains moves into a hot loop.
The list that throws during delivery
Every event bus has the same collection: subscribers registered at startup, notified on every event, almost never changed. A plain ArrayList handles that fine until the event where one handler adds or removes another handler, and the delivery loop dies halfway through.
private final List<Handler> handlers = new ArrayList<>(); public void update(State s) { for (Handler h : handlers) { h.onState(s); // one handler calls add/remove here -> ConcurrentModificationException } }
Reads pay nothing, writes pay a copy. If the read-to-write ratio is the reason you are reading this, that trade is the whole design.
A thin Set over a copy-on-write array
CopyOnWriteArraySet is a facade. It holds a private CopyOnWriteArrayList and forwards every operation to it; there is no second data structure and no hash table anywhere in the class.
| Set call | Forwards to | Cost |
|---|---|---|
| add(e) | list.addIfAbsent(e) | O(n) scan, plus a copy when the element is new |
| contains(o) | list.contains(o) | O(n) equals scan |
| remove(o) | list.remove(o) | O(n) scan, plus a copy when found |
| iterator() | list.iterator() | snapshot of the array at that moment |
| addAll(c) | list.addAllAbsent(c) | one copy for the whole batch of new elements |
| equals(o) | a membership comparison against any Set | O(n) to O(n squared) for a different Set implementation |
There is no hashing in here. The array is the membership test, and that single fact explains every cost in the table.
CopyOnWriteArraySet · anatomy
a Set facade over one array
CopyOnWriteArraySet
Set contract, array storageCopyOnWriteArrayList al
writes copy the whole arrayEvery mutation builds a new array and swaps the reference; reads just take the current reference.
snapshot reader
The reader keeps walking A while the writer moves to B, so nothing can interrupt it.
iteration never throwscontains("Ben")
A hit stops at the match; a miss compares against every element before answering false.
O(n) per checkSnapshots: delivery that cannot fail
iterator() captures the array reference the list holds at that moment. Writes never touch that array: they copy it, change the copy, and swap the reference. An iteration in flight therefore walks a frozen snapshot, and no writer can disturb it.
That is why ConcurrentModificationException is impossible here, and why the iterator refuses remove(). The snapshot is not connected to the live set, so a subscriber that leaves in the middle of a dispatch still receives the event in flight; the removal takes effect for the next dispatch.
- Snapshot, not live view: the loop sees the membership from the moment iterator() ran.
- remove() is unsupported: the iterator throws UnsupportedOperationException, because there is nothing live to remove from.
- Stale for exactly one dispatch: a joiner waits for the next event, a leaver still gets the event in flight.
- Visibility without locks: the backing reference is volatile, so a reader that starts a traversal sees a fully built array, never a half-written one.
Staleness for one dispatch is the feature. You trade a live view for a traversal that cannot fail.
Subscriber registry · delivery during writes
backing array · insertion order
live iterator snapshot
no iteration in flight
cost of each call · the selected backing is written in accent
contains(o)
array set: O(n) equals scan
key set: average O(1) probe
add(e) / remove(o)
array set: O(n) scan + a full array copy
key set: average O(1), no copy
iterator()
array set: frozen snapshot, no remove()
key set: weakly consistent view
iteration order
array set: insertion order
key set: unspecified
null element
array set: one null allowed
key set: rejected with NPE
An event bus keeps three subscribers in a CopyOnWriteArraySet: Ada, Ben, Cy. Delivery runs on every event; subscribes and unsubscribes happen at startup and shutdown. That ratio is what the class is built for.
The bill: linear writes, free reads
A write scans (for a duplicate, or for the element being removed), then copies the entire array. Removing the last element still copies every remaining element: the array shrinks by one reference and is rebuilt whole. The copy happens under the list's write lock, so writers also serialise with each other.
Reads are the opposite: capture the reference, walk it, no lock and no coordination with writers. Iteration order is insertion order, which is a small bonus for anything that dispatches subscribers or event handlers in registration order.
- Write path: lock, scan, copy n references, swap the reference. O(n) time and a fresh array.
- Read path: one volatile read, then array indexing. No lock, nothing to retry.
- Memory: during a write two arrays exist at once, so peak usage is roughly double the live set.
- n is a design input: the class is meant for sets that stay small; its own javadoc says so.
The class assumes small n. Past a few thousand elements, every unsubscribe is a visible amount of copying.
contains is a scan, and a miss is the worst case
contains is the quiet cost. It is a linear equals scan with no hash involved, and a miss pays the full price: the method must compare against every element before it can answer false. A hit stops at the match, so absence is the expensive answer.
In a subscriber set that is fine, because delivery iterates rather than queries. A hot loop that asks whether an item is registered once per processed item is a different shape: that is n comparisons per call, which is the workload this class was never meant to serve.
// Fine: delivery walks the set once per event. for (Handler h : handlers) h.onState(s); // Not fine: membership inside a hot loop, n equals calls per check. if (handlers.contains(candidate)) { /* ... */ }
Absence is the worst case: contains answers false only after comparing against every element.
The modern alternative: ConcurrentHashMap.newKeySet()
Since Java 8 the hash-based option is one line: ConcurrentHashMap.newKeySet() returns a Set view over a map's key set. It is a real Set, it is thread-safe, and add, contains and remove are O(1) on average with no copying anywhere.
The trade flips completely. Nothing is copied on a write; the iterator is weakly consistent instead of a snapshot (it never throws, but it may or may not see a write that happens mid-walk); iteration order is unspecified; and null is rejected, where the array set tolerates a single null element.
Before Java 8 the fallback was Collections.synchronizedSet, which locks every read and still demands manual synchronization to iterate. That is the version many people remember when they call concurrent sets slow.
| Question | CopyOnWriteArraySet | ConcurrentHashMap.newKeySet() |
|---|---|---|
| contains(o) | O(n) equals scan | average O(1) hash probe |
| add(e) / remove(o) | O(n) scan plus an array copy | average O(1), the table is not copied |
| Iterate while another thread writes | frozen snapshot, the write is invisible | weakly consistent, the write may or may not be visible |
| ConcurrentModificationException | never | never |
| Iteration order | insertion order | unspecified |
| null element | one null allowed | rejected with NullPointerException |
| Best at | small sets, rare writes, frequent traversal | larger sets, hot membership checks, frequent writes |
Small and read-mostly: array. Growing or query-heavy: hash. That is the whole decision, and both classes are one line to construct.
The decision, in five questions
Run these in order. The first one that fires decides, and none of them require measuring to answer.
- Count the elements. Tens or low hundreds: the array set is still comfortable. Thousands and climbing: go hash-based.
- Find every contains call. Membership inside a per-item loop decides against the array set regardless of size, because each check costs a scan.
- Find every write. Subscribes and unsubscribes at startup or shutdown are fine; writes that track request traffic make the copy-per-write the wrong bill.
- Check the iteration contract you want. A frozen snapshot suits dispatch (a leaver still gets the event in flight). A weakly consistent view suits scans that tolerate missing a just-added element.
- Check for null. One null element is legal in the array set and illegal in the key set, which matters when a sentinel value is part of the design.
Pick by access pattern, not by novelty. The array set earns its place when reads vastly outnumber writes and the set stays small; the key set earns it everywhere else.
The unsubscribe that broke dispatch
The ArrayList version fails where you least want it to: halfway through delivering an event, because one handler unsubscribed another. Iteration over the array set cannot fail that way, and it can surprise you in the opposite direction: the subscriber that just left still receives the event in flight, because the loop is walking the membership from before the removal. Both behaviours come from the same rule, safety over freshness for exactly one dispatch. If a handler must never see an event after leaving, check membership inside the loop or remove it between dispatches.
Interview angles
Why is contains O(n) in CopyOnWriteArraySet?+
It delegates to the backing CopyOnWriteArrayList, which is just an array with no hash index: contains runs an equals scan. Add and remove are linear for the same reason, and the class javadoc states that its add, remove and contains are proportional to the size of the set.
Only the traversal side is cheap. Iterators walk a frozen snapshot with no lock and no allocation per element, which is exactly the workload the class was designed for.
What does an iterator see when another thread writes during a traversal?+
The snapshot: the array reference captured when iterator() was called. The writer copies the array and swaps the reference, so the loop finishes on the old one and never throws ConcurrentModificationException.
That is also why remove() on the iterator throws UnsupportedOperationException: the snapshot cannot be edited, and the class does not pretend otherwise.
Common misconception: Copy-on-write means the iterator sees the newest elements as they appear.
Two threads add the same new element at the same time. What happens?+
Exactly one add returns true. addIfAbsent performs the duplicate check and the array swap under the same lock, so the second thread finds the element present and returns false without copying anything.
When is CopyOnWriteArraySet the wrong choice?+
When the set grows large, when contains is called in a hot loop, or when writes are frequent. Each of those turns a design assumption into a per-call cost: a linear scan or a full array copy.
Follow-up: What would you reach for instead? ConcurrentHashMap.newKeySet(): O(1) average operations, no copying, and a weakly consistent iterator.
Why does equals work against any Set, even one with a different iteration order?+
equals is defined in Set terms: it compares membership against any Set, matching elements pair by pair, and hashCode follows the Set contract, so equal sets hash equally.
The comparison costs O(n) to O(n squared) against a Set of a different implementation. The source comment for that comparison says it is acceptable because the class expects small sets.