The java.util.In real terms, concurrentModificationException is one of the most common runtime exceptions Java developers encounter, and despite its name, it rarely has anything to do with actual multithreading. It is thrown when a collection is structurally modified while an iteration over it is in progress — for example, adding or removing elements inside a for-each loop. Understanding why the exception exists and knowing the handful of correct patterns for fixing it will save you hours of debugging. This article explains the root cause, walks through the most frequent code patterns that trigger it, and gives you concrete, production-ready fixes for lists, sets, and maps.
What Is ConcurrentModificationException?
ConcurrentModificationException (often abbreviated as CME) is an unchecked exception in the java.util package. It signals that a collection detected an illegal concurrent modification — a change made outside the iterator that is currently traversing it.
Most standard collections in Java (ArrayList, HashMap, HashSet, LinkedList, TreeMap, and others) are fail-fast. In real terms, they keep an internal counter, usually called modCount, that increments every time the collection's structure changes (elements added or removed, size altered). When you obtain an iterator, it snapshots that counter into expectedModCount. On every call to next() or remove(), the iterator compares the two values. If they differ, it throws the exception immediately Easy to understand, harder to ignore..
List names = new ArrayList<>(List.of("Ana", "Ben", "Cara"));
for (String name : names) {
if (name.startsWith("B")) {
names.remove(name); // throws ConcurrentModificationException
}
}
The critical insight: this code is single-threaded, yet it still fails. Here's the thing — the exception name is misleading. It is a detection mechanism, not a concurrency guarantee.
Why the Exception Is Actually Helpful
It is tempting to treat CME as an annoyance, but it protects you from silent data corruption. Without fail-fast behavior, an iterator could skip elements, return duplicates, or read stale internal state after the underlying array or bucket table has been resized. The exception converts a subtle logic bug into a loud, immediate failure Small thing, real impact. Turns out it matters..
Worth pausing on this one.
Two important caveats:
- Fail-fast is best-effort, not guaranteed. The Javadoc explicitly states that the exception is thrown on a "best-effort basis" and that programs should not depend on it for correctness.
- Not all collections are fail-fast.
ConcurrentHashMap,CopyOnWriteArrayList, and otherjava.util.concurrentclasses use weakly consistent iterators that never throw CME. They iterate over a snapshot or tolerate concurrent changes.
The Most Common Causes
Before fixing anything, identify which pattern you are hitting The details matter here..
- Removing elements inside a
for-eachloop over the same collection. - Adding elements inside a
for-eachloop, including adding to a map while iterating itskeySet(). - Calling
list.remove()insideforEach()or a stream lambda that operates on the same list. - Nested iteration with modification — iterating a list while a called method mutates it.
- Modifying a
subList()view, which writes through to the backing list. - True multithreading — one thread iterates while another adds or removes without synchronization.
- Using
Collections.unmodifiableList()wrappers incorrectly, where the backing list is still mutated elsewhere.
Fix 1: Use Iterator.remove()
This is the classic, correct solution for removal during iteration. The iterator's own remove() method updates both the collection and the iterator's expectedModCount, keeping them in sync Worth keeping that in mind..
Iterator it = names.iterator();
while (it.hasNext()) {
if (it.next().startsWith("B")) {
it.remove(); // safe
}
}
Note that Iterator only supports removal. If you need to add or replace elements while traversing a List, use ListIterator, which provides add() and set().
ListIterator li = names.listIterator();
while (li.hasNext()) {
if (li.next().equals("Ana")) {
li.set("Anna"); // safe replacement
li.add("Alicia"); // safe insertion
}
}
Fix 2: Use removeIf() (Java 8+)
For the extremely common "remove all matching elements" case, Collection.Worth adding: removeIf() is the cleanest option. It is implemented internally with an iterator and is safe by design Simple as that..
names.removeIf(name -> name.startsWith("B"));
This works on List, Set, and the collection views of Map:
map.entrySet().removeIf(e -> e.getValue() == null);
map.keySet().removeIf(k -> k.startsWith("temp_"));
Fix 3: Iterate Over a Copy
If you're need to modify the original collection while looping — for example, transforming elements and adding new ones — iterate over a defensive copy. The iterator then watches a collection nobody is touching.
for (String name : new ArrayList<>(names)) {
if (name.startsWith("B")) {
names.add(name.toUpperCase());
}
}
This is simple and readable, but it allocates a copy. For large collections in hot paths, prefer the iterator approach or a stream-based rebuild Small thing, real impact..
Fix 4: Use an Index Loop (Lists Only)
For ArrayList and other List implementations that support random access, a reverse index loop avoids the iterator entirely and sidesteps index-shifting bugs The details matter here..
for (int i = names.size() - 1; i >= 0; i--) {
if (names.get(i).startsWith("B")) {
names.remove(i);
}
}
Iterating **backwards
Continuing the discussion on safe modification while iterating
Reverse‑index loop – why it works
When a List is traversed from the front, each removal shifts the indices of the remaining elements to the left. If the loop proceeds forward, the next element to be examined will be the one that slid into the current position, causing an element to be skipped or an IndexOutOfBoundsException to be thrown. Walking the list backwards eliminates this problem: removing an element at index i never affects the positions of the items that have already been processed (those with higher indices).
for (int i = names.size() - 1; i >= 0; i--) {
if (names.get(i).startsWith("B")) {
names.remove(i);
}
}
Because the loop counts down, the element at i‑1 remains at its original position until the iteration reaches that index, guaranteeing that every element is examined exactly once.
When the reverse‑index technique is appropriate
- Random‑access lists –
ArrayList,LinkedList(viaListIteratorwithget/set), and any implementation that supportsget(int)andremove(int)in O(1) time. - Simple removals – when you need to delete a handful of items based on a predicate, the reverse loop is often more readable than juggling an
Iterator. - Performance‑critical paths – it avoids the overhead of creating a copy or an
Iteratorobject, which can be beneficial in tight loops.
Other collection types
The same principle applies to LinkedList when you use its ListIterator in reverse, but the code becomes more verbose. For arrays, you can mimic the reverse loop with a traditional for statement, though you must allocate a temporary array if you need to add elements (arrays are fixed‑size) It's one of those things that adds up..
Honestly, this part trips people up more than it should.
If you are dealing with a Set, the iterator’s remove() method is the only safe way to delete while iterating; there is no index to count down.
Stream‑based rebuilding
In many modern applications, the need to “modify while iterating” can be avoided altogether by constructing a new collection that reflects the desired changes:
List filtered = names.stream()
.filter(n -> !n.startsWith("B"))
.collect(Collectors.toList());
names.clear();
names.addAll(filtered);
This approach is immutable with respect to the original list during the stream pipeline, so ConcurrentModificationException never appears. Still, it allocates a new list and may not be suitable for very large data sets or low‑latency environments Nothing fancy..
Concurrent modification in multithreaded code
When one thread iterates a collection while another thread mutates it, the standard Collection implementations throw ConcurrentModificationException. To make such code safe:
-
Synchronize externally – wrap the iteration and mutation in a synchronized block:
synchronized (names) { for (String n : names) { if (n.startsWith("B")) { names.remove(n); } } } -
Use a thread‑safe collection –
CopyOnWriteArrayListcopies the underlying array on each write, making iteration safe without explicit synchronization. The trade‑off is higher memory usage and slower writes. -
Employ
ConcurrentModificationConcurrentutilities –ConcurrentLinkedQueueorConcurrentHashMapprovide fail‑safe iterators that never throw the exception, though they have different semantics (e.g., no random access) Easy to understand, harder to ignore..
Summary of recommended
Continuing the discussion – What to actually do
From the overview above there are four practical paths you can take, depending on the shape of the problem and the resources you have at hand:
-
Small, ad‑hoc deletions – When you only need to drop a handful of items that satisfy a simple predicate, the most readable solution is usually the “reverse” loop over the original collection. This avoids the overhead of constructing a temporary iterator or creating a copy, and it lets you mutate the underlying structure directly Practical, not theoretical..
synchronized (names) { for (String n : names) { if (n.startsWith("B")) { names.remove(n); } } } -
Performance‑critical code or very large datasets – If every element is processed inside tight loops and you cannot afford the cost of per‑element allocation, consider collecting the desired results first and then replacing the source container in one shot. The stream example illustrates this pattern:
Listfiltered = names.But collect(Collectors. Which means startsWith("B")) . n.toList()); names.Now, stream() . filter(n -> !clear(); names. This eliminates the risk of `ConcurrentModificationException` because the pipeline never modifies the original list, but keep in mind the extra memory footprint and the fact that the operation may be slower than an in‑place pass. -
LinkedList/ array reverse iteration – When you deliberately need a reverse view (e.g., traversing from tail to head) and the iterator’s API does not expose a simple index counter, you can fall back to a traditionalforloop paired with a temporary array only if you must insert elements later. Otherwise, writing a customListIteratormakes the code considerably less concise. -
Setwhile iterating – ASetiterator has no countdown mechanism; the only safe way to delete elements during traversal is to calliterator.remove(element)on each step. Attempting to invokeremove(int)would throwNoSuchElementException. -
Multithreaded environments – Mutating one collection while another iterates triggers
ConcurrentModificationException. Three proven strategies exist:- External synchronization – Wrap the whole operation in a
synchronizedblock (as shown). Simple but can serialize access unintentionally. - Thread‑safe containers – Use
CopyOnWriteArrayList(or similar) which copies the backing array on each write, making concurrent reads safe; the downside is higher memory consumption and slower writes. - Fail‑safe iterators – take advantage of implementations such as
ConcurrentLinkedQueueorConcurrentHashMapwhose built‑in iterators ignore concurrent modifications. They sacrifice random‑access semantics but guarantee safety without extra locks.
- External synchronization – Wrap the whole operation in a
Bottom line
| Situation | Recommended technique |
|---|---|
| Few, known deletions, low latency needed | Reverse loop + optional synchronized wrapper |
| Bulk transformation or filtering of millions of items | Build a new collection via streams (or a library collector) and replace the old one |
Need to walk a LinkedList backwards but |
| Need to walk a `LinkedList` backwards but leave it intact | `ListIterator` with `hasPrevious()` / `previous()` — no copying, no index arithmetic |
| Removing a known subset from a `Set` | `Iterator.remove()` only; there is no positional shortcut |
| Removing everything that matches a predicate | `removeIf` — the compiler-recommended one-liner |
| Shared, concurrently mutated state | `CopyOnWriteArrayList` for read-heavy loads, fail‑safe iterators for queues and maps |
A note on the Set case above
Set has no remove(int) overload at all, so the failure mode is more mundane than a runtime exception: the code will not compile. Collection.In real terms, remove(int) belongs to List, where the argument is an index. If you write iterator.Consider this: remove(element) on a Set iterator, the element is simply discarded if present and ignored otherwise — Iterator. remove() takes no arguments precisely so this distinction cannot be blurred Small thing, real impact..
When the modern one-liner is enough
If you are not constrained to an older language level, removeIf is almost always the right answer. It is concise, it is implemented by the collection itself (usually via the iterator under the hood), and it expresses intent rather than mechanics:
names.removeIf(n -> n.startsWith("B"));
For a List, removeIf runs in linear time. In real terms, for a HashSet, it iterates and deletes in constant amortized time per element. Reach for the explicit iterator form only when you need the loop body to do more than a single predicate test, or when you are maintaining code that must run on a pre‑Java‑8 runtime.
Reverse traversal without copying
If you genuinely want tail‑to‑head order and the list is a LinkedList, ListIterator gives it to you directly. No temporary array, no Collections.reverse, no extra allocation:
ListIterator it = names.listIterator(names.size());
while (it.hasPrevious()) {
String name = it.previous();
if (name.startsWith("B")) {
it.remove(); // safe: remove() always follows previous() here
}
}
The one rule worth memorising: remove(), add(), and set() operate on the element most recently returned by either next() or previous(), so the cursor position after the call is well defined regardless of the direction you were travelling Worth knowing..
Choosing deliberately
The three techniques are not competing answers to one question; they answer three different questions And that's really what it comes down to..
Iterator.remove()asks: can I delete this element as I encounter it? It is allocation‑free, works on everyCollection, and is the fallback when the surrounding code is already iterator‑based.removeIfasks: which elements match? It is the clearest expression of filtering, and it delegates the traversal entirely to the collection, which lets each implementation use its own fastest path.- Rebuild and swap asks
: what should the collection contain when I am done? Instead of mutating in place, you build the survivor set into a fresh collection and assign it back. This is the oldest trick in the book, and it is still the right one when the filter is expensive, when several predicates interact, or when the source collection is unmodifiable and you have no choice but to produce a new one:
List kept = new ArrayList<>(names.size());
for (String name : names) {
if (!name.startsWith("B")) {
kept.add(name);
}
}
names = kept; // or names.clear(); names.addAll(kept);
Two details make this safer than it looks. Second, the reassignment names = kept is only valid if names is a local variable or a field you own. size())avoids the repeated array growth that a naiveaddloop incurs; the upper bound is exact, and the wasted slots cost nothing worth measuring. First, sizing the destination up front withnew ArrayList<>(names.If callers hold a reference to the original list, they will keep pointing at the old contents, and the swap becomes a silent bug.
List kept = new ArrayList<>(names.size());
for (String name : names) {
if (!name.startsWith("B")) {
kept.add(name);
}
}
names.clear();
names.addAll(kept);
We're talking about the retainAll/removeAll shape done by hand, and it is worth knowing because the bulk operations have a trap of their own: removeAll on an ArrayList is quadratic in the worst case, since each removal shifts the tail. The rebuild-and-swap version is linear, which is exactly why it survives in production code despite looking primitive And that's really what it comes down to..
Honestly, this part trips people up more than it should.
The failure modes, collected
It helps to have the whole landscape on one page, because the exceptions are easy to confuse:
| What you wrote | What happens | Why |
|---|---|---|
for (String s : list) list.remove(s); |
ConcurrentModificationException |
Enhanced for hides an iterator; list.size(); i++) list.size() - 1; i >= 0; i--) list.Now, remove(i); |
for (int i = list. remove(i); |
Works | Descending index never revisits a shifted element |
iterator.And remove() before any next() |
IllegalStateException |
There is no "current element" to remove |
map. entrySet().remove(k) inside a for over entrySet() |
ConcurrentModificationException |
Structural modification of the map invalidates the entry iterator |
map.Think about it: removeIf(... remove() after next() |
Works | The iterator updates its own expected count |
iterator.remove bumps modCount behind its back |
||
for (int i = 0; i < list.) |
Works | Delegated to the map's own iterator |
| `set. |
The ConcurrentModificationException row deserves one clarification, because the name misleads. It has nothing to do with threads. It is a fail-fast check: the iterator records a modification count when it is created and compares it on every next(). That said, a single-threaded loop that mutates the backing collection through any channel other than the iterator itself will trip it just as reliably as a genuine race would. The exception means "you changed this collection while I was walking it," not "two threads are fighting.
A short decision procedure
When you sit down to write the loop, three questions settle it:
- Are you on Java 8 or later, and is the condition a single predicate? Use
removeIf. Stop reading. - Do you need to do work per element beyond the test — log it, accumulate a count, call a side effect — or must the code run on an older runtime? Use an explicit
Iteratoranditerator.remove(). It is the only in-place mechanism that is correct on everyCollectionand every language level. - Is the source unmodifiable, is the predicate expensive, or do you need to keep the original reference intact? Build a new collection and swap or copy it back. Accept the extra allocation; it buys you linear time and total clarity about what the result is.
Everything else — descending index loops, retainAll, Collections.removeAll on a copy — is a special case of
one of those three patterns. The descending-index loop is just manual bookkeeping that happens to dodge the element-shift problem; retainAll is bulk predicate removal implemented by the collection itself; and copying into a new collection is the “build a new collection” path with extra steps. There is no fourth in-place, iterator-safe loophole Not complicated — just consistent..
So the practical takeaway is short: reach for removeIf first. Day to day, if you need more control or must run on an older runtime, use an explicit Iterator and call only its remove() method. Practically speaking, if neither fits, build a fresh collection and replace the old one. Never mutate a collection through its own remove() or add() methods while an enhanced for loop or any other iterator is walking it, and do not let the name ConcurrentModificationException trick you into thinking threads are involved. It is a single-threaded, fail-fast boundary, and respecting it keeps your loops predictable Took long enough..
Some disagree here. Fair enough.