☕ Java Intermediate

What is CopyOnWriteArrayList in Java?

Answer

CopyOnWriteArrayList is a thread-safe variant of ArrayList where all mutative operations (add, set, remove) are implemented by making a fresh copy of the underlying array. This means reads never block and do not require synchronization — very efficient when reads vastly outnumber writes. The iterator of CopyOnWriteArrayList is fail-safe — it operates on a snapshot of the array at the time the iterator was created and never throws ConcurrentModificationException. However, it is expensive for write-heavy workloads because of the array copying. Best suited for listener/observer lists where iteration is far more common than modification.