Java Concurrency Interview

Concurrent collections question 69 of 180 mid

What is the iteration behaviour of a concurrent collection, and what is ConcurrentModificationException?

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.

collections iteration

Quiz yourself on Concurrent collections Suggest a correction