Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

You are designing a shared event listener registry where listeners can unregister themselves while an event is being dispatched. Which list implementation and design would you choose, and why?

We would store listeners in a CopyOnWriteArrayList. Dispatch iterates a snapshot of the array, so listeners can add or remove themselves during an event without ConcurrentModificationException and without locks on the read path, which suits a list that is read on every event and changed rarely. A removal during dispatch takes effect from the next event, which we document; for lists that change very often, we would copy under a lock instead, and either way unregistering must really drop the reference so removed listeners can be garbage collected.

Why this question is asked

Listener registries look trivial, a list of callbacks, until a listener unregisters itself from inside its own callback, or another thread registers one in the middle of a dispatch. Then a plain ArrayList throws ConcurrentModificationException or, worse, skips listeners. Interviewers ask this design question because it combines iteration semantics, concurrency, memory leaks and API design. In this answer, we will see why the obvious design fails, build the registry on CopyOnWriteArrayList, define what happens when a listener removes itself mid-dispatch, look at the alternative for high-churn lists, and make unregistering leak-free.

1Why a Plain ArrayList Fails

The obvious registry holds an ArrayList and loops over it with for-each to dispatch. If a listener's callback calls unregister(this), the list is modified while the loop's iterator is active. The iterator notices the changed modification count and throws ConcurrentModificationException on its next step, or, if the removed listener was second-last, ends the loop early and the last listener never hears the event. With several threads registering and dispatching, it is also simply not thread-safe.

Java
class NaiveRegistry {
private final List<Listener> listeners = new ArrayList<>();
void register(Listener l) { listeners.add(l); }
void unregister(Listener l) { listeners.remove(l); }
void dispatch(Event e) { for (Listener l : listeners) l.onEvent(e); }
}
registry.register(e -> registry.unregister(/* itself */ ...));
registry.dispatch(event); // ConcurrentModificationException, or a silently skipped listener

2Building the Registry on CopyOnWriteArrayList

CopyOnWriteArrayList keeps its elements in an array that is never modified in place. Every add or remove creates a new array with the change, then swaps it in with a volatile write. An iterator captures the array that was current when it was created, a snapshot, and walks that array, which nobody will ever change. So dispatch needs no lock, never sees a half-made change, and never throws ConcurrentModificationException.

Java
public final class ListenerRegistry<E> {
private final List<Consumer<? super E>> listeners = new CopyOnWriteArrayList<>();
public Registration register(Consumer<? super E> listener) {
Objects.requireNonNull(listener);
listeners.add(listener);
return () -> listeners.remove(listener); // a handle the caller keeps to unregister
}
public void dispatch(E event) {
for (Consumer<? super E> l : listeners) { // iterates a snapshot
try {
l.accept(event);
} catch (RuntimeException ex) {
log.warn("listener failed", ex); // one bad listener does not stop the others
}
}
}
public interface Registration extends AutoCloseable { @Override void close(); }
}
Step throughA listener removes itself during dispatch
DispatcherRegistry listListener AListener B
iterator(): snapshot [A, B]
onEvent(e1)
remove(A): new array [B]
onEvent(e1) from the snapshot
next event: snapshot [B]
onEvent(e2)

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

The removal is not seen by the dispatch already in progress.

The trade-off is the cost of a change: each register or unregister copies the whole array, O(n). For listeners that is a good bargain. A registry of 50 listeners is read on every event, perhaps thousands of times a second, and changed a handful of times during its life. Reads are as fast as iterating a plain array. Notice also two details beyond the list itself: each listener call is wrapped so one exception does not stop delivery to the rest, and register returns a Registration handle.

3What Removal During Dispatch Means

Because each dispatch walks a snapshot, a change made during dispatch is visible only from the next event. Two cases follow. If listener A unregisters itself, it has already received the current event, and it will not receive the next one, which is what callers expect. If listener A unregisters listener B, and B comes later in the snapshot, B still receives the current event. Likewise, a listener registered during a dispatch receives events from the next one only.

These are reasonable semantics, but they must be written down, because the second case surprises people. A listener that has been told to stop, for example because its screen was closed, might still get one more callback. Listeners that cannot tolerate that check their own closed flag at the start of onEvent.

Effect of changes made during a dispatch
Change during dispatch of event 1Event 1Event 2
A unregisters itselfA already notifiedA not notified
A unregisters B (later in list)B still notifiedB not notified
A registers CC not notifiedC notified
Another thread registers DD not notifiedD notified
Write these rules in the registry's Javadoc.

4High-Churn Lists: Copy Under a Lock

Copy-on-write becomes expensive when changes are frequent and the list is large, for example thousands of short-lived subscriptions per second on a list of 10,000 entries: each change copies 10,000 references. In that case we keep a plain ArrayList guarded by a lock, change it under the lock, and at dispatch take a copy under the lock and call listeners outside it.

Java
private final List<Listener> listeners = new ArrayList<>();
private final Object lock = new Object();
void dispatch(Event e) {
List<Listener> snapshot;
synchronized (lock) { snapshot = List.copyOf(listeners); } // short critical section
for (Listener l : snapshot) l.onEvent(e); // callbacks run without the lock
}

The important rule is in the last line: never call listeners while holding the lock. A callback might block, take another lock, or call back into the registry, and holding our lock during foreign code is how deadlocks happen. This design copies once per dispatch instead of once per change, so it wins when changes outnumber dispatches.

5Unregistering Without Leaks

A registry that outlives its listeners is the classic source of memory leaks: a screen or a session registers a listener, is closed, and forgets to unregister, so the registry keeps the listener, and through it the whole screen, alive. The answer is to make unregistering easy and real. Our register returns a Registration handle that removes exactly that listener, and it is AutoCloseable, so owners can use try-with-resources or close it in their own lifecycle method. Using a handle also avoids a subtle bug with lambdas: remove(listener) uses equals, and two lambdas with the same body are different objects, so unregistering with a new lambda removes nothing.

Weak references, where the registry holds listeners through WeakReference, are sometimes suggested so forgotten listeners are collected automatically. We would avoid them as the default: a lambda that nothing else references is collected almost immediately, so the listener silently stops working. Explicit handles make ownership clear.

6Follow-up questions

Why not use Collections.synchronizedList for the registry?

Its individual methods lock, but iteration is many calls, so dispatch would have to hold the list's lock for the whole loop, which means calling listeners while holding a lock, the deadlock risk we want to avoid. It also blocks registration during every dispatch. CopyOnWriteArrayList or copy-under-lock avoid both problems.

Should dispatch be synchronous or asynchronous?

Synchronous dispatch is simpler and keeps ordering, but a slow listener delays everyone. If listeners may be slow or the event source must not block, we hand each event to an executor, and then we must document ordering and what happens to events when the executor is full. The list choice stays the same.

How does iteration order work in CopyOnWriteArrayList?

It is insertion order, like ArrayList, so listeners are called in the order they registered. If a listener registers twice, it is called twice, so a registry that must prevent duplicates uses addIfAbsent, or a CopyOnWriteArraySet.

7Conclusion

In this answer, we saw that a plain ArrayList registry breaks when listeners unregister during dispatch. CopyOnWriteArrayList fixes it: changes copy the array, and dispatch iterates a snapshot without locks, which suits read-mostly listener lists. Changes during dispatch take effect from the next event, which we document. For high-churn lists we copy under a lock and call listeners outside it, and in both designs a Registration handle makes unregistering reliable so removed listeners can be garbage collected.

What to say in the interviewAbout 100 seconds aloud

Open with

I would build it on CopyOnWriteArrayList. Every add or remove creates a new array and swaps it in, and an iterator walks the array that was current when it started, a snapshot that never changes.

Then, if they want more

So dispatch needs no lock and never throws ConcurrentModificationException, even when a listener unregisters itself inside its callback. With a plain ArrayList that would throw, or silently skip the last listener. The cost is that each change copies the array, but listener lists are read on every event and changed rarely, so that is the right trade.

I would document the semantics: a change during dispatch applies from the next event. A listener that removes itself has already been notified, but if it removes another listener later in the list, that one still gets the current event, and a newly registered one starts with the next event.

I would wrap each callback in a try-catch so one failing listener does not stop the others. If the list were large and changed constantly, I would switch to a plain list under a lock, copying it under the lock at dispatch and calling listeners outside the lock, because calling foreign code while holding a lock invites deadlocks.

Finally, register returns an AutoCloseable registration handle, so unregistering is easy and really drops the reference, which prevents leaks. It also avoids the lambda equality trap. I would not default to weak references, since unreferenced lambdas would vanish.

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 "You are designing a shared event listener registry where listeners can unregister...": https://scrivio-interview-library.netlify.app/java/lists/2c6f61d3b2/