CopyOnWriteArrayList
Definition:
A thread-safe list that publishes a replacement backing array for structural changes.
Explanation:
A listener registry dispatches one event while another thread changes the subscribers. The dispatch should complete against a stable membership list. CopyOnWriteArrayList makes that snapshot cheap to obtain and shifts the cost to writes.
Illustration image:
Example:
static void copyOnWriteArrayList() {
var listeners = new CopyOnWriteArrayList<>(List.of("email", "sms"));
Iterator<String> snapshot = listeners.iterator();
listeners.remove("email");
listeners.add("push");
var observed = new ArrayList<String>();
snapshot.forEachRemaining(observed::add);
check(observed.equals(List.of("email", "sms")));
check(listeners.equals(List.of("sms", "push")));
}Expected result. The snapshot returns [email, sms]. A fresh list read returns [sms, push].
Internal working:
Inside OpenJDK
The list holds a volatile reference to its current backing array. Structural writes serialize under a lock, prepare a replacement array and publish it. Iterators capture the current array reference when constructed. The writer never edits the captured array in place, so the iterator can read it without holding the writer lock.
Trace the example
Create the iterator when the array holds email and sms. Remove email and add push; subsequent readers see sms and push. The old iterator still reads email and sms. Objects are shared: copying the array does not clone mutable listeners.
Cost and limits
Indexed access is constant time. Appending, inserting or removing usually copies O(n) references, and long-lived iterators can keep old arrays alive. Iterator mutation methods are unsupported. Choose this for small read-mostly lists; for frequent changes, measure copy and allocation rates.
Interview questions:
What does an iterator see after someone adds an element?
It continues to traverse the original array snapshot; a new iterator sees the published replacement.