Avoiding
ConcurrentModificationException
Learn why Java throws this exception when you modify a collection during iteration, and master the safe patterns to avoid it.
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.
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.
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?
The Core Rule
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.
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
Example 1: The Broken Code
Fix 1: Iterator.remove()
Fix 2: Collect-then-Remove
Fix 3: removeIf() (Java 8+)
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.
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.
Common Mistakes
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
Consider the following code:
List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> toRemove = new ArrayList<>();
for (int n : nums) { if (n % 2 == 0) toRemove.add(n); }
nums.removeAll(toRemove);
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?