Video in progress
How does CopyOnWriteArrayList work, and where does it make sense to use it?
On every write (add, set, remove) a full copy of the internal array is made, while reads work on the old array without a lock. So it is meant for lists that rarely change but are read a lot, such as listeners or a configuration list.
📖 Answer
List<EventListener> listeners = new CopyOnWriteArrayList<>();
// rare: at application startup
listeners.add(new AuditListener());
// very frequent, from many threads
for (EventListener l : listeners) {
l.onEvent(event);
}
The iterator works on a "snapshot" of the array from the moment it was created. If another thread adds a listener during iteration, there is no ConcurrentModificationException; the iterator just doesn't see the new element. iterator.remove() is not supported.
When it is a bad choice:
- a list that is written often: for a list of 10,000 elements, every
addcopies 10,000 references; - using it as a queue: for that there are
ConcurrentLinkedQueueor aBlockingQueue; - a big list: every write allocates a new array, which puts load on the GC.
On one project, CopyOnWriteArrayList was used to keep the last 1000 events. With hundreds of add calls per second, the allocation rate shot up and GC pauses became more frequent. After switching to ArrayDeque + a lock, the problem went away.
Sign up to mark studied questions and save your progress.