Fail-Fast vs Fail-Safe Iterators

Difficulty: Intermediate

Question

What are fail-fast and fail-safe iterators? Why do you get ConcurrentModificationException and how do you avoid it?

Answer

You have probably seen ConcurrentModificationException at least once, usually when you tried to remove something from a list inside a for-each loop. Let me explain exactly why it happens, because understanding the mechanism is what interviewers want.

Most collections in java.util, such as ArrayList, HashMap, HashSet and LinkedList, have fail-fast iterators. Each of these collections keeps an internal counter called modCount that increments on every structural modification (add, remove, clear, resize). When an iterator is created, it remembers the modCount as expectedModCount. On every call to next (and remove), the iterator compares its expected value to the collection's current modCount. If they differ, someone changed the collection behind the iterator's back, and it throws ConcurrentModificationException immediately. The idea is to fail quickly rather than continue with unpredictable behaviour.

Notice that this has nothing to do with multiple threads specifically. The most common cause is a single thread modifying the list inside its own for-each loop, because the enhanced for loop uses an Iterator behind the scenes. Calling list.remove(x) changes modCount, but the iterator does not know, so the next call to next throws.

There is a famous quirk here. If you remove the second-to-last element in a for-each loop, no exception is thrown. After the removal, the size drops by one, the cursor equals the new size, hasNext returns false, and the loop ends without calling next. That is why the exception is a best effort and must never be used as program logic; it is meant only for detecting bugs.

How do you avoid it? The correct ways are: use the iterator's own remove method (it updates expectedModCount), use removeIf (Java 8), use replaceAll or streams to build a new filtered list, or collect items to remove in a separate list and call removeAll afterwards. For plain index loops, iterating backward works when removing.

Fail-safe (more precisely weakly consistent or snapshot) iterators do not throw the exception. These belong to java.util.concurrent. CopyOnWriteArrayList copies the whole underlying array on every write, and its iterator works on the snapshot taken at the moment it was created. Modifications made afterwards do not appear in that iteration, and no exception happens. The cost is that each write is O(n) and uses extra memory, so it suits read-heavy, write-rare data such as listener lists. ConcurrentHashMap and ConcurrentLinkedQueue have weakly consistent iterators: they work on the live structure, never throw, and may or may not show changes made during iteration.

The name fail-safe is a bit of a misnomer; the Java documentation does not use it. The accurate terms are fail-fast and weakly consistent. Mentioning that shows precision.

Also remember: Hashtable's Enumeration is not fail-fast, but its iterator is. And Arrays.asList returns a fixed-size list that throws UnsupportedOperationException on add or remove, a different error that people often confuse with this one.

Code examples

Triggering and avoiding ConcurrentModificationException

import java.util.*;
import java.util.concurrent.*;

public class FailFastDemo {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
        try {
            for (Integer x : list) {
                if (x == 2) {
                    list.remove(x);
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("CME");
        }
        System.out.println(list);

        list.removeIf(x -> x % 2 == 0);
        System.out.println(list);

        List<String> cow = new CopyOnWriteArrayList<>(List.of("a", "b"));
        for (String s : cow) {
            cow.add(s + "!");
        }
        System.out.println(cow);
    }
}

Removing 2 inside the for-each bumps modCount and the next call to next throws, though the removal itself already happened. removeIf is safe. The CopyOnWriteArrayList iterator works on a snapshot, so the additions do not affect the loop or throw.

Key points

Common follow-up questions

Interview tips

Concepts covered

Iterator, ConcurrentModificationException, modCount, CopyOnWriteArrayList

More Core Java & Collections questions