Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

Two threads use a Collections.synchronizedList. One iterates with for-each while the other adds, and ConcurrentModificationException appears. Why, and what are the options?

Collections.synchronizedList locks each method call separately, but a for-each loop is many calls to an iterator, and between them the other thread's add gets the lock, changes the list, and the iterator then detects the change and throws ConcurrentModificationException. The Javadoc requires the iterating thread to hold the list's own lock for the whole loop with synchronized (list). The alternatives are CopyOnWriteArrayList, which iterates over a snapshot and suits read-heavy lists, or copying the list under the lock and iterating the copy; compound operations such as check-then-add need external locking too.

Why this question is asked

Many developers assume that a synchronized collection is thread-safe in every way, so this exception feels like a bug in the JDK. It is not; it is the exact limit of what a synchronized wrapper can promise. Interviewers ask this to see whether we understand the difference between making single operations atomic and making a sequence of operations atomic, which is the core of most concurrency bugs. In this answer, we will recap how the wrapper and fail-fast iterators work, reproduce the failure, follow it step by step, and then compare the fixes and their costs.

1A Quick Recap: The Wrapper and Fail-Fast Iterators

Collections.synchronizedList(list) returns a wrapper whose every method, such as add, get or size, runs inside synchronized on one lock object, which by default is the wrapper itself. So two threads can never be inside add at the same time, and each single call sees a consistent list.

An ArrayList iterator is fail-fast. The list keeps a counter called modCount that increases on every structural change, such as an add or remove. When we create an iterator, it remembers the current modCount. On every call to next(), it compares the remembered value with the list's current one, and if they differ, it throws ConcurrentModificationException rather than continue with a list that changed under it. This is a best-effort check designed to expose bugs early.

2Reproducing the Problem

One thread keeps adding events, while another periodically iterates to send them. The iterating thread uses a plain for-each loop.

Java
List<String> events = Collections.synchronizedList(new ArrayList<>());
// Thread A: producer
for (int i = 0; i < 100_000; i++) events.add("e" + i);
// Thread B: reporter
for (String e : events) { // events.iterator(), then hasNext()/next() repeatedly
send(e);
}
// Exception in thread "reporter" java.util.ConcurrentModificationException
// at java.util.ArrayList$Itr.checkForComodification(...)
// at java.util.ArrayList$Itr.next(...)

Notice where the exception comes from: ArrayList's own iterator. The wrapper's iterator() method does not wrap the iterator in any lock; it returns the underlying list's iterator directly. The documentation says this explicitly, and that it is the user's job to lock during iteration.

3Why Locking Each Call Is Not Enough

The for-each loop calls iterator() once and then hasNext() and next() for each element. Only iterator() goes through the wrapper, and even that holds the lock only while the call runs. Between two next() calls, the lock is free, so thread A can take it, append an element and increase modCount. When thread B's next() runs, the iterator sees that modCount no longer matches and throws.

This is the general rule: a synchronized wrapper makes each operation atomic, but not a sequence of operations. Iteration is a sequence. So is check-then-act, such as if (!events.contains(x)) events.add(x), where another thread can add x between the contains and the add, giving us a duplicate.

Step throughHow the add slips in between two next() calls
Reporter threadWrapper lockArrayListProducer thread
iterator(): remembers modCount = 10
next() -> e0, counts match
takes the lock for add(e10)
add: modCount becomes 11
releases the lock
next(): 10 != 11
ConcurrentModificationException

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

The reporter never held the lock between calls, so nothing stopped the producer.

4Fix 1: Hold the List's Lock During Iteration

The fix the documentation prescribes is to synchronize on the list itself, the wrapper, for the whole loop. Because the wrapper's methods lock on the same object, the producer's add waits until the loop finishes.

Java
synchronized (events) { // the wrapper is the lock its methods use
for (String e : events) {
send(e);
}
} // producer's add() waits here until the loop ends

This is correct, but it has a cost: the producer is blocked for the whole iteration. If send() is a slow network call and the list has 10,000 events, every producer thread waits for all of them. Holding a lock while doing slow work is also a classic way to cause deadlocks, if send() takes another lock. So this fix fits short loops over small lists.

5Fix 2: Copy Under the Lock, Then Iterate the Copy

A refinement is to hold the lock only long enough to copy the list, and do the slow work on the copy without the lock.

Java
List<String> snapshot;
synchronized (events) {
snapshot = new ArrayList<>(events); // fast: one array copy
}
for (String e : snapshot) send(e); // no lock held while sending

Now the producer waits only for the copy, which for 10,000 references takes microseconds. The trade-off is that the reporter works on the state at the time of the copy, which is usually exactly what we want for reporting, and that each pass allocates a copy.

6Fix 3: CopyOnWriteArrayList, and Choosing Between Them

CopyOnWriteArrayList builds the snapshot idea into the collection. Every write creates a new internal array, and every iterator walks the array that existed when it was created. Iteration never throws ConcurrentModificationException and needs no lock, so readers never block writers or each other.

The cost moves to writes: each add copies the whole array. For a list of event listeners that changes a few times a day and is iterated on every event, that is ideal. For our producer adding 100,000 events, it would copy the array 100,000 times, which is far too slow. For a producer and consumer passing items, a concurrent queue such as ConcurrentLinkedQueue or a BlockingQueue is usually the right structure altogether, because the consumer takes items rather than iterating a growing list.

Compound operations still need care whichever list we choose. CopyOnWriteArrayList offers addIfAbsent for the check-then-add case. With a synchronized wrapper, we put both steps inside synchronized (list) so no other thread can act between them.

Comparing the options
OptionIterationWrite costBest for
synchronized (list) { loop }Safe, blocks writersNormalShort loops, small lists
Copy under lock, iterate copySafe, brief blockNormal; copy per passSlow work per element
CopyOnWriteArrayListSafe, never blocksCopies the whole arrayRead-heavy, rarely changed
Concurrent queueConsumer takes itemsCheapProducer-consumer flows

7Follow-up questions

Why does the exception sometimes not appear, even with the bug?

Fail-fast checks are best effort and the timing is random. If the producer happens not to add during the loop, the loop finishes cleanly. Worse, ArrayList's iterator is not designed for concurrent use at all, so an unlucky timing can also give a wrong element or skip one without any exception. That is why we must not rely on the exception to detect the bug.

Is ConcurrentModificationException only a concurrency problem?

No. The most common cause is single-threaded: removing from a list inside a for-each loop over the same list. The fix there is iterator.remove() or list.removeIf(...).

Does Vector avoid this?

No. Vector's methods are synchronized like the wrapper's, and its iterator is fail-fast in the same way, so iterating a Vector while another thread adds can throw the same exception. We still need to lock on the Vector during iteration.

8Conclusion

In this answer, we saw that a synchronized wrapper locks each call, but a for-each loop is many calls, so another thread's add slips in between them and the fail-fast iterator throws ConcurrentModificationException. We fixed it by holding the list's lock during iteration, by copying under the lock and iterating the copy, or by switching to CopyOnWriteArrayList for read-heavy lists or a concurrent queue for producer-consumer flows, and we noted that check-then-act sequences need the same external locking.

What to say in the interviewAbout 90 seconds aloud

Open with

The synchronized wrapper only makes each individual method call atomic. A for-each loop is many calls: iterator, then hasNext and next for every element, and the lock is released between them.

Then, if they want more

So while thread B is iterating, thread A can take the lock, add an element and bump the list's modCount. On the next call to next, ArrayList's fail-fast iterator sees that modCount changed and throws ConcurrentModificationException.

The wrapper's iterator method even returns the underlying iterator without any locking, and the Javadoc says the caller must synchronize on the list while iterating. So the first fix is synchronized on the list around the whole loop, which is correct but blocks every writer for the duration, so I would not do slow work like network calls inside it.

A better version for slow work is to copy the list inside the synchronized block and iterate the copy outside it.

If the list is read far more often than written, like a list of listeners, CopyOnWriteArrayList is ideal: iterators work on a snapshot and never throw, but every write copies the array, so it is wrong for a busy producer. For a producer and consumer, a concurrent queue is usually the right structure. And compound actions like check-then-add also need external locking, or addIfAbsent on CopyOnWriteArrayList.

About this answer

Last updated
12 November 2026
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 "Two threads use a Collections.synchronizedList. One iterates with for-each while the...": https://scrivio-interview-library.netlify.app/java/collections-overview/9e218ae433/