Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
What is CopyOnWriteArrayList and when should you choose it over synchronized lists?
senior LevelCode ExampleSystem DesignData Structures
In Simple Words:
A CopyOnWriteArrayList is a thread-safe List implementation where every write operation (add, set, remove) creates a brand-new internal copy of the underlying array.
Ideal Use Case:
- Read-Heavy, Write-Rare: Perfect for observer/listener lists, system configuration caches, or routing tables where iterations happen thousands of times per second but mutations happen infrequently.
Key Mechanics:
- Zero Locking on Iteration: Iterators operate on an immutable snapshot taken at the exact millisecond the iterator was created. It will never throw
ConcurrentModificationException. - Expensive Writes: Mutating operations acquire a reentrant lock, allocate an entirely new array of size $N+1$, copy all existing elements, insert the new element, and point the
volatilearray reference to the new array.
java
CopyOnWriteArrayList<EventListener> listeners = new CopyOnWriteArrayList<>();
// Fast, non-blocking iteration:
for (EventListener listener : listeners) {
listener.onEvent(event); // Snapshot iteration; no locks, no exceptions!
}