Concurrent collections question 69 of 180 mid
What is the iteration behaviour of a concurrent collection, and what is ConcurrentModificationException?
- Concurrent collections throw CME too, just less often
- Correct: Their iterators are weakly consistent: never throw CME, may or may not reflect changes made after creation, and traverse each element once
- They snapshot the whole collection
- They lock the collection during iteration
HashMap and ArrayList iterators are fail-fast: they keep a modification counter and throw
ConcurrentModificationException when they notice a change. That is a bug detector, not a thread
safety mechanism, and it is best-effort even single threaded (removing an element via the collection
inside a for-each is the usual trigger).
Concurrent collections instead promise weak consistency. You will see every element that was present for the whole traversal, you may or may not see concurrent insertions, and nothing throws. The price is that an iteration is not a snapshot, so counting with it gives an approximation.
CopyOnWriteArrayList is the exception: its iterator is a true immutable snapshot of the array at
creation time, so it never sees later changes and does not support remove.
Quiz yourself on Concurrent collections Suggest a correction