Video in progress
When is CopyOnWriteArrayList the right choice, and when is it a bad one?
It copies the whole array on every write, while reads and iteration are lock-free. So it is great for small lists with lots of reads and very few writes, such as a list of listeners.
📖 Answer
The internals are simple: add creates a new array, copies the old elements, adds the new one and swaps the reference. Threads that are reading keep seeing the old array.
A good place:
private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
void publish(Order o) {
for (OrderListener l : listeners) { // no ConcurrentModificationException
l.onOrder(o);
}
}
Listeners are added at application start and then read thousands of times, which is ideal.
A bad place: a big list that is written often. With hundreds of add calls per second on a list of 100,000 elements, each one copies 100,000 elements and puts heavy pressure on the GC.
One more subtle point: the iterator sees a "snapshot". An element added during iteration is not visible within that loop, and iterator.remove() throws an UnsupportedOperationException.
For write-heavy cases, look at ConcurrentLinkedQueue, ConcurrentHashMap or Collections.synchronizedList.
Sign up to mark studied questions and save your progress.