Java Concurrency Interview

Concurrent collections question 70 of 180 mid

When is CopyOnWriteArrayList the right choice?

Every mutation allocates a new array and copies the whole thing, under a lock. Writes are O(n) and produce garbage; reads take no lock at all and never block, because they read a final snapshot reference.

That makes it excellent for listener and subscriber lists: written at startup, read on every event, never large. It is a disaster for anything written in a loop or holding thousands of elements, where each add copies the lot.

The snapshot iterator also has a semantic consequence: a listener added during an event dispatch will not receive that event, which is usually what you want and occasionally a surprise.

collections performance

Quiz yourself on Concurrent collections Suggest a correction