Concurrent collections question 70 of 180 mid
When is CopyOnWriteArrayList the right choice?
- Whenever a list is shared
- Correct: When reads massively outnumber writes and the list is small, such as a listener registry
- When the list is very large
- When you need index-based writes
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.
Quiz yourself on Concurrent collections Suggest a correction