Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A single-threaded loop throws ConcurrentModificationException: for (Order o : orders) if (o.isCancelled()) orders.remove(o); Explain why and give three correct alternatives.

The enhanced for loop walks the list with a hidden Iterator, and ArrayList's iterator is fail-fast: it remembers the list's modification count and throws ConcurrentModificationException as soon as the list is changed by anything other than the iterator itself. Calling orders.remove(o) inside the loop changes the count, so the next call to next() throws, even with a single thread. The three safe alternatives are orders.removeIf(Order::isCancelled), an explicit Iterator with iterator.remove(), or building a new filtered list with a stream.

Why this question is asked

Removing items while looping over a list is one of the first bugs most Java developers write, and it keeps coming back in production code because the loop looks perfectly innocent. Interviewers ask it because the exception's name misleads people into hunting for a second thread that does not exist, and because the answer shows whether we know what the enhanced for loop really compiles to. In this answer, we will recap what the for-each loop does behind the scenes, see exactly where the exception comes from, look at a strange case where the bug hides, and then go through three correct ways to remove the cancelled orders and what to do when several threads really are involved.

1A Quick Recap of the Enhanced For Loop

The enhanced for loop, for (Order o : orders), is shorthand. The compiler turns it into code that asks the list for an Iterator, an object whose job is to walk through the elements one at a time, and then calls hasNext() and next() on it until hasNext() returns false.

So even though our code never mentions an iterator, one is there, and it is the iterator that throws. The loop body runs between two calls to next(), and that is where our remove happens.

Java
// What we wrote
for (Order o : orders) if (o.isCancelled()) orders.remove(o);
// Roughly what the compiler generates
Iterator<Order> it = orders.iterator();
while (it.hasNext()) {
Order o = it.next(); // the check happens here
if (o.isCancelled()) orders.remove(o); // changes the list behind the iterator's back
}

Notice that the removal goes through orders.remove(o), the list's own method, not through the iterator. The iterator has no idea it happened.

2Why the Iterator Throws: modCount and Fail-Fast Checks

ArrayList keeps an int field called modCount, which counts structural modifications: any add or remove that changes the size. When we create an iterator, it copies the current modCount into its own field, expectedModCount. Every call to next() compares the two. If they differ, the iterator knows the list changed underneath it and throws ConcurrentModificationException.

The reason for this design is safety. After a removal, every element to the right shifts one place left, so the iterator's position now points at the wrong element. Carrying on would silently skip an element or read past the end. Instead of guessing, the iterator fails fast: it stops at the first sign of trouble with a clear exception. Collections whose iterators behave like this are called fail-fast.

Java
List<Order> orders = new ArrayList<>(List.of(a, cancelledB, c, d));
for (Order o : orders) {
if (o.isCancelled()) orders.remove(o); // removes cancelledB, modCount goes from 0 to 1
}
// next() on the following pass sees expectedModCount 0 != modCount 1
// java.util.ConcurrentModificationException
Step throughOne pass of the loop that throws
  1. it.next() returns cancelledBexpectedModCount = 0, modCount = 0
  2. orders.remove(cancelledB)size 4 -> 3, modCount = 1
  3. it.hasNext(): cursor != size?
    YesCall it.next()NoLoop ends quietly
  4. it.next(): modCount == expectedModCount?
    YesReturn the next orderNoThrow ConcurrentModificationException

4 steps in order. Play them, or step through them one at a time.

So the word concurrent in the name does not mean threads. It means the list was modified concurrently with an iteration over it, and a single thread can do that perfectly well. The check is also best-effort, so we must never rely on it for correctness.

3The Case Where the Bug Hides

There is a catch that makes this bug harder to spot. hasNext() does not check modCount; it only compares its cursor with the current size. If the cancelled order is the second-to-last element, the removal shrinks the size so that the cursor equals the size, hasNext() returns false, and the loop ends without any exception.

Java
List<Order> orders = new ArrayList<>(List.of(a, b, cancelledC, d));
for (Order o : orders) if (o.isCancelled()) orders.remove(o);
// no exception, but d was never checked
System.out.println(orders.size()); // 3

Notice what happened: the last order was never even looked at. If d had also been cancelled, it would still be in the list. So a test can pass while production data fails.

4Fix 1: removeIf

Since Java 8, every Collection has removeIf, which takes a predicate and removes every element that matches. It is the shortest and clearest fix, and it says exactly what we mean.

Java
orders.removeIf(Order::isCancelled);
System.out.println(orders.size()); // 2, both cancelled orders gone

ArrayList overrides removeIf so that it first finds the matching elements and then compacts the array in one pass. That makes it O(n) for the whole list. The naive loop, even when it does not throw, is O(n squared) in the worst case, because each remove shifts the rest of the array. For a list of 100,000 orders with many cancellations, the difference is large.

5Fix 2: An Explicit Iterator With iterator.remove()

If we need more logic in the loop, for example logging or counting what we remove, we can write the iterator ourselves and remove through it.

Java
Iterator<Order> it = orders.iterator();
while (it.hasNext()) {
Order o = it.next();
if (o.isCancelled()) {
it.remove(); // the iterator updates expectedModCount itself
log.info("removed {}", o.id());
}
}

This works because iterator.remove() removes the element and then sets expectedModCount to the new modCount, and it also moves its cursor back so no element is skipped. The iterator is the one making the change, so it stays consistent. Notice, though, that each removal still shifts the array, so for an ArrayList with many removals this is O(n squared); for a LinkedList it is O(n).

6Fix 3: Build a New Filtered List

The third option does not modify the list at all. We create a new list containing only the orders we want to keep.

Java
List<Order> active = orders.stream()
.filter(o -> !o.isCancelled())
.toList(); // Java 16+, returns an unmodifiable list
System.out.println(active.size()); // 2

This is often the cleanest choice when the original list is shared, comes from somewhere else, or might be unmodifiable (List.of results throw UnsupportedOperationException on any remove). The cost is a second list in memory, which is usually fine. If the rest of the code needs a mutable list, collect with Collectors.toCollection(ArrayList::new) instead of toList().

7When Several Threads Really Are Involved

Everything above assumes one thread. If one thread iterates while another removes, removeIf and iterator.remove() are not enough, because ArrayList itself is not thread-safe and the fail-fast check is not guaranteed to fire. We then need either proper locking around every access, or a concurrent collection.

CopyOnWriteArrayList gives each iterator a snapshot, so iteration never throws; it suits lists that are read far more often than they change, because every write copies the array. Concurrent collections such as ConcurrentLinkedQueue have weakly consistent iterators that never throw. The rule is simple: either one owner modifies the collection, or the collection is designed for sharing.

8Follow-up questions

Why does the same loop over a CopyOnWriteArrayList not throw?

Because its iterator works on a snapshot: the array as it was when the iterator was created. Calling list.remove(o) replaces the internal array with a new copy, but the iterator keeps reading the old one. The loop finishes and the cancelled orders are removed, at the cost of copying the array on every removal. Note that iterator.remove() on a CopyOnWriteArrayList iterator throws UnsupportedOperationException, so there we remove through the list or use removeIf.

Does an index-based for loop avoid the problem?

It avoids the exception, because there is no iterator, but it introduces a classic off-by-one bug: after removing index i, the next element moves into position i and the loop's i++ skips it. Looping backwards from size() - 1 down to 0 fixes that, but removeIf is clearer and faster.

9Conclusion

In this answer, we saw that the enhanced for loop uses a hidden iterator, and that ArrayList's iterator compares the list's modCount with the value it remembered, throwing ConcurrentModificationException when the list is changed by anything but the iterator. That happens with a single thread, and it can even hide when the removed element is second to last. We then fixed it three ways: removeIf, which is O(n) and the clearest; an explicit iterator with iterator.remove(); and a stream that builds a new list. For real multi-threaded access, we need locking or a concurrent collection instead.

What to say in the interviewAbout 80 seconds aloud

Open with

The for-each loop is compiled into an Iterator, and ArrayList's iterator is fail-fast. The list keeps a modCount that increases on every structural change, the iterator copies it when it is created, and each next() call compares the two.

Then, if they want more

When I call orders.remove inside the loop, the list changes behind the iterator's back, so the next call to next() throws ConcurrentModificationException. No second thread is needed; concurrent here means modified during iteration. It can even hide: if the removed element is second to last, hasNext returns false and the last element is never checked.

I would fix it in one of three ways. The best is orders.removeIf(Order::isCancelled), which is clear and O(n) because ArrayList compacts the array in one pass. If I need extra logic per element, I use an explicit iterator and call iterator.remove, which keeps the iterator's expected count in step.

Or, if the list is shared or might be unmodifiable, I build a new list with a stream filter. If several threads really touch the list, none of those is enough on its own, and I would use locking or a concurrent collection such as CopyOnWriteArrayList for read-mostly data.

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 documentation below. 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 "A single-threaded loop throws ConcurrentModificationException: for (Order o : orders) if...": https://scrivio-interview-library.netlify.app/java/exceptions/b2da2e2231/