All topics
library
advanced

CopyOnWrite Collections

Use CopyOnWriteArrayList and CopyOnWriteArraySet for read-heavy, write-rare thread-safe scenarios.

CopyOnWriteArrayList and CopyOnWriteArraySet are thread-safe collections that create a new copy of the underlying array on every write (add, set, remove). Reads are lock-free and fast.

Like a shared Google Doc where edits create a new version. Readers always see a consistent version. Editors pay the cost of copying, but readers are never blocked.

Key Concepts

1
How it works: the internal array is volatile. Writes acquire a lock, copy the entire array, modify the copy, and swap the reference. Reads see either the old or new array — no synchronization needed.
2
Advantages: - No ConcurrentModificationException during iteration - Iterators work on a snapshot — safe to modify the collection while iterating - Reads are very fast (no locking, no volatile reads per element)
3
Disadvantages: - Writes are expensive: O(n) copy on every mutation - Memory: briefly holds two copies of the array - Not suitable for write-heavy workloads
4
Ideal use cases: - Event listener lists (listeners rarely change, invoked frequently) - Configuration caches (written once, read many times) - Observer pattern (observers list is read far more than modified)
5
The iterator returned by CopyOnWriteArrayList doesn't support remove(), set(), or add() — it's a read-only snapshot.