Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Fail Fast Iterator: Behavior and Pitfalls

Java fail-fast iterators rely on modCount to detect concurrent modification. See when ConcurrentModificationException occurs and how to avoid it with iterator.remove(), snapshots, and concurrent collections.

~5 min readJava
#ConcurrentModificationException#modCount#Iterator#Fail-safe
Diagram illustrating a Java fail fast iterator detecting collection modification and throwing ConcurrentModificationException

Java fail-fast iterator behavior is implemented by many collection iterators in the Java Collections Framework. When you create an iterator over a collection and then modify the collection structurally by adding or removing elements from another thread, or from the same thread outside the iterator's own remove method, the iterator can throw ConcurrentModificationException at a later operation such as next(). This is not a bug; it is a deliberate design choice that favors failing early over continuing with possibly inconsistent data.

What Does Fail Fast Mean for Java Iterators?

A fail-fast iterator checks whether the collection has been structurally modified after the iterator was created. If it detects a change, it throws ConcurrentModificationException instead of trying to continue with the iteration. The name refers to the system's preference to stop with a clear error rather than risk corrupted or unpredictable behavior. The iterators of ArrayList, HashMap, LinkedList, and other standard java.util collections use this design; java.util.concurrent collections generally use different, non-fail-fast semantics.

The detection is best-effort, not a guaranteed contract. Java's API documentation says that fail-fast behavior cannot be guaranteed, but common collection implementations do check the modification state and throw when they detect a mismatch. Code should not rely on the exception being thrown at an exact point.

The Mechanism Behind Fail Fast: modCount

Standard Java collections that have fail-fast iterators maintain an integer field called modCount. Structural changes, such as adding, removing, or clearing elements, increment this field. When an iterator is created, it stores the current modCount value as expectedModCount. During iteration, methods such as next() and remove() compare the collection's current modCount with expectedModCount. If the values differ, the iterator throws ConcurrentModificationException.

Here is a simplified illustration of the check inside a typical iterator:

java
public E next() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } // ... return the next element }

The iterator's own remove() method updates expectedModCount after a removal, so a removal made through the iterator does not invalidate that iterator. A direct collection method such as add(), remove(), or clear() does not update expectedModCount, which is why the next check can fail.

When Does ConcurrentModificationException Occur?

The exception occurs when a structural modification is made after an iterator is created and the iterator detects the change. The common scenarios are:

  1. Another thread modifies the collection while one thread is iterating.
  2. The same thread modifies the collection directly with a collection add or remove method instead of using the iterator's own remove.

For example, this code throws an exception on the second call to next():

java
List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (item.equals("a")) { list.remove(item); // Direct removal, not iterator.remove() } }

The list.remove() increments modCount, but the iterator's expectedModCount remains unchanged. The next call to iterator.next() detects the mismatch and throws.

Avoiding Fail Fast Exceptions in Single-Threaded Code

In single-threaded code, the most direct way to remove elements during iteration is to use the iterator's own remove() method. It keeps the iterator's expectedModCount in sync with the collection's modCount.

java
Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (item.equals("a")) { iterator.remove(); // Safe } }

If you need to add elements while iterating, the standard Iterator interface has no add method. You can collect the new elements in a separate list and add them after the loop, or use a ListIterator for a List, because ListIterator.add() supports insertion during iteration.

Another approach is to iterate over a copy of the collection:

java
for (String item : new ArrayList<>(list)) { if (condition) { list.remove(item); } }

Here the loop uses a separate snapshot, so modifications to the original list do not affect the iterator over the copy. Java 8 also provides Collection.removeIf(), which is often the simplest way to remove elements by a predicate without writing an explicit loop.

Fail Fast vs. Fail Safe Iterators

Not all collection iterators fail fast. In java.util.concurrent, iterators follow different rules:

  • CopyOnWriteArrayList returns an iterator over a snapshot of the list's elements at iterator creation. Later structural changes do not affect the snapshot, and it does not throw ConcurrentModificationException.
  • ConcurrentHashMap iterators are weakly consistent. They do not take a full snapshot, and they may or may not reflect modifications made during traversal, but they do not throw ConcurrentModificationException.

The term 'fail safe' is often used informally for these iterators, although the Java API documentation usually describes concurrent collection iterators as 'weakly consistent'.

AspectFail-fast iteratorFail-safe / weakly consistent iterator
Behavior on modificationThrows ConcurrentModificationException when a change is detectedDoes not throw; uses a snapshot or weak consistency
Common collectionsArrayList, HashMap, LinkedListCopyOnWriteArrayList, ConcurrentHashMap
OverheadLow per-iteration checkHigher memory or coordination overhead
Typical useSingle-threaded code or code with explicit synchronizationConcurrent access without a single lock around iteration

Performance and Operational Considerations

Fail-fast iterators add only a small per-iteration cost: typical implementations compare an int field in methods such as next() or remove(). The main benefit is corrective feedback rather than performance. When the check detects an unintended structural modification, it raises a clear exception instead of allowing the iteration to continue with inconsistent state.

Fail-fast behavior is not a substitute for synchronization. If one thread can modify a collection while another thread iterates it, protect the collection with a lock or use a concurrent collection designed for that access pattern.

Handling Concurrent Modifications in Practice

For applications that need to allow concurrent access, choose a collection with suitable semantics. For a list that is read frequently and modified rarely, CopyOnWriteArrayList provides snapshot iteration. For a map, ConcurrentHashMap provides weakly consistent traversal and avoids ConcurrentModificationException.

If you must use a standard collection, synchronize the entire iteration and modification block with the same lock, and use the iterator's methods for removal:

java
synchronized (list) { Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (item.equals("a")) { iterator.remove(); } } }

This is safe only if all code that reads or writes the list uses the same lock. The lock prevents another thread from modifying the collection during the block, while iterator.remove() keeps the iterator's expectedModCount in sync. A direct list.remove() inside the block would still cause the next iterator check to throw, because direct removal does not update expectedModCount.

Another pattern that avoids modifying the collection during iteration is to collect the elements first and remove them afterward:

java
List<String> toRemove = new ArrayList<>(); for (String item : list) { if (item.equals("a")) { toRemove.add(item); } } list.removeAll(toRemove);

Understanding how fail-fast iterators work and when they throw is important for writing reliable Java loops over collections. The modCount mechanism is simple, but it affects how you structure code that changes a collection during iteration. Choosing the right collection type and using the iterator's own methods lets you avoid ConcurrentModificationException while keeping the code predictable.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.