💣 Here’s a minimal and crystal-clear single-threaded Java program that throws a ConcurrentModificationException by modifying a collection during iteration — a classic trap!
✅ Java Program That Throws ConcurrentModificationException
import java.util.*;
public class ConcurrentModificationExample {
public static void main(String[] args) {
List<String> colors = new ArrayList<>();
colors.add("red");
colors.add("green");
colors.add("blue");
// This will throw ConcurrentModificationException
for (String color : colors) {
if (color.equals("green")) {
colors.remove(color); // ❌ Modifying list while iterating
}
}
}
}
💥 Output at runtime:
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:xxx)
...
🔍 Why this happens:
- The
for-eachloop uses an internalIterator. - When you call
colors.remove(color), the collection is modified directly, but the iterator isn’t aware of that change. - On the next loop iteration, it checks if the internal structure has changed → detects it → boom → throws
ConcurrentModificationException.
🛡️ Want to avoid it?
Use the Iterator‘s own remove() method:
Iterator<String> iterator = colors.iterator();
while (iterator.hasNext()) {
String color = iterator.next();
if (color.equals("green")) {
iterator.remove(); // ✅ Safe removal
}
}