01 / 21

Avoiding
ConcurrentModificationException

Learn why Java throws this exception when you modify a collection during iteration, and master the safe patterns to avoid it.

Java

What is an Iterator?

An Iterator is an object that lets you traverse a collection one element at a time. When you write a for-each loop, Java secretly creates an Iterator behind the scenes.

"A" "B" "C" "D" Iterator cursor ArrayList<String>

What is ConcurrentModificationException?

It is a runtime exception thrown when a collection detects it has been structurally modified while an Iterator is actively traversing it. "Structural modification" means adding or removing elements: changing the size of the collection.

✕ Structural
add(), remove(), clear() change the collection's size and trigger the exception.
✓ Non-structural
set() on a List replaces a value without changing size. This is safe during iteration.

The modCount Mechanism

Every Java collection maintains an internal counter called modCount. When you create an Iterator, it copies this value into its own expectedModCount. On each call to next(), the Iterator checks: do these two numbers still match?

ArrayList modCount = 3 elements: ["A","B","C"] Iterator expectedModCount = 3 cursor = 0 copies After list.add("D") modCount = 4 Iterator.next() expectedModCount = 3
\(4 \neq 3\)
ConcurrentModificationException!

The Core Rule

1
for-each loop creates a hidden Iterator. Calling list.remove() inside it breaks the modCount contract.
2
Iterator.remove() updates both modCount and expectedModCount together, keeping them in sync.
3
Collect-then-modify: gather elements to remove in a separate list, then remove them after the loop ends.

The Fail-Fast Principle

Java collections use a fail-fast strategy. Rather than silently producing corrupted results, the Iterator immediately throws an exception when it detects a mismatch. This protects you from subtle bugs.

Start Create Iterator next()
\(3=3\) ✓
Read "A" list .remove() modCount becomes 4 next()
\(4 \neq 3\) ✕
EXCEPTION Fail-Fast: Crash early, not silently.

Iterator.remove() vs List.remove()

Iterator.remove() List.remove()
Updates modCount ✓ Yes ✓ Yes
Updates expectedModCount ✓ Yes ✕ No
Safe during iteration? ✓ Safe ✕ Throws exception
Adjusts cursor position ✓ Yes ✕ No

Safe Strategies for Removal

1
Use Iterator.remove(): call it right after next(). Only removes the element you just retrieved.
2
Collect-then-remove: iterate first, saving items to remove in a separate list. After the loop, call removeAll().
3
Use removeIf(): a single-line lambda approach added in Java 8. Handles the Iterator internally.
4
Use CopyOnWriteArrayList: iterates over a snapshot copy. Safe but slower for large or frequently-modified lists.

Example 1: The Broken Code

✕ THROWS EXCEPTION
List<String> names = new ArrayList<>( Arrays.asList("Alice", "Bob", "Carol")); for (String name : names) { if (name.equals("Bob")) { names.remove(name); // Danger! } }

Fix 1: Iterator.remove()

✓ SAFE
List<String> names = new ArrayList<>( Arrays.asList("Alice", "Bob", "Carol")); Iterator<String> it = names.iterator(); while (it.hasNext()) { String name = it.next(); if (name.equals("Bob")) { it.remove(); // Safe! Syncs both counters } }

Fix 2: Collect-then-Remove

✓ SAFE
List<String> names = new ArrayList<>( Arrays.asList("Alice", "Bob", "Carol")); List<String> toRemove = new ArrayList<>(); for (String name : names) { if (name.startsWith("B")) { toRemove.add(name); // Collect, don't remove yet } } names.removeAll(toRemove); // Remove after loop ends

Fix 3: removeIf() (Java 8+)

✓ SAFE AND CONCISE
List<String> names = new ArrayList<>( Arrays.asList("Alice", "Bob", "Carol")); names.removeIf(name -> name.equals("Bob")); // Result: ["Alice", "Carol"]

What About Adding Elements?

The same rule applies: calling list.add() during a for-each loop also throws ConcurrentModificationException. But Iterator does not have an add() method. For adding during traversal, use a ListIterator.

List<String> names = new ArrayList<>( Arrays.asList("Alice", "Carol")); ListIterator<String> li = names.listIterator(); while (li.hasNext()) { String name = li.next(); if (name.equals("Alice")) { li.add("Bob"); // Inserts after "Alice" } } // Result: ["Alice", "Bob", "Carol"]

Maps and ConcurrentModification

The same rules apply to HashMap, TreeMap, and other Map implementations. Iterating over keySet(), values(), or entrySet() creates an Iterator under the hood.

✕ Broken
Calling map.remove(key) inside a for-each over map.keySet() throws the exception.
✓ Safe
Use iterator.remove() on the entrySet iterator, or use map.entrySet().removeIf() in Java 8+.

Common Mistakes

✕ remove() in for-each
Calling collection.remove() inside a for-each loop. The hidden Iterator detects the change on the next call to next().
✕ Adding in for-each
Calling collection.add() inside a for-each loop. Additions also increment modCount and break the contract.
✕ Removing the "second-to-last"
Removing the second-to-last element may not throw an exception (due to hasNext() check order), hiding the bug until the list size changes.

Strategy Comparison

Strategy Removal Addition Ease
Iterator.remove() ✓ ✕ Medium
ListIterator ✓ ✓ Medium
Collect-then-remove ✓ ✓ Easy
removeIf() (Java 8+) ✓ ✕ Easiest
CopyOnWriteArrayList ✓ ✓ Easy (slower)

Question 1 of 5

Which of the following directly causes a ConcurrentModificationException?

Question 2 of 5

What does the Iterator check on each call to next()?

Question 3 of 5

What is the result after this code executes?

Question 4 of 5

Which method would you use to add an element safely while iterating over a List?

Question 5 of 5

Why might removing the second-to-last element in a for-each loop not throw a ConcurrentModificationException?