skip to content

Fail-Fast vs Fail-Safe Iterators

Fail-fast iterators track modCount and throw ConcurrentModificationException the moment the collection changes structurally underneath them; weakly consistent iterators from the concurrent collections tolerate it. Interviewers ask what causes CME, including the single-threaded case.

part ofJavaread it →
on this pageshow

questions

5

What is a ConcurrentModificationException, and when does it typically occur?

level: juniorimportance: must knowfreq 78%

answer

  1. modCount vs expectedModCount
  2. structural = add/remove, or perturbs iteration
  3. usually single-threaded for-each bug
  4. fix: Iterator.remove / removeIf / copy
  5. fail-fast = throw at the next check

basics

~20 s

ConcurrentModificationException is the unchecked exception a fail-fast iterator throws, on a best-effort basis, when its collection is structurally modified outside the iterator during a loop. The classic case is list.remove(x) inside a for-each, with no threads involved.

solid answer

~50 s

ConcurrentModificationException (CME) signals that a collection was structurally modified while it was being iterated, in a way the iterator didn't expect. 'Structural' means adding or removing elements, or otherwise disturbing an iteration in progress as ArrayList.sort does, not just updating an existing element's value. The most common cause has nothing to do with multiple threads: it's modifying the collection directly (e.g. list.remove(x)) inside a for-each loop over that same collection. The for-each loop uses an iterator under the hood, and that iterator detects the modification on its next next() or remove() call and throws. hasNext() runs no check, so one removal while the loop is on an ArrayList's second-to-last element ends it silently with the last element unvisited. The fix is to either iterate over a copy, use Iterator.remove(), use removeIf(), or collect-then-modify. Despite the 'Concurrent' name, it is most often a single-threaded bug.

code

java · 15 lines
java
List<String> list = new ArrayList<>(List.of("a", "b", "c"));

// Throws ConcurrentModificationException on the next iteration
for (String s : list) {
    if (s.equals("a")) list.remove(s);
}

// Alternative (Java 8+): no loop left to interfere with
list.removeIf(s -> s.equals("a"));

// Alternative: remove through the iterator itself
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    if (it.next().equals("a")) it.remove();
}

go deeper

for a junior

Recognizes the classic 'remove inside a for-each' bug and knows the standard fix (Iterator.remove or removeIf). Knows CME is usually a single-threaded mistake, not a threading issue.

for a middle

Can explain modCount/expectedModCount and what 'structural modification' precisely means (adding, removing or otherwise perturbing iteration, not a value change). Lists multiple correct fixes and knows set() is safe.

for a senior

Explains why fail-fast exists (avoid silent wrong results), that detection is best-effort and not a concurrency guarantee, and when to switch to concurrent collections instead.

for a principal

Frames CME as a bug detector, contrasts fail-fast vs weakly-consistent iterators as a library trade-off, and guides teams on choosing data structures for concurrent access patterns.

## The problem in one picture In Java, a **collection** is an object that holds a group of elements (a `List`, `Set`, `Map`, etc.). To visit every element you use an **iterator** — an object that walks the collection one element at a time via `hasNext()` and `next()`. The `for (T x : collection)` syntax (the **for-each loop**) is just syntactic sugar: the compiler turns it into an explicit iterator loop. **ConcurrentModificationException (CME)** is a `RuntimeException` (unchecked — you don't have to declare or catch it) thrown when the collection is **structurally modified** while an iterator is walking it. ## What 'structural modification' means A **structural modification** adds or removes elements (`add`, `remove`, `clear`, `addAll`, etc.) or otherwise perturbs the collection so that an iteration in progress could go wrong. A changed `size()` is the usual sign, not the definition: `ArrayList.sort` counts with the size unchanged, and in an access-ordered `LinkedHashMap` even `get` counts. **Not** structural: replacing an existing element's value in place, e.g. `list.set(i, newValue)` or `put(existingKey, newValue)` on a `HashMap` — these do **not** trigger CME. ## The classic bug (single-threaded) ```java List<String> list = new ArrayList<>(List.of("a", "b", "c")); for (String s : list) { // hidden iterator if (s.equals("a")) { list.remove(s); // structural modification of the SAME list } } // throws ConcurrentModificationException on the next iteration ``` Notice: **no threads involved.** You modified the list through the *list* while iterating through the *iterator*; the iterator notices the change underneath it and refuses to continue, because continuing could skip elements or read garbage. **Not every position throws.** Change the test to `"b"`, the second-to-last element, and the loop ends silently with `[a, c]`: `ArrayList`'s `hasNext()` is only `cursor != size` and runs no check, so it returns false before `next()` can look, and `"c"` is never visited. That is a missed element, not a safe removal. ## How the iterator notices (the mechanism) Most JDK collections keep an internal counter, **`modCount`** (modification count), incremented on every structural change. When you create an iterator it snapshots that value into `expectedModCount`. On each `next()` (and `remove()`) the iterator runs a check, `checkForComodification()` in `ArrayList`: if `modCount != expectedModCount`, the collection changed behind its back, so it throws CME. This is called a **fail-fast** iterator: it fails at its next check, loudly, rather than carrying on and producing wrong results. ## Why fail fast at all? If the iterator quietly kept going after a removal, it could skip the element right after the removed one, or index past the end. Surfacing a clear exception at the loop's next step, close to the misuse, is far better than a subtle, data-dependent bug. CME is a **bug detector**, not a feature you should catch and ignore. ## The correct fixes 1. **`Iterator.remove()`** — the iterator's own remove keeps `expectedModCount` in sync: ```java Iterator<String> it = list.iterator(); while (it.hasNext()) { if (it.next().equals("b")) it.remove(); } ``` 2. **`Collection.removeIf(predicate)`** (Java 8+) — concise and safe as a replacement for the loop. Called inside a for-each over the same list, it is one more outside modification: if it removes something, the next `next()` throws, provided the loop reaches one. 3. **Iterate a copy, modify the original:** `for (String s : new ArrayList<>(list)) { ... }`. 4. **Collect then modify:** gather the to-remove items in a separate list, then `removeAll`. ## The 'Concurrent' in the name is misleading The same exception *can* fire when one thread iterates while another structurally modifies the collection — but fail-fast detection is **best-effort and not guaranteed** for true concurrency (the `modCount` read isn't synchronized). So you must never *rely* on CME for thread-safety; for genuine multi-threaded access use the concurrent collections (`ConcurrentHashMap` with its **weakly consistent** iterators, `CopyOnWriteArrayList` with its **snapshot** iterators), whose iterators never throw CME. ## CME with no iterator in sight Iterators are the classic source, not the only one: the exception's contract covers any method that detects a modification it does not permit. `HashMap.computeIfAbsent`, `computeIfPresent`, `compute` and `merge` throw it on a best-effort basis when the function you pass modifies the map, and `TreeMap` does the same since JDK 15. `ArrayList.removeIf` throws it when the predicate structurally modifies the list. All of this holds on both JDK 25 and JDK 27.

  • Does calling list.set(i, value) inside a for-each loop throw CME?
    No. set() only replaces an existing element's value, which ArrayList's Javadoc says is not a structural modification, so it does not bump modCount. (Note: for-each gives you no index, so set is awkward there anyway; the point is set() itself is CME-safe.)
  • Is CME a checked or unchecked exception?
    Unchecked — it extends RuntimeException, so you are not required to declare or catch it. Its Javadoc says it should be used only to detect bugs, not as something a correct program depends on.

Like counting people in a room from a clipboard list: if someone walks out (or in) mid-count, your tally is now wrong, so you stop and raise your hand rather than report a bad number.

  • Thinking CME only happens with multiple threads — it's usually a single-threaded for-each bug.
  • Believing list.set() during iteration causes CME — it doesn't, because it isn't a structural modification.
  • Catching CME and ignoring/retrying instead of fixing the modify-while-iterating code.
  • Assuming the JVM guarantees CME on every concurrent modification — detection is best-effort only.

ConcurrentModificationException
Java 1.2
Collection.removeIf
Java 1.8

Assumes JDK 27; JDK 25 LTS behaves the same. Collection.removeIf arrived in 1.8. TreeMap's compute and merge methods throw this exception since JDK 15.

context

open as a page

How does a fail-fast iterator in java.util, such as ArrayList's, detect concurrent modification internally?

level: middleimportance: must knowfreq 62%

basics

~20 s

The collection keeps a counter called modCount that goes up every time you add or remove an element. When you make an iterator, it remembers that number. On each next() it compares them; if they differ, the collection changed behind its back, so it throws.

open as a page

You need to remove elements from a List while iterating it. What are the correct ways, and what are the pitfalls of each?

level: middleimportance: must knowfreq 70%

basics

~20 s

Don't call list.remove() inside a for-each loop: it usually throws ConcurrentModificationException and can silently skip an element. Use removeIf() with a condition, or an explicit Iterator and iterator.remove(). Looping over a copy and removing from the original also works.

open as a page

How do fail-fast iterators differ from fail-safe (weakly consistent or snapshot) iterators in Java, and which collections use each?

level: seniorimportance: should knowfreq 58%

basics

~20 s

Fail-fast iterators (ArrayList, HashMap) throw ConcurrentModificationException, best effort, when the collection is structurally modified mid-loop. Fail-safe ones (CopyOnWriteArrayList, ConcurrentHashMap) never throw it: they walk a snapshot or tolerate changes, and may miss the latest updates.

open as a page

Why did the Java library designers make most collections fail-fast rather than fail-safe, and when does that decision break down?

level: principalimportance: nice to knowfreq 30%

basics

~20 s

The docs state no motive; the usual reading is that single-threaded use is the common case, so iteration stays cheap and misuse usually fails loudly at the next check. It breaks down when collections are shared across threads, where concurrent collections fit instead.

open as a page