Skip to main content
InterviewHubPRO
Section Overview
Q13

Question 13 of 50

Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

26%
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:

  1. Zero Locking on Iteration: Iterators operate on an immutable snapshot taken at the exact millisecond the iterator was created. It will never throw ConcurrentModificationException.
  2. 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 volatile array 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!
}