Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A single-threaded event bus iterates its listeners list and calls each listener; one listener unregisters itself during the callback. The application throws ConcurrentModificationException even though there is only one thread. Explain and fix.

ConcurrentModificationException is about changing a collection while iterating it, not about threads: the bus iterates its ArrayList of listeners, a listener calls unregister() during its callback, and that removal from the same list makes the iterator's next call to next() throw. Store listeners in a CopyOnWriteArrayList, whose iterator walks a snapshot, or iterate over a copy, or defer removals until the loop has finished; CopyOnWriteArrayList also keeps registration safe if other threads start registering later.

Why this question is asked

Event buses, observers and callback lists appear in almost every application, and a listener that unsubscribes itself after handling one event is a very natural thing to write. The resulting exception confuses many developers because of its name: there is only one thread, so how can anything be concurrent? Interviewers ask this to check that we understand what the exception really detects. In this answer, we will reproduce the problem, see why it happens with a single thread, and compare three fixes and when to use each.

1Reproducing the Problem

Here is a minimal event bus. It keeps listeners in an ArrayList and calls each one in a loop. One listener handles the first event and then removes itself.

Java
class EventBus {
private final List<Listener> listeners = new ArrayList<>();
void register(Listener l) { listeners.add(l); }
void unregister(Listener l) { listeners.remove(l); }
void publish(Event e) {
for (Listener l : listeners) l.onEvent(e); // hidden Iterator over listeners
}
}
bus.register(e -> log("A"));
bus.register(new Listener() {
public void onEvent(Event e) { log("once"); bus.unregister(this); }
});
bus.register(e -> log("C"));
bus.publish(new Event()); // logs A, once, then ConcurrentModificationException

Notice that the listener that removes itself does nothing wrong from its own point of view. The problem is where the call happens: inside publish(), while the for loop is still iterating the same list.

2Why One Thread Is Enough

The enhanced for loop uses the list's Iterator. ArrayList counts structural changes in a field called modCount, and the iterator remembers the value it started with. The listener's unregister() call removes an element directly from the list, so modCount goes up. When the loop asks for the next listener, the iterator sees that the count has changed and throws.

Nothing here involves a second thread. The name ConcurrentModificationException means modification concurrent with iteration, that is, while an iteration is in progress, and the call stack makes that visible: publish() calls onEvent(), which calls unregister(), which changes the list publish() is still walking.

Step throughThe removal happens inside the loop
publish() looplisteners listonce listener
next() -> listener A, called
next() -> once listener
onEvent(e)
unregister(this): remove, modCount + 1
returns
next(): modCount changed
ConcurrentModificationException

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

One thread, one call stack. The callback changes the list its caller is iterating.

3A Variant That Fails Silently

There is a nastier version of the same bug. If the self-removing listener happens to be the second-to-last in the list, no exception is thrown at all. After the removal, the iterator's cursor equals the new size, so hasNext() returns false and the loop ends, and the last listener is never called for this event.

So depending on registration order, the same code either throws or silently skips a listener. That is a strong reason to fix the design rather than to rely on the exception to tell us something is wrong.

4Fix 1: CopyOnWriteArrayList

CopyOnWriteArrayList is designed for exactly this kind of list: read on every event, changed rarely. Every write copies the internal array and swaps in the new one, and every iterator walks the array that was current when it started.

Java
class EventBus {
private final List<Listener> listeners = new CopyOnWriteArrayList<>();
void register(Listener l) { listeners.add(l); }
void unregister(Listener l) { listeners.remove(l); } // creates a new array
void publish(Event e) {
for (Listener l : listeners) l.onEvent(e); // walks the old array
}
}
bus.publish(new Event()); // logs A, once, C
bus.publish(new Event()); // logs A, C

Notice the semantics: the listener that removed itself is still part of the current publish, because the loop walks the snapshot, and it is gone from the next one. Listeners registered during a publish also wait for the next event. That is usually exactly what an event bus should do. It also makes the bus safe if, later, other threads register or unregister listeners while events are being published, which is common once a bus is shared.

5Fix 2 and 3: Iterate a Copy, or Defer the Removal

If we want to keep the ArrayList, we can iterate over a copy, which is the same idea as copy-on-write but paying the copy on every publish instead of on every change. Or we can make removal requests during a publish wait until the loop ends.

Java
// Fix 2: iterate a copy
void publish(Event e) {
for (Listener l : List.copyOf(listeners)) l.onEvent(e); // changes affect the original only
}
// Fix 3: defer removals
private final List<Listener> pendingRemovals = new ArrayList<>();
private boolean publishing;
void unregister(Listener l) {
if (publishing) pendingRemovals.add(l); else listeners.remove(l);
}
void publish(Event e) {
publishing = true;
try { for (Listener l : listeners) l.onEvent(e); }
finally {
publishing = false;
listeners.removeAll(pendingRemovals);
pendingRemovals.clear();
}
}

Copying on each publish is simple and fine when events are rare and lists are short. Deferring gives full control, for example to skip a listener removed earlier in the same publish, but it is more code and, as written, it is only correct for a single thread, and it does not handle nested publishes from inside a listener. For most buses, CopyOnWriteArrayList is the best balance.

6Follow-up questions

Would Collections.synchronizedList fix this?

No. Synchronization prevents two threads from changing the list at the same moment, but here a single thread changes it during its own iteration. The synchronized wrapper's iterator is still fail-fast, and a lock held by publish() would be re-entered by the same thread in unregister(), so nothing stops the removal.

Is CopyOnWriteArrayList expensive?

Each write copies the array, so registering a listener in a list of 50 costs copying 50 references, which is trivial. It becomes a problem only when the list is large and changes often, which listener lists rarely do. Reads and iteration cost nothing extra.

How does Spring's event system handle this?

Spring's ApplicationEventMulticaster retrieves the listeners for an event type into its own collection before invoking them, so listeners changing registration during a publish do not break the loop. We get the same effect in our own bus with a snapshot.

7Conclusion

In this answer, we saw that ConcurrentModificationException needs no second thread: a listener that unregisters itself during its callback removes an element from the list that publish() is iterating, so the iterator detects the changed modCount and throws, or, if the listener was second-to-last, silently skips the last listener. CopyOnWriteArrayList fixes it by iterating a snapshot and also makes later multi-threaded registration safe. Iterating a copy or deferring removals until the loop finishes are the alternatives when we want to keep the plain list.

What to say in the interviewAbout 90 seconds aloud

Open with

The exception isn't about threads at all. ConcurrentModificationException means the collection was structurally changed while an iteration over it was in progress, by something other than that iterator.

Then, if they want more

Here publish uses a for-each loop, which is an Iterator over the ArrayList, and calls each listener. When a listener calls unregister on itself, that removes it from the same list, modCount goes up, and when the loop calls next again the iterator sees the mismatch and throws. It's all one call stack: publish, onEvent, unregister.

There's an even worse variant: if the listener is second-to-last, hasNext just returns false, the loop ends early and the last listener silently misses the event. My preferred fix is to store listeners in a CopyOnWriteArrayList.

Every change copies the array, and the iterator walks the snapshot it started with, so a listener removing itself during a publish still finishes the current event and is gone from the next one.

Listener lists are read much more than they change, so the copy cost is negligible, and it also makes registration safe if other threads start registering listeners later, which usually happens once a bus is shared.

Alternatives are iterating over a copy, like List.copyOf, in each publish, or recording removals during a publish and applying them after the loop, which gives more control but is more code.

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 "A single-threaded event bus iterates its listeners list and calls each listener; one...": https://scrivio-interview-library.netlify.app/java/iteration/c327f18731/