SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 13 / 25

Middle

When does ConcurrentModificationException happen, and how do fail-fast and fail-safe iterators differ?

Short answer

A fail-fast iterator remembers how many times the collection was modified (modCount) when created. If the collection is changed not through that iterator, next() throws ConcurrentModificationException, even with just one thread.

modCount growsupdates bothCreate iteratorremember modCountlist.remove(x)inside for-eachnext() sees mismatchConcurrentModificationExceptionit.remove() or removeIfNo error

3 points to say:

  1. Removing inside for-each is the most common cause.
  2. Use removeIf or iterator.remove().
  3. Fail-fast does not protect multithreading.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.