intermediateConcurrency Utilities

How does CopyOnWriteArrayList work internally, and when is it appropriate to use?

Every mutating operation on a CopyOnWriteArrayList, such as add(), set(), or remove(), copies the entire backing array, applies the change to that new copy, and then atomically swaps the internal reference to point at the new array. Because of this, reads never need any locking at all -- they simply read whatever array reference is currently visible and always see a fully consistent snapshot. Iteration is similarly snapshot-based: a ConcurrentModificationException can never occur, but any mutation that happens after an iterator was created will not be visible to that iterator. This makes CopyOnWriteArrayList appropriate when reads vastly outnumber writes, such as with event listener lists, routing tables, or observer lists, where the occasional O(n) cost of copying the array on a write is an acceptable tradeoff. It should be avoided for lists that are written to frequently or that are very large, since copying tens of thousands of elements on every single write becomes prohibitively expensive.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What is a deadlock, and what are the four Coffman conditions that must hold for one to occur?← Back to all Java Concurrency & Multithreading questions