Java ConcurrentModificationException
A fail-fast iterator can report structural changes made directly to its backing collection. Even one thread can trigger ConcurrentModificationException.
A simple example
ConcurrentModificationException
- Start with An iterator is traversing a list
- Do this Change the list directly, then advance the iterator
- Result Can report concurrent modification
Syntax
iterator.next()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRemove an expired pass during inspection
A clerk walks through a list of travel passes to remove expired entries. Editing the list behind an active iterator can invalidate its position, so the cleanup needs an iteration strategy that supports removal.
import java.util.ArrayList;
import java.util.List;
import java.util.ConcurrentModificationException;
class Main {
public static void main(String[] args) throws Exception {
var passes = new ArrayList<>(List.of("expired", "valid"));
var inspection = passes.iterator();
passes.remove("expired");
try {
inspection.next();
} catch (ConcurrentModificationException changed) {
System.out.println(passes);
}
}
}
[valid]
Removing a pass directly changes this ArrayList after the iterator is created. The next call detects the stale iterator.
Clear all expired travel passes in one operation
A transit inspector clears the expired passes at the end of a shift. The valid entries should stay in the list even when two expired passes are next to each other.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var passes = new ArrayList<>(List.of("expired", "expired", "valid"));
passes.removeIf("expired"::equals);
System.out.println(passes);
}
}
[valid]
removeIf performs the removals through the collection's supported operation.
Clear a cancelled rehearsal
Both entries in a rehearsal list are marked off. Use the iterator to remove cancelled entries during review. How many names remain?
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
var roster=new ArrayList<>(List.of("off","off"));
var entries=roster.iterator();
while(entries.hasNext()) if(entries.next().equals("off")) entries.remove();
System.out.println(roster.size());
}
}
0
What to watch for
Fail-fast detection is best effort. Never rely on this exception for synchronization or for a cleanup loop to work.