When ConcurrentModificationException Is Thrown
You'll learn: The exact conditions that cause fail-fast iterators to throw ConcurrentModificationException during iteration.
The Triggering Condition
A ConcurrentModificationException is thrown when an iterator detects that the collection's structure has been modified after the iterator was created, but not through the iterator itself. This happens because the iterator tracks the collection's modCount (modification count) at creation time and compares it on each operation.
Think of it like a library checkout: When you check out a book, the librarian notes the catalog version number. If you return later and the version has changed (books added/removed by someone else), the librarian knows the catalog was modified while you were gone.
Exact Trigger Points
The exception is thrown when:
- You modify the collection directly (using
add(),remove(),clear(), etc.) while iterating - The iterator performs its next operation (
hasNext(),next(), or its ownremove()) - The stored
modCountdoesn't match the collection's currentmodCount
The exception typically occurs on the next call to hasNext() or next(), not immediately when you modify the collection.
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
Iterator<String> it = list.iterator();
it.next(); // "A" - fine so far
list.remove("B"); // Direct modification - modCount changes!
it.next(); // ConcurrentModificationException thrown HERE
Important: Only structural modifications trigger this—changes that add/remove elements. Simply reading values or using the iterator's own remove() method is safe because the iterator updates its expected modCount.
Key Takeaway: ConcurrentModificationException is thrown when an iterator detects that the collection's modCount has changed unexpectedly, which happens when you modify the collection directly (outside the iterator) during iteration.