liveBook · Manning

CopyOnWriteArrayList

As explained in 100 Java Mistakes and How to Avoid Them

CopyOnWriteArrayList is a thread-safe Java list implementation that copies its backing array whenever the list is modified and provides iterators over a snapshot.

CopyOnWriteArrayList is a thread-safe Java list that copies its internal array on every modification. Iterators read the collection state captured when they are created, so iteration can tolerate concurrent changes. section 8.8

Use it when modifications during iteration are expected but uncommon and later changes need not appear in the current traversal. Avoid assuming it is automatically faster; benchmark against copying the collection for iteration. section 8.8

Keep these iteration rules in mind:

  • Treat forEach() and stream operations as iteration; modifying the traversed collection can still break the operation. section 8.8
  • Choose snapshot iteration only when subsequent modifications do not need to be observed. section 8.8
for (String element : new ArrayList<>(collection)) {
  … // Use the element; modify the collection.
}

Shows the alternative of iterating over a copied collection before modifying the original. section 8.8

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains copy-on-write and iterator snapshots, but defers performance choice to workload-specific benchmarking.
Examples
Uses modified ArrayList loops and copied-collection iteration as contrasting examples.
What it assumes
Assumes familiarity with Java collections, loops, iterators, forEach, and streams.
What you can do after
Apply snapshot iteration and choose between CopyOnWriteArrayList and collection copying for modification-heavy traversals.
How it connects
Links iteration with iterators, forEach, streams, ArrayList, and concurrent modification.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.