Avoid Removing Elements While Iterating: Java ConcurrentModificationException Example and Fix
During a product bug investigation, the author demonstrates how removing entries from a Java HashMap while iterating triggers a ConcurrentModificationException, provides the faulty code, shows the exception stack trace, and presents a safe fix that collects keys first and removes them after iteration.
I encountered a bug in a company product where removing an element from a Map while iterating caused a crash due to a ConcurrentModificationException.
Important reminder: do not delete elements during iteration.
Reproduction code:
Map
abc = new HashMap<>();
abc.put(1, 2);
abc.put(2, 3);
abc.put(3, 4);
Set
keys = abc.keySet();
for (int i : keys) {
if (i == 2) {
abc.remove(i);
}
}The exception thrown is:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
at source.Practise.testDemo(Practise.java:23)
at source.Practise.main(Practise.java:12)Correct approach: first collect the keys to be removed, then delete them after the iteration completes.
Map
abc = new HashMap<>();
abc.put(1, 2);
abc.put(2, 3);
abc.put(3, 4);
Set
keys = abc.keySet();
List
toRemove = new ArrayList<>();
for (int i : keys) {
if (i == 2) {
toRemove.add(i);
}
}
for (int i : toRemove) {
abc.remove(i);
}This method avoids modifying the collection during iteration, preventing the ConcurrentModificationException.
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.