Skip to lesson

Fail-Fast Iterators and ConcurrentModificationException

"Why does this loop throw ConcurrentModificationException?" is a classic written-round and viva question. The interviewer is checking that you know the mechanism, the safe ways to remove, and the one case where the loop does not throw.

modCount: why the exception is thrown

modCount is a counter inside ArrayList and HashMap that goes up on every structural change, one that alters the size. An iterator keeps its own copy and compares the two on each next().

Start with the mechanism. The program removes a name inside a for-each loop and catches the exception, so you can see exactly where it is thrown.

Example 1 · Removing inside for-each throws

ForEachRemoveDemo.javaJava
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
public class ForEachRemoveDemo {    public static void main(String[] args) {        List<String> students = new ArrayList<>(List.of("Asha", "Ravi", "Kiran", "Meena"));        try {            for (String s : students) {                System.out.println("Visiting " + s);                if (s.equals("Ravi")) {                    students.remove(s);   // modCount changes here                }            }        } catch (ConcurrentModificationException e) {            System.out.println("Caught ConcurrentModificationException");        }        System.out.println("List now: " + students);    }}
Output
Visiting Asha
Visiting Ravi
Caught ConcurrentModificationException
List now: [Asha, Kiran, Meena]

What this code does

  • The removal itself works: Ravi is gone. The exception comes from the next call to next(), which sees that modCount no longer matches.
  • Kiran and Meena are never visited, so the loop's work is left half done.

Collections such as ArrayList and HashMap keep a counter called modCount. Every structural change, one that changes the size such as add or remove, increases it. Revise: Iterator and safe removal (opens in a new tab).

When an iterator is created it copies the counter into expectedModCount. Each call to next() compares the two, and if they differ it throws ConcurrentModificationException. The name says "concurrent", but one thread is enough: the iterator only sees that someone other than itself changed the collection.

  • Structural change = size changes: add, remove, clear, put of a new key.
  • Not structural: list.set(i, x), map.put on an existing key.
  • next() checks modCount == expectedModCount, else CME.
  • For-each on a collection is just an iterator in disguise.

Order of execution

How the exception happens

A for-each loop removes an element from its own list. Put the steps in order.

Predict the output: changing a collection inside for-each

A structural change is any change that alters the size of a collection: add, remove, clear, or put with a new key. set and replacing the value of an existing key are not structural.

Not every change throws. The program tries add, set and map changes inside loops and prints which ones throw.

Example 2 · Which changes inside a loop throw?

WhichChangesThrowDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class WhichChangesThrowDemo {    static void tryRun(String label, Runnable action) {        try {            action.run();            System.out.println(label + ": ok");        } catch (RuntimeException e) {            System.out.println(label + ": " + e.getClass().getSimpleName());        }    }
    public static void main(String[] args) {        tryRun("list.add in for-each", () -> {            List<Integer> marks = new ArrayList<>(List.of(70, 80, 90));            for (int m : marks) {                if (m == 70) marks.add(100);            }        });        tryRun("list.set in for-each", () -> {            List<Integer> marks = new ArrayList<>(List.of(70, 80, 90));            for (int m : marks) {                if (m == 70) marks.set(0, 75);            }        });        tryRun("map.put new key in keySet loop", () -> {            Map<String, Integer> fees = new HashMap<>(Map.of("Tuition", 1, "Hostel", 2));            for (String k : fees.keySet()) {                fees.put("Bus", 3);            }        });        tryRun("map.put existing key in keySet loop", () -> {            Map<String, Integer> fees = new HashMap<>(Map.of("Tuition", 1, "Hostel", 2));            for (String k : fees.keySet()) {                fees.put(k, fees.get(k) * 10);            }        });    }}
Output
list.add in for-each: ConcurrentModificationException
list.set in for-each: ok
map.put new key in keySet loop: ConcurrentModificationException
map.put existing key in keySet loop: ok

What this code does

  • add and a put with a new key change the size, so modCount changes and the next next() throws.
  • set and a put on an existing key only replace a value. The size is unchanged, so there is no exception.

A for-each loop over a collection is compiled into Iterator it = list.iterator(); while (it.hasNext()) { x = it.next(); ... }. So calling list.remove(x) or list.add(x) inside the loop changes modCount, and the next it.next() throws.

The same applies to maps: putting a new key or removing one while looping over keySet(), values() or entrySet() throws. Replacing the value of an existing key is safe, because the size does not change.

Predict the output

Predict: does the loop throw?

Pick what each snippet does.

Round 1 of 3

A set inside a for-each loop.

List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
for (Integer x : list) {
list.set(0, 9);
}
System.out.println(list);

Safe removal: Iterator.remove and removeIf

Iterator.remove() removes the element last returned by next() through the iterator itself, so the iterator updates its own counter and stays valid. Call it at most once per next().

Four safe ways to remove while looping. The program removes failing marks with Iterator.remove, removeIf, a backward index loop and a map removeIf.

Example 3 · Four safe ways to remove

SafeRemovalDemo.javaJava
import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.TreeMap;
public class SafeRemovalDemo {    public static void main(String[] args) {        List<Integer> a = new ArrayList<>(List.of(35, 72, 28, 90, 41));        Iterator<Integer> it = a.iterator();        while (it.hasNext()) {            if (it.next() < 40) {                it.remove();            }        }        System.out.println("Iterator.remove: " + a);
        List<Integer> b = new ArrayList<>(List.of(35, 72, 28, 90, 41));        b.removeIf(m -> m < 40);        System.out.println("removeIf:        " + b);
        List<Integer> c = new ArrayList<>(List.of(35, 72, 28, 90, 41));        for (int i = c.size() - 1; i >= 0; i--) {            if (c.get(i) < 40) {                c.remove(i);            }        }        System.out.println("index from end:  " + c);
        Map<String, Integer> dues = new HashMap<>(Map.of("Asha", 0, "Ravi", 1500, "Kiran", 0));        dues.entrySet().removeIf(e -> e.getValue() == 0);        System.out.println("map removeIf:    " + new TreeMap<>(dues));    }}
Output
Iterator.remove: [72, 90, 41]
removeIf:        [72, 90, 41]
index from end:  [72, 90, 41]
map removeIf:    {Ravi=1500}

What this code does

  • it.remove() updates both the list and the iterator's expected count, so the loop continues safely.
  • Looping by index from the end works because removing at i only shifts elements you have already checked.
  • For maps, entrySet().removeIf removes entries in place; the TreeMap copy is only for sorted printing.

You must call next() before each remove(); calling it twice in a row throws IllegalStateException.

removeIf(predicate) (Java 8+) is the shortest fix and, on ArrayList, does the job in one O(n) pass. For maps, use map.entrySet().removeIf(...) or map.values().removeIf(...). Other safe options: loop by index from the end, or collect the items first and call removeAll after the loop.

Find the bug

Find the removal bug

Each loop removes items the wrong way. Tap the wrong line, then check the fix.

Remove cancelled orders (names starting with X-).

Round 1 of 3

Fail-fast vs fail-safe iterators

A fail-safe iterator comes from a concurrent collection and never throws ConcurrentModificationException. It walks a snapshot or tolerates changes, so it may not show changes made during the loop.

Some iterators never throw. The program loops over a CopyOnWriteArrayList while adding to it, and prints what the loop sees.

Example 4 · Fail-safe iterators do not throw

FailSafeDemo.javaJava
import java.util.List;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArrayList;
public class FailSafeDemo {    public static void main(String[] args) {        List<String> notices = new CopyOnWriteArrayList<>(List.of("Exam", "Fest"));        for (String n : notices) {            System.out.println("Reading " + n);            notices.add(n + " update");        }        System.out.println("After loop: " + notices);
        Map<String, Integer> seats = new ConcurrentHashMap<>(Map.of("CSE", 60, "ECE", 60));        for (String branch : seats.keySet()) {            if (!branch.endsWith("-B")) {                seats.put(branch + "-B", 30);            }        }        System.out.println("Branches now: " + seats.size() + ", no exception");    }}
Output
Reading Exam
Reading Fest
After loop: [Exam, Fest, Exam update, Fest update]
Branches now: 4, no exception

What this code does

  • The CopyOnWriteArrayList loop reads a snapshot taken when it started, so the two added notices are not visited and no exception is thrown.
  • ConcurrentHashMap's iterator is weakly consistent: it may or may not visit the -B keys added during the loop. The endsWith check makes the result 4 either way; never rely on whether new keys are seen.

Fail-fast iterators (ArrayList, HashMap, HashSet and most java.util collections) throw CME on a detected change. This is a best-effort bug detector, not a guarantee, so never write code that relies on catching it.

Fail-safe iterators come from concurrent collections and never throw CME. CopyOnWriteArrayList iterates over a snapshot: changes during the loop do not show, and every write copies the whole array, so it suits lists read often and changed rarely. ConcurrentHashMap iterators are weakly consistent: they never throw and may or may not see changes made during the loop. Revise: CopyOnWriteArrayList (opens in a new tab).

Trap: removing the second-to-last element does not throw

A removal that does not throw. The program removes the second-to-last, a middle and the last element in three loops, and prints what happens.

Example 5 · The second-to-last removal that does not throw

SecondToLastDemo.javaJava
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
public class SecondToLastDemo {    static void removeWhileLooping(String target) {        List<String> names = new ArrayList<>(List.of("Asha", "Ravi", "Kiran", "Meena"));        try {            for (String s : names) {                System.out.print(s + " ");                if (s.equals(target)) {                    names.remove(s);                }            }            System.out.println("| no exception, list " + names);        } catch (ConcurrentModificationException e) {            System.out.println("| CME, list " + names);        }    }
    public static void main(String[] args) {        removeWhileLooping("Kiran");   // second-to-last        removeWhileLooping("Ravi");        removeWhileLooping("Meena");   // last    }}
Output
Asha Ravi Kiran | no exception, list [Asha, Ravi, Meena]
Asha Ravi | CME, list [Asha, Kiran, Meena]
Asha Ravi Kiran Meena | CME, list [Asha, Ravi, Kiran]

What this code does

  • After removing Kiran, size becomes 3 and the cursor is 3, so hasNext() is false. The loop ends without calling next(), and Meena is silently skipped.
  • Removing the last element makes size 3 while the cursor is 4. hasNext() is true (4 ≠ 3), so next() runs, checks modCount and throws.

hasNext() is simply cursor != size. If you remove the second-to-last element inside a for-each loop, the size drops by one and becomes equal to the cursor. hasNext() returns false, the loop ends quietly, next() is never called, and no exception is thrown.

The code looks correct, but the last element is never visited. Interviewers use this case to check that you understand the mechanism and do not just remember "for-each plus remove throws".

Next step

Check your understanding

12 quick questions