Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

Code iterates a Collections.synchronizedList with an enhanced for loop and occasionally throws ConcurrentModificationException, but list.forEach(...) never does. Explain, and show how to iterate correctly.

Collections.synchronizedList locks each method call separately, and its forEach and removeIf hold that lock for the whole operation, so they cannot interleave with other threads' writes. iterator() is different: it returns the underlying list's fail-fast iterator, and each hasNext() and next() runs without the wrapper's lock, so an enhanced for loop can interleave with writes from other threads. The Javadoc requires manual iteration to be wrapped in synchronized (list) { ... }; when that blocks writers too long, copy under the lock and iterate the copy, or switch to a concurrent collection.

Why this question is asked

Collections.synchronizedList looks like a simple way to make a list thread-safe, and for single calls it is. Iteration is where that simplicity breaks, and the fact that list.forEach works while the enhanced for loop fails is a good clue to what the wrapper actually does. Interviewers ask this to see whether we understand the difference between thread-safe methods and thread-safe compound operations, and whether we know the documented rule for iterating these wrappers. In this answer, we will look inside the wrapper, see why forEach is safe and the loop is not, fix the loop, and compare the alternatives.

1What the Synchronized Wrapper Does

Collections.synchronizedList(list) returns a wrapper object that holds the real list and a lock object, called the mutex, which by default is the wrapper itself. Every method of the wrapper does the same thing: take the mutex, call the same method on the real list, release the mutex. So any single call, add(), get(), size(), is atomic with respect to every other call made through the wrapper.

Java
// a simplified picture of the wrapper, close to the JDK source
class SynchronizedList<E> implements List<E> {
final List<E> list; final Object mutex = this;
public boolean add(E e) { synchronized (mutex) { return list.add(e); } }
public E get(int i) { synchronized (mutex) { return list.get(i); } }
public void forEach(Consumer<? super E> a) { synchronized (mutex) { list.forEach(a); } }
public boolean removeIf(Predicate<? super E> f) { synchronized (mutex) { return list.removeIf(f); } }
public Iterator<E> iterator() { return list.iterator(); } // must be manually synched by user
}

Notice the last line. The JDK source comments it the same way: iterator() hands back the underlying ArrayList's own iterator and takes no lock, because a lock taken inside iterator() would be released the moment the method returned, long before the loop is done.

2Why forEach Is Safe and the Loop Is Not

forEach and removeIf are single method calls on the wrapper, and the wrapper holds the mutex for their whole duration. While one thread is inside list.forEach(...), any other thread calling list.add(...) waits at the mutex. No write can happen during the iteration, so the ArrayList's modCount never changes under it.

The enhanced for loop calls iterator() once, then hasNext() and next() many times on the raw ArrayList iterator, with no lock at all. Between any two of those calls, another thread can call add() through the wrapper, which takes the mutex briefly, changes the list and releases it. The iterator's next() then sees a changed modCount and throws, or, because the read is unsynchronized, sometimes reads stale state without throwing.

Step throughThe loop interleaves with a writer
Reader threadWrapper mutexArrayListWriter thread
iterator(): no lock taken
next() -> element 0, no lock
add(x): acquire mutex
list.add(x): modCount + 1
release mutex
next(): modCount changed
ConcurrentModificationException

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

Each write is atomic, but the loop as a whole is not protected.

3Fix: Hold the Lock for the Whole Loop

The Collections.synchronizedList Javadoc states the rule: it is imperative that the user manually synchronize on the returned list when traversing it via Iterator, Spliterator or Stream. We synchronize on the wrapper itself, because that is the mutex every wrapper method uses.

Java
List<String> list = Collections.synchronizedList(new ArrayList<>());
synchronized (list) { // the same lock the wrapper's methods use
for (String s : list) {
process(s); // no add() from other threads can run now
}
}
// writers calling list.add(...) wait until the block ends

Locking on the inner ArrayList or on some other object would not work, because writers through the wrapper take the wrapper's mutex, not ours. The same applies to list.stream() and list.spliterator(), which are also unsynchronized: a stream pipeline over a synchronized list must run inside the same synchronized block.

4When the Lock Is Held Too Long

Holding the lock for the whole loop is correct, but every writer waits for as long as the loop runs. If process(s) calls a database or a remote service, a loop over 10,000 elements can block writers for seconds, and any thread that tries to add while holding another lock risks a deadlock with code inside process(). There are two common ways out.

Java
// copy under the lock, iterate outside it
List<String> snapshot;
synchronized (list) {
snapshot = new ArrayList<>(list); // a few microseconds for thousands of elements
}
for (String s : snapshot) process(s); // slow work without blocking writers
Ways to iterate a list shared between threads
ApproachWriters blocked?Reader seesFits
synchronized (list) { for ... }For the whole loopExact stateShort loops
Copy under lock, iterate copyOnly during the copySnapshotSlow loop bodies
list.forEach(...) on the wrapperFor the whole loopExact stateShort actions
CopyOnWriteArrayListNeverSnapshotRead-mostly lists
ConcurrentLinkedQueueNeverWeakly consistentAppend and drain

The copy is a point-in-time snapshot, so the loop works on the state at the moment of the copy and does not see later additions, which is usually what we want. The second way out is to stop using the wrapper. A CopyOnWriteArrayList gives the same snapshot iteration with no lock on reads, which suits read-mostly lists, and a ConcurrentLinkedQueue or ConcurrentLinkedDeque gives weakly consistent iteration that never throws, which suits lists that are mostly appended and drained.

5Follow-up questions

Does Vector have the same problem?

Yes. Vector synchronizes each method, but its iterator, like the wrapper's, is fail-fast and not locked across the loop. Iterating a Vector while other threads modify it needs synchronized (vector) around the loop, which is one reason Vector offers little over an ArrayList in a wrapper.

Is the copy constructor itself safe without the synchronized block?

new ArrayList<>(list) calls list.toArray(), which the wrapper does synchronize, so the copy alone would be consistent. Writing the synchronized block anyway makes the intent obvious and stays correct if the copying code is later changed to something that iterates.

Can the lambda passed to forEach call list.add on the same list?

The thread already holds the mutex, and Java's synchronized locks are re-entrant, so the add() runs. But it changes the list during the ArrayList's own forEach, which detects the modCount change and throws ConcurrentModificationException. Holding the lock protects against other threads, not against the loop modifying itself.

6Conclusion

In this answer, we saw that Collections.synchronizedList locks each method call, and that forEach and removeIf are single calls that hold the lock for the whole operation, while iterator() returns an unlocked, fail-fast iterator whose calls interleave with other threads' writes. The fix the Javadoc requires is synchronized (list) around the loop, using the wrapper as the lock. When that blocks writers too long, we copy under the lock and iterate the copy, or move to CopyOnWriteArrayList or a concurrent queue.

What to say in the interviewAbout 90 seconds aloud

Open with

The synchronized wrapper works by taking one mutex, the wrapper itself, around every method call. So add, get and size are each atomic, and forEach and removeIf are too, because they're single calls on the wrapper and the wrapper holds the lock for the whole traversal.

Then, if they want more

That's why list.forEach never throws: no other thread can write until it finishes. iterator() is the exception. It just returns the underlying ArrayList's fail-fast iterator and takes no lock, because a lock inside iterator() would be released as soon as it returns.

The enhanced for loop then calls hasNext and next without any lock, other threads' adds interleave between those calls, and the iterator sees modCount change and throws ConcurrentModificationException, or reads stale data.

The Javadoc is explicit that you must manually synchronize on the returned list when iterating, so the fix is synchronized (list) around the whole for loop, locking on the wrapper, not the inner list, and the same applies to streams over it. The trade-off is that writers are blocked for the whole loop.

If the loop body is slow, I'd copy the list inside the synchronized block and iterate the copy outside it. And if the list is read much more than written, I'd replace the wrapper with a CopyOnWriteArrayList, which iterates a snapshot with no locking, or use a concurrent queue with weakly consistent iteration if it's mostly appended and drained.

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 "Code iterates a Collections.synchronizedList with an enhanced for loop and occasionally...": https://scrivio-interview-library.netlify.app/java/iteration/96296b48f3/