0
0
JavaDebug / FixBeginner · 4 min read

How to Fix ConcurrentModificationException in Java Quickly

A ConcurrentModificationException happens when you change a collection while looping over it with an iterator. To fix it, avoid modifying the collection directly inside the loop; instead, use the iterator's remove() method or collect changes to apply after the loop.
🔍

Why This Happens

This error occurs because Java's collections detect when you change them while looping through with an iterator. The iterator expects the collection to stay the same during the loop. If you add or remove items directly, it throws ConcurrentModificationException to prevent unpredictable behavior.

java
import java.util.ArrayList;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("apple");
        fruits.add("banana");
        fruits.add("cherry");

        for (String fruit : fruits) {
            if (fruit.equals("banana")) {
                fruits.remove(fruit); // This causes ConcurrentModificationException
            }
        }
    }
}
Output
Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997) at Example.main(Example.java:11)
🔧

The Fix

To fix this, use the iterator's remove() method instead of removing directly from the collection. This keeps the iterator and collection in sync and avoids the error.

java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("apple");
        fruits.add("banana");
        fruits.add("cherry");

        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            if (fruit.equals("banana")) {
                iterator.remove(); // Correct way to remove during iteration
            }
        }

        System.out.println(fruits); // Output: [apple, cherry]
    }
}
Output
[apple, cherry]
🛡️

Prevention

To avoid ConcurrentModificationException in the future, follow these tips:

  • Use the iterator's remove() method when deleting items during iteration.
  • Collect items to add or remove in a separate list, then update the original collection after the loop.
  • Consider using concurrent collections like CopyOnWriteArrayList if you need safe modifications during iteration in multi-threaded code.
  • Use enhanced for-loops only when you don't modify the collection inside the loop.
⚠️

Related Errors

Other errors similar to ConcurrentModificationException include:

  • IndexOutOfBoundsException: Happens if you modify a list by index incorrectly during iteration.
  • IllegalStateException: Can occur if you call remove() on an iterator before next().
  • NullPointerException: May happen if your collection contains nulls and your code does not check for them.

Key Takeaways

Never modify a collection directly inside a loop using an iterator; use the iterator's remove() method instead.
If you need to add or remove multiple items, collect changes first and apply them after the loop.
Use concurrent collections like CopyOnWriteArrayList for safe modifications in multi-threaded environments.
Enhanced for-loops are convenient but unsafe for modifying collections during iteration.
Understanding how iterators track modifications helps prevent runtime exceptions.