Java Design Program · CD14
Design an Event Bus in Java
When an order is placed, email, stock and SMS code all need to react. An event bus lets the order code publish once and stay unaware of who is listening.
Problem Statement
Design an EventBus with subscribe(topic, listener), publish(topic, data) and a way to unsubscribe.
Listeners of a topic run in the order they subscribed. Publishing to a topic with no listeners does nothing.
Input/Output Examples
publish("order.placed", "ORD-101")Outputemail, stock and sms notifiedExplanation: all three listeners of that topic run.remove sms, publish ORD-102Outputemail and stock notifiedExplanation: the removed listener is skipped.publish("payment.failed", ...)Outputnothing happensExplanation: unknown topics are not an error.Visual Explanation
- Subscribeorder.placedemailstocksmstopic → listeners
- PublishORD-101emailstocksmseach listener runs
- Unsubscribeorder.placedemailstocksmshandle.run()
- PublishORD-102: email, stock
The publisher and the listeners only share the topic name and the event data, which is what makes the design easy to extend.
Approaches
Both approaches deliver events in subscription order. The first indexes listeners by topic; the second keeps one list of subscriptions.
Approach 1: Map of Topic to Listeners (Recommended)
Idea: keep a ConcurrentHashMap<String, CopyOnWriteArrayList<Consumer>>; subscribe() returns a handle that removes the listener.
- Create the topic's list on first subscribe with
computeIfAbsent(). - Return a
Runnablethat removes this listener. - In
publish(), call every listener of the topic. - Use an empty list for unknown topics.
Time: O(L) · Space: O(S). L is the number of listeners of one topic and S all subscriptions.
Approach 2: Single Subscription List
Idea: store Subscription(topic, listener) records in one list and filter by topic when publishing.
- Add a subscription record on subscribe.
- Take a snapshot of the list under the lock.
- Call the matching listeners outside the lock.
Time: O(S) · Space: O(S).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Map of Topic to Listeners (Recommended)
Publishing touches only the listeners of that topic, and the copy-on-write list makes concurrent subscribe and publish safe.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
public class EventBusMap {
// Topic name -> its listeners. CopyOnWriteArrayList lets listeners unsubscribe safely during publish.
static class EventBus {
private final Map<String, List<Consumer<String>>> listeners = new ConcurrentHashMap<>();
Runnable subscribe(String topic, Consumer<String> listener) {
listeners.computeIfAbsent(topic, t -> new CopyOnWriteArrayList<>()).add(listener);
return () -> listeners.get(topic).remove(listener);
}
void publish(String topic, String data) {
for (Consumer<String> listener : listeners.getOrDefault(topic, List.of())) {
listener.accept(data); // publisher never knows who is listening
}
}
int count(String topic) {
return listeners.getOrDefault(topic, List.of()).size();
}
}
public static void main(String[] args) {
EventBus bus = new EventBus();
List<String> log = new ArrayList<>();
bus.subscribe("order.placed", data -> log.add("email: confirmation for " + data));
bus.subscribe("order.placed", data -> log.add("stock: reserve items of " + data));
Runnable unsubscribeSms = bus.subscribe("order.placed", data -> log.add("sms: text for " + data));
bus.subscribe("order.shipped", data -> log.add("email: tracking for " + data));
bus.publish("order.placed", "ORD-101");
unsubscribeSms.run(); // the SMS listener stops listening
bus.publish("order.placed", "ORD-102");
bus.publish("payment.failed", "ORD-103"); // no subscribers: nothing happens
log.forEach(System.out::println);
System.out.println("listeners for order.placed: " + bus.count("order.placed"));
}
}
email: confirmation for ORD-101 stock: reserve items of ORD-101 sms: text for ORD-101 email: confirmation for ORD-102 stock: reserve items of ORD-102 listeners for order.placed: 2
Time complexity: O(L) · Space complexity: O(S).
Approach 2: Single Subscription List
Very simple and easy to extend with wildcard topics, but every publish scans all subscriptions.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class EventBusTyped {
// Each subscription is a small object; publish() filters by topic. Simple, and the order of
// subscription is the order of delivery across all topics.
static class EventBus {
private record Subscription(String topic, Consumer<String> listener) { }
private final List<Subscription> subscriptions = new ArrayList<>();
synchronized Runnable subscribe(String topic, Consumer<String> listener) {
Subscription s = new Subscription(topic, listener);
subscriptions.add(s);
return () -> { synchronized (this) { subscriptions.remove(s); } };
}
void publish(String topic, String data) {
List<Subscription> snapshot;
synchronized (this) {
snapshot = List.copyOf(subscriptions); // deliver outside the lock
}
for (Subscription s : snapshot) {
if (s.topic().equals(topic)) {
s.listener().accept(data);
}
}
}
synchronized int count(String topic) {
return (int) subscriptions.stream().filter(s -> s.topic().equals(topic)).count();
}
}
public static void main(String[] args) {
EventBus bus = new EventBus();
List<String> log = new ArrayList<>();
bus.subscribe("order.placed", data -> log.add("email: confirmation for " + data));
bus.subscribe("order.placed", data -> log.add("stock: reserve items of " + data));
Runnable unsubscribeSms = bus.subscribe("order.placed", data -> log.add("sms: text for " + data));
bus.subscribe("order.shipped", data -> log.add("email: tracking for " + data));
bus.publish("order.placed", "ORD-101");
unsubscribeSms.run(); // the SMS listener stops listening
bus.publish("order.placed", "ORD-102");
bus.publish("payment.failed", "ORD-103"); // no subscribers: nothing happens
log.forEach(System.out::println);
System.out.println("listeners for order.placed: " + bus.count("order.placed"));
}
}
email: confirmation for ORD-101 stock: reserve items of ORD-101 sms: text for ORD-101 email: confirmation for ORD-102 stock: reserve items of ORD-102 listeners for order.placed: 2
Time complexity: O(S) · Space complexity: O(S).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Map of Topic to Listeners | O(L) | O(S) |
| Single Subscription List | O(S) | O(S) |
With the map, a publish costs one call per listener of that topic. With a single list, a publish scans every subscription.
Interview Tips and Recommended Approach
- Name the pattern: observer, also called publish/subscribe when a broker sits in the middle.
- Return an unsubscribe handle. Listeners that are never removed are a classic memory leak.
- Decide what happens when a listener throws. Usually log it and continue with the others.
- Mention async delivery. Running listeners on an executor stops a slow one from blocking the publisher.
Recommended Approach: Map of Topic to Listeners
Why: publishing only touches the right listeners, and the concurrent collections make the bus thread-safe with almost no code.