Skip to content
javahacks.dev
Java Core

Fix ConcurrentModificationException in Java Collections

Why changing a list inside a for-each loop throws ConcurrentModificationException, and the safe ways to remove, add or replace elements while iterating.

6 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, IntelliJ IDEA, Linux, Gradle and Spring logos.

ConcurrentModificationException is thrown when you change a collection while you are iterating over it, and the name misleads: no second thread is needed. The most common trigger is a single thread removing from a list inside a for-each loop over that list. The exception comes from the collection's iterator, which keeps a count of the changes and checks it on every step. This post explains the mechanism, then gives four fixes in the order to try them, shows that maps behave the same way, and covers the multi-threaded case where the right answer is a different collection. It uses JDK 25.

What triggers it

src/main/java/com/example/Cleanup.javajava
List<String> names = new ArrayList<>(List.of("ann", "bob", "cy", "dee"));
for (String name : names) {
    if (name.length() == 3) {
        names.remove(name);          // changes the list during iteration
    }
}
Text
Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1096)
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1050)

The for-each loop uses an Iterator. ArrayList keeps an integer modCount that increases on every structural change (add, remove, clear). When the iterator is created it copies the count, and on each next() it compares: if the list's count differs from its own, it throws. The check is "fail-fast": the collection detects the problem as early as it can, instead of producing wrong results later. It is a best-effort check meant for finding bugs, and the Javadoc says you must not rely on it for correctness.

The exception does not occur every time. If you remove the second-to-last element, the loop's hasNext() returns false before next() is called, and the loop ends silently, skipping the last element. That inconsistency makes the bug hard to reproduce: it appears for some inputs and not for others, and the silent-skip case is worse than the exception because it gives a wrong result without an error.

Fix 1: removeIf

When the goal is to remove elements that match a condition, ask the collection to do it:

java
names.removeIf(name -> name.length() == 3);

Collection.removeIf is available since Java 8, takes a predicate and removes every matching element safely. For ArrayList it is also faster than a loop of remove calls, because it compacts the array in one pass instead of shifting elements for each removal. This is the right fix for the large majority of cases, and the one to reach for first. Map has entrySet().removeIf(...), keySet().removeIf(...) and values().removeIf(...) for the same purpose. Use replaceAll for transforming elements in place, and a stream with filter and collect when you want a new collection.

Fix 2: the iterator's remove

When the removal logic needs more than a predicate, use the iterator explicitly and remove through it:

java
Iterator<String> it = names.iterator();
while (it.hasNext()) {
    String name = it.next();
    if (shouldDrop(name)) {
        it.remove();                 // allowed: the iterator updates its own expected count
    }
}

Iterator.remove() removes the last element returned by next() and tells the iterator about the change, so it stays consistent. It can be called once per next(). This is the classic pattern and it works for any collection whose iterator supports removal. For lists, ListIterator also offers add and set during iteration, for insertion after the current element and replacement. Immutable collections, from List.of or Collections.unmodifiableList, throw UnsupportedOperationException for any removal, a different error with its own fix in the unsupported operation guide.

Fix 3: build a new collection

Often the clearest approach is not to modify at all:

java
List<String> kept = names.stream()
    .filter(name -> name.length() != 3)
    .toList();

The original is untouched, so nothing can interfere with it, and the result is easy to reason about. toList() returns an unmodifiable list; use collect(Collectors.toCollection(ArrayList::new)) when you need a mutable one. For code written in a functional style, this is the natural form. The cost is an allocation for the new collection, which matters only in a measured hot path. If other code holds a reference to the original list and expects to see the change, you must modify it in place instead, with removeIf, or replace the reference in the owner.

Fix 4: collect changes, apply later

When you must add and remove based on what you see during the pass, record the changes and apply them afterwards:

java
List<Order> toCancel = new ArrayList<>();
for (Order order : orders) {
    if (order.isStale()) toCancel.add(order);
}
orders.removeAll(toCancel);

Iterate over the original, collect what to change, and modify after the loop. For lists with many items to remove, removeAll with a List argument is quadratic, because each contains call scans the list; pass a HashSet instead, or use removeIf(toCancel::contains) with a set. Iterating over a copy (new ArrayList<>(orders)) while changing the original is another variant, with the cost of the copy, and it is safe only when nothing else changes the collection meanwhile.

Maps behave the same way

java
for (String key : map.keySet()) {
    if (isExpired(key)) map.remove(key);        // ConcurrentModificationException
}

HashMap has the same fail-fast iterators for keySet, values and entrySet. The fixes mirror the list ones: map.keySet().removeIf(this::isExpired), map.entrySet().removeIf(e -> e.getValue().isExpired()), or map.values().removeIf(...). Changing the value of an existing key during iteration with entry.setValue(...) or map.put(existingKey, v) is not a structural change and is allowed; adding or removing keys is not. compute, merge and computeIfAbsent inside the iteration of the same map can also throw, and in recent JDKs HashMap.computeIfAbsent detects a mapping function that modifies the map and throws ConcurrentModificationException deliberately.

Threads: use the right collection

If another thread modifies the collection while this thread iterates, the same exception can occur, or worse, wrong results without it. Fail-fast iterators are not a synchronisation mechanism: the check is not atomic and can miss a change. The fix is to use a collection designed for concurrent access, or to synchronise.

ConcurrentHashMap and ConcurrentLinkedQueue have weakly consistent iterators: they never throw the exception, they reflect the state at some point since the iterator was created, and may or may not show later changes. CopyOnWriteArrayList gives each iterator a snapshot of the array, so iteration is never disturbed, at the price of copying the whole array on each write, which suits lists read often and changed rarely, such as listener lists. Wrapping with Collections.synchronizedList does not help iteration; you must hold the lock on the list for the whole loop, as its Javadoc says. Choosing among them is part of the broader topic in threads and executors.

A shared mutable collection is also a design smell. Often the better fix is to give each thread its own data and merge results at the end, or to pass immutable snapshots.

Where this does not apply

An exception with a similar name and a different cause, ConcurrentModificationException from a Spliterator or stream, appears when you modify the source collection inside a stream pipeline's lambda; the fix is the same, collect first. Languages with other collections may allow modification during iteration; Java's do not. The behaviour is specified in the Collection Javadoc and the exception's page. The language features used in the examples are covered in the modern Java guide.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.