Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

This code throws ConcurrentModificationException:

Java
for (Order o : orders) {
if (o.isCancelled()) orders.remove(o);
}

Explain why and give correct alternatives.

The for-each loop runs on the list's iterator, and the iterator remembers how many structural changes the list had when it was created. Calling orders.remove(o) changes the list behind the iterator's back, so on the next call to next() the counts differ and the iterator fails fast with ConcurrentModificationException. The correct alternatives are an explicit iterator with it.remove(), orders.removeIf(Order::isCancelled), or building a new filtered list with a stream.

Why this question is asked

Removing items from a list while looping over it is one of the first bugs most Java developers write, and it still appears in production code because it sometimes works by accident. Interviewers ask about it because the explanation shows whether we understand what the for-each loop really does, what the Iterator pattern is, and why fail-fast behaviour exists. In this answer, we will reproduce the exception, unpack the for-each loop into the iterator calls it hides, follow the modification count that triggers the failure, look at a case where the bug does not throw but still gives a wrong result, and then go through the three correct fixes and the behaviour of concurrent collections.

1Reproducing the Problem

Let us start with a list of three orders where the first one is cancelled. The class Order has a method isCancelled() that returns a boolean.

Java
List<Order> orders = new ArrayList<>(List.of(
new Order(1, true), // cancelled
new Order(2, false),
new Order(3, false)));
for (Order o : orders) {
if (o.isCancelled()) {
orders.remove(o); // removes order 1, size is now 2
}
} // ConcurrentModificationException on the next loop step

The remove call itself succeeds. Order 1 is gone and the list has two elements. The exception comes a moment later, when the loop asks for the next element. To see why, we need to look at what the compiler turns a for-each loop into.

2What the For-Each Loop Really Does

The enhanced for loop works on anything that implements Iterable. It is shorthand for asking the collection for an Iterator, an object that walks through the elements one at a time, and calling hasNext() and next() on it. This is the Iterator pattern: the loop does not know how ArrayList stores its elements, it only talks to the iterator.

Java
// What the compiler generates for: for (Order o : orders) { ... }
Iterator<Order> it = orders.iterator();
while (it.hasNext()) {
Order o = it.next(); // the check happens here
if (o.isCancelled()) {
orders.remove(o); // goes to the list directly, not through the iterator
}
}
Step throughHow the iterator detects the change
LoopIteratorArrayList
iterator(): saves expectedModCount = 0
next()
order 1
remove(order 1): modCount becomes 1
hasNext(): cursor 1 != size 2, true
next(): modCount 1 != expected 0
throws ConcurrentModificationException

7 messages in order. Play them, or step through them one at a time.

The removal goes around the iterator, so its saved count no longer matches the list.

ArrayList keeps a field called modCount, a counter that it increments on every structural modification, meaning any change in size such as add or remove. When we create an iterator, it copies the current value into its own field, expectedModCount. Every call to next() first compares the two. If they differ, someone changed the list without going through this iterator, so the iterator's idea of where it is in the list can no longer be trusted, and it throws ConcurrentModificationException instead of returning a wrong element.

Notice that the word concurrent in the name is misleading here. There is only one thread. The exception means that the list was modified concurrently with the iteration, not by another thread.

3Why It Sometimes Does Not Throw

The check runs in next(), and hasNext() for ArrayList simply compares the cursor with the current size. So if the element we remove is the second-to-last one, the loop can end before next() is ever called again.

Java
List<Order> orders = new ArrayList<>(List.of(
new Order(1, false),
new Order(2, true), // cancelled
new Order(3, true))); // also cancelled
for (Order o : orders) {
if (o.isCancelled()) orders.remove(o);
}
System.out.println(orders); // [Order 1, Order 3]: no exception, and order 3 was never checked

After next() returns order 2, the cursor is 2. Removing it shrinks the size to 2, so hasNext() returns false and the loop ends quietly. Order 3 is cancelled but stays in the list. This is why the Javadoc says fail-fast behaviour is only best effort: the exception is a debugging aid, not a guarantee. We must never write code that depends on catching it, and code that does not throw is not therefore correct.

4Fix 1: Remove Through the Iterator

The iterator itself has a remove() method that deletes the element most recently returned by next(). Because the change goes through the iterator, it updates both the list and its own expectedModCount and cursor, so iteration continues correctly.

Java
Iterator<Order> it = orders.iterator();
while (it.hasNext()) {
if (it.next().isCancelled()) {
it.remove(); // list and iterator stay in agreement
}
}
System.out.println(orders); // [Order 1]

This form is useful when the loop does more than filtering, for example when it removes an order and also records it somewhere else in the same pass. Calling it.remove() twice without a next() in between throws IllegalStateException, because there is no current element to remove.

5Fix 2: removeIf, and Fix 3: A Filtered Copy

Since Java 8, every Collection has removeIf, which takes a predicate and removes all matching elements. For ArrayList it is also faster than repeated removal, because it marks the matching elements first and then shifts the survivors once, instead of shifting the array on every removal.

Java
boolean changed = orders.removeIf(Order::isCancelled); // true
System.out.println(orders); // [Order 1]
// Or leave the original alone and build a new list
List<Order> active = orders.stream()
.filter(o -> !o.isCancelled())
.toList(); // unmodifiable list, Java 16 and later

Choose between them by ownership. removeIf changes the list in place, which is right when the list is ours and nobody else holds a reference expecting the old contents. The stream version leaves the original untouched and returns a new list, which is safer when the list came from a caller, is shared, or is itself unmodifiable. Notice that Stream.toList() returns an unmodifiable list; if the caller needs to add to it later, collect with Collectors.toCollection(ArrayList::new) instead.

6What Concurrent Collections Do Instead

Collections from java.util.concurrent do not fail fast. Their iterators are weakly consistent: they never throw ConcurrentModificationException, they never return an element twice, and they may or may not show changes made after the iterator was created. CopyOnWriteArrayList goes further: its iterator reads a snapshot of the array taken when iteration began, so removing from the list inside the loop is allowed and the loop still visits all original elements. But its iterator's own remove() throws UnsupportedOperationException, and every write copies the whole array, so it suits lists that are read far more often than they are changed, like listener lists. Swapping to a concurrent collection only to silence this exception is the wrong fix; in single-threaded code, removeIf is the answer.

7Follow-up questions

Does the same problem happen with a HashMap?

Yes. Iterating over map.keySet(), values() or entrySet() and calling map.remove() inside the loop fails in the same way, because HashMap also keeps a modCount. The fixes are the same: use the iterator's remove(), or map.entrySet().removeIf(e -> ...), or map.values().removeIf(...).

Would a classic index loop work?

A loop with for (int i = 0; i < orders.size(); i++) does not throw, but removing at index i shifts the next element into position i, and then i++ skips it. It works only if we decrement i after each removal or loop backwards from the end. Both are easy to get wrong, so removeIf is the clearer choice.

Is it safe to modify an element's fields during iteration?

Yes. Changing a field of an Order, such as setting its status, is not a structural modification of the list, so modCount does not change and the iterator is unaffected. Only operations that change the list's size, or replace its backing structure, count. Note that ArrayList.set does not increment modCount either.

8Conclusion

In this answer, we saw that the for-each loop is a hidden Iterator, that ArrayList counts structural changes in modCount, and that the iterator compares that count with its own expectedModCount in next() and fails fast when the list changed behind it. We saw that the check is only best effort, since removing the second-to-last element ends the loop silently and skips an element. The correct fixes are it.remove() in an explicit iterator loop, removeIf with a predicate, or a new filtered list from a stream, while concurrent collections use weakly consistent iterators that never throw.

What to say in the interviewAbout 80 seconds aloud

Open with

The enhanced for loop is just sugar for an iterator: it calls orders.iterator(), then hasNext and next in a loop. ArrayList keeps a modCount that goes up on every structural change, and the iterator saves that value when it is created.

Then, if they want more

When I call orders.remove(o) directly, the list's count goes up but the iterator's saved count does not, so the next call to next sees they differ and throws ConcurrentModificationException. It is called concurrent even though there is one thread, because the list was modified during the iteration.

The check is best effort: if I remove the second-to-last element, hasNext returns false and the loop ends without an exception, but the last element was never checked, so I would never rely on the exception for correctness. To fix it I have three options.

I can write an explicit iterator loop and call it.remove, which keeps the iterator and list in sync. Simplest is orders.removeIf(Order::isCancelled), which is also more efficient on ArrayList because it shifts elements once. Or if I should not mutate the list, I build a new one with a stream filter and toList.

Concurrent collections behave differently: their iterators are weakly consistent and never throw, but I would not switch to one just to hide this bug.

About this answer

Last updated
12 November 2026
Versions it names
Java 16, Java 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This code throws ConcurrentModificationException:": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/7da2ded85b/