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
