A bowler bowls one ball in a cricket match. Within a second, the scoreboard on your phone changes, a line appears in the live commentary, and if a batter has just reached 50, a notification buzzes in your pocket. One event happened, and several unrelated parts of the system reacted to it.
This shape is everywhere. A stock price changes and alerts, charts and portfolios update. A parking spot is taken and the display boards at every entrance change. A message arrives and the chat list, the unread badge and the notification all react. In each case, one object knows something changed, and an open-ended list of other objects needs to hear about it.
The Observer pattern lets the object that changes tell everyone who cares, without knowing who they are. In this article we build a small live score service twice. The first version calls each part directly. The second uses the Observer pattern. Then we look at the hard parts: a listener that throws, a listener that is slow, and a listener that leaves in the middle of a notification.
All the code is Java, and all of the project code compiles and runs. The snippets come from two projects, the first version and the finished one, except for one short sketch that is labelled as such. The Open file button on a finished-project snippet shows the whole file in a code browser.
The score service we are building
A scorer at the ground records each ball as it is bowled. The service must:
- Record each ball: who batted, how many runs, and whether a wicket fell.
- Update the scoreboard with the total, the wickets and the overs.
- Add a commentary line for every ball.
- Send a push notification when a wicket falls or a batter reaches 50 or 100.
- Take on new consumers, such as a stats tracker or a betting odds feed, without changing the score service.
- Keep going if one consumer breaks. The score must still be recorded and the other consumers must still hear about the ball.
To keep the example small, every ball is a legal delivery. Wides and no-balls are left out.
The figure shows the two halves of the problem. On the left, one object owns the score and knows when it changes. On the right, a list of consumers wants to know, and that list will grow. The rest of this article is about the line between the two halves.
The first version: the score service calls everyone
The obvious way to write this is to give the score service a field for each consumer and call each one after updating the score:
public class ScoreService { private final Scoreboard scoreboard; private final CommentaryFeed commentary; private final MilestoneAlerts alerts; private final Map<String, Integer> batterRuns = new HashMap<>(); private int totalRuns; private int wickets; private int ballsBowled; public ScoreService(Scoreboard scoreboard, CommentaryFeed commentary, MilestoneAlerts alerts) { this.scoreboard = scoreboard; this.commentary = commentary; this.alerts = alerts; } public void recordBall(Ball ball) { totalRuns += ball.runs(); ballsBowled++; if (ball.wicket()) { wickets++; } int before = batterRuns.getOrDefault(ball.batter(), 0); int after = before + ball.runs(); batterRuns.put(ball.batter(), after); scoreboard.update(totalRuns, wickets, ballsBowled); commentary.add(ball, ballsBowled); alerts.check(ball.batter(), before, after, ball.wicket()); }}This code works, and for two consumers that will never change, it is a fine answer. The trouble starts as the list grows.
The score service knows every consumer, and each one's own method. The scoreboard wants update(totalRuns, wickets, ballsBowled). The commentary wants add(ball, ballsBowled). The alerts want check(batter, before, after, wicket). The score service has to know all three shapes, and it works out data, like the batter's runs before the ball, that only one consumer needs.
A new consumer means editing the score service. A stats tracker means a new field, a new constructor parameter and a new call in recordBall. So does an odds feed. The class that owns the score changes every time someone new wants to know about it.
One broken consumer breaks everything after it. If the commentary store is down and commentary.add throws, the exception leaves recordBall. The alerts, called after it, never hear about the ball. The scorer's screen shows an error for a problem that has nothing to do with the score.
Testing the score needs every consumer. To check that four runs were added, a test must build a scoreboard, a commentary feed and an alerts object, because the constructor demands them.
The idea
The pattern works like this:
- There is one listener interface with one method, here
onBall(event). Every consumer implements it. - The object that changes keeps a list of listeners. Anyone can add themselves with
subscribe, which returns a handle they later use to leave. - When something happens, the object builds one event and calls every listener in the list with it.
- The object never knows what a listener does. It only knows that it implements the interface.
The object that changes is called the subject. Here it is the ScoreService. The objects that react are the observers, also called listeners or subscribers. Here they are the Scoreboard, the CommentaryFeed and the MilestoneAlerts.
Building it, step by step
Step 1: one interface for everyone who listens
Every consumer will implement this:
public interface BallListener { void onBall(BallEvent event);}The interface has one method with one parameter. The scoreboard, the commentary, the alerts and any future consumer all look the same to the score service. A one-method interface also lets a test or a demo pass a lambda, like event -> calls.add("first"), instead of writing a class.
Step 2: decide what a listener is told
The listener needs to know what happened. There are two ways to give it that information.
public record BallEvent(Ball ball, int totalRuns, int wickets, int ballsBowled, int batterRuns) { // Completed overs, as a scoreboard shows them: the sixth ball of the first over makes "1.0". public String overs() { return (ballsBowled / 6) + "." + (ballsBowled % 6); } // This ball's own label, as commentary shows it: the sixth ball of the first over is "0.6". public String ballLabel() { return ((ballsBowled - 1) / 6) + "." + ((ballsBowled - 1) % 6 + 1); }}BallEvent is a record: the ball itself, plus the score as it stood right after that ball. It has two ways to show the over. A scoreboard shows completed overs, so the sixth ball of the first over makes "1.0". Commentary labels the ball itself, so the same ball is "0.6". Both come from ballsBowled, so they can never disagree.
Does the subject send the data, or do listeners ask for it?
Pull: the event says something changed, and listeners read the score service
The event can be tiny, and each listener reads only what it needs. But a listener now holds a reference to the score service and calls back into it. If another ball is recorded before the listener reads, it sees the score after a later ball, not the one it was told about.
Push: the event carries a snapshot of everythingOur pick
Each event holds the score as it was after its own ball, in an unchangeable record. A listener that runs late, or keeps the event for later, still sees the right numbers. Listeners never need a reference to the score service. The cost is that the event carries fields some listeners ignore. For four integers and a ball, that cost is small.
Pushing totals also decides what happens to a listener that joins late. A big screen at the ground is switched on after 40 balls, and it subscribes a new Scoreboard. Nothing is sent at that moment, so the board shows its starting text, 0/0, until the next ball. When that ball arrives, its event carries the whole score, so the board jumps straight to the right total. If events carried only this ball's runs, a late board would count from zero and stay wrong for the rest of the match.
If even one ball of 0/0 is too long, the service can keep the last event and send it to each new listener inside subscribe. We left this out to keep the service small. In an interview, it is a good follow-up to raise yourself.
Step 3: the subject keeps a list and calls everyone
Here is the whole score service:
public class ScoreService { private final List<Registration> registrations = new CopyOnWriteArrayList<>(); private final ErrorLog errorLog; private final Map<String, Integer> batterRuns = new HashMap<>(); private int totalRuns; private int wickets; private int ballsBowled; private boolean notifying; public ScoreService(ErrorLog errorLog) { this.errorLog = Objects.requireNonNull(errorLog, "errorLog"); } public Subscription subscribe(BallListener listener) { Registration registration = new Registration(Objects.requireNonNull(listener, "listener")); registrations.add(registration); return registration; } public synchronized void recordBall(Ball ball) { Objects.requireNonNull(ball, "ball"); if (notifying) { throw new IllegalStateException("recordBall was called from inside a listener"); } totalRuns += ball.runs(); ballsBowled++; if (ball.wicket()) { wickets++; } int runsForBatter = batterRuns.merge(ball.batter(), ball.runs(), Integer::sum); BallEvent event = new BallEvent(ball, totalRuns, wickets, ballsBowled, runsForBatter); notifying = true; try { for (Registration registration : registrations) { notifyOne(registration.listener, event); } } finally { notifying = false; } }subscribe adds a listener to the list and returns a Subscription. recordBall updates the totals first, then builds one BallEvent, then walks the list and calls onBall on each listener in the order they subscribed. The score service has no idea that one of those listeners draws a scoreboard and another sends notifications. The loop calls notifyOne for each listener, which we look at in step 4.
Four details in this class need explaining.
The list is a CopyOnWriteArrayList. Every subscribe or cancel copies the list, and the loop in recordBall walks the copy that existed when the loop started. So a listener can safely subscribe or leave, even in the middle of a notification, from any thread.
recordBall is synchronized. One scorer usually records the balls, but if two threads ever record at once, the lock keeps the totals right and makes every listener see the balls in order: 1, 2, 3, with none skipped or swapped.
A listener may not record a ball. Java's synchronized lock is reentrant, so a listener that called recordBall from inside onBall would get straight back in. It would send ball 2 to every listener before the rest had heard ball 1. The notifying flag makes that call throw an IllegalStateException before anything is counted. notifyOne catches it and reports it to the ErrorLog, like any other listener failure.
subscribe returns a handle. Each subscription is a Registration, and calling cancel() on it removes that registration by identity. An unsubscribe(listener) method would remove the first listener that is equal to the one passed in, which can be the wrong one. It also has a trap: unsubscribe(screen::onBall) removes nothing, because each method reference creates a new object. A listener subscribed twice is called twice, and each of its two handles removes only its own subscription. A second cancel() on the same handle does nothing. A cancel from another thread applies from the next ball, so a ball already being sent can still reach the listener once.
private final class Registration implements Subscription { private final BallListener listener; Registration(BallListener listener) { this.listener = listener; } @Override public void cancel() { // Removed by identity, so an equal listener subscribed separately stays subscribed. registrations.remove(this); } }What happens when the list changes during a notification?
A plain ArrayList
This is simple and fast. But if a listener leaves, or removes another listener, while the loop is running, the loop either throws a ConcurrentModificationException or quietly ends early. Either way, the remaining listeners never hear the ball. A screen switched off at the wrong moment would break the scoreboard for everyone.
A CopyOnWriteArrayList, so changes apply from the next eventOur pick
The loop walks a snapshot. A listener removed during a notification still hears the current ball, and a listener added during it starts with the next one. The cost is a full copy of the list on every subscribe and cancel. Listeners change rarely and events happen often, which is exactly the case this list is built for.
Step 4: a broken listener must not stop the rest
Each call to onBall is wrapped in its own try:
private void notifyOne(BallListener listener, BallEvent event) { try { listener.onBall(event); } catch (RuntimeException e) { // One broken listener must not stop the others. report(listener, e); } } private void report(BallListener listener, RuntimeException error) { try { errorLog.listenerFailed(listener, error); } catch (RuntimeException logFailure) { // A broken error log must not stop the others either. System.err.println("A listener failed (" + error + ") and so did the error log (" + logFailure + ")"); } }If a listener throws a RuntimeException, notifyOne catches it, hands it to an ErrorLog, and the loop moves on to the next listener. The totals were already updated before the loop, so the score is safe whatever the listeners do. ErrorLog is an interface passed into the constructor, so production can send failures to monitoring and a test can collect them in a list. If the error log itself throws, report prints both failures to System.err, so a broken log cannot stop the other listeners either.
An Error, such as OutOfMemoryError, is let through. It means the program itself is in trouble, and carrying on would hide that.
The constructor, subscribe and recordBall reject null at once with Objects.requireNonNull. A null there is a programmer's mistake, and failing at the call shows where it happened.
What does the subject do when a listener throws?
Let the exception through
The scorer finds out at once that something is broken. But one faulty odds feed then stops every listener after it, and makes recording a ball look like it failed when it did not.
Catch it per listener, report it, and carry onOur pick
Every other listener still hears the ball, and the failure still reaches someone through ErrorLog. The broken listener stays subscribed, so it is called again on the next ball. If it keeps failing, someone has to fix or remove it. Silently unsubscribing it would hide the problem.
Step 5: each listener does its own job
With the plumbing done, a listener is a small class that does one thing. The scoreboard keeps one line of text:
public class Scoreboard implements BallListener { private final String team; // A screen thread reads this while the scorer's thread writes it. private volatile String display; public Scoreboard(String team) { this.team = Objects.requireNonNull(team, "team"); this.display = team + " 0/0 (0.0 ov)"; } @Override public void onBall(BallEvent event) { display = team + " " + event.totalRuns() + "/" + event.wickets() + " (" + event.overs() + " ov)"; } public String display() { return display; }}The milestone alerts work out whether this ball crossed 50 or 100:
public class MilestoneAlerts implements BallListener { private static final List<Integer> MILESTONES = List.of(50, 100); private final PushSender sender; public MilestoneAlerts(PushSender sender) { this.sender = Objects.requireNonNull(sender, "sender"); } @Override public void onBall(BallEvent event) { String batter = event.ball().batter(); if (event.ball().wicket()) { sender.send("WICKET! " + batter + " is out for " + event.batterRuns()); } int before = event.batterRuns() - event.ball().runs(); for (int milestone : MILESTONES) { if (before < milestone && event.batterRuns() >= milestone) { sender.send(batter + " reaches " + milestone); } } }}The batter's runs before this ball are their runs after it, minus the runs off this ball. A milestone fires when the runs before were under it and the runs after are at or over it. So a batter on 48 who hits a six gets one "reaches 50" alert, and the four after that gets none.
MilestoneAlerts does not send anything itself. It calls a PushSender, which in production would talk to a push notification service over the network. That raises the last question.
Who deals with a slow listener?
The subject calls every listener on a thread pool
A slow listener can no longer hold up the others. But the events can now arrive out of order, exceptions happen on other threads where the try in notifyOne cannot catch them, and a test can no longer check what a listener did straight after recordBall returns.
The subject calls listeners in turn, and a slow listener hands its slow work to a queueOur pick
The score service stays simple: one thread, a fixed order, and every listener's RuntimeException caught in one place. The rule for listeners is that onBall must return quickly. A listener with slow work, like a network call, puts that work on its own queue and returns. In production, the PushSender would add the message to a queue that a separate worker sends from.
This rule matters because recordBall holds its lock while it calls the listeners. A listener that blocks for two seconds would block the next ball for two seconds. Calling code you do not control while holding a lock is also how deadlocks start. If a listener waits for a lock that another thread holds, and that thread is waiting to record a ball, both wait forever.
Listeners also run on the scorer's thread, so anything a listener stores for a screen to read is shared between two threads. Scoreboard keeps its text in a volatile field, and CommentaryFeed makes both of its methods synchronized.
The finished design
Here is one ball, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package score; import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.concurrent.CopyOnWriteArrayList; public class ScoreService { private final List<Registration> registrations = new CopyOnWriteArrayList<>(); private final ErrorLog errorLog; private final Map<String, Integer> batterRuns = new HashMap<>(); private int totalRuns; private int wickets; private int ballsBowled; private boolean notifying; public ScoreService(ErrorLog errorLog) { this.errorLog = Objects.requireNonNull(errorLog, "errorLog"); } public Subscription subscribe(BallListener listener) { Registration registration = new Registration(Objects.requireNonNull(listener, "listener")); registrations.add(registration); return registration; } public synchronized void recordBall(Ball ball) { Objects.requireNonNull(ball, "ball"); if (notifying) { throw new IllegalStateException("recordBall was called from inside a listener"); } totalRuns += ball.runs(); ballsBowled++; if (ball.wicket()) { wickets++; } int runsForBatter = batterRuns.merge(ball.batter(), ball.runs(), Integer::sum); BallEvent event = new BallEvent(ball, totalRuns, wickets, ballsBowled, runsForBatter); notifying = true; try { for (Registration registration : registrations) { notifyOne(registration.listener, event); } } finally { notifying = false; } } private void notifyOne(BallListener listener, BallEvent event) { try { listener.onBall(event); } catch (RuntimeException e) { // One broken listener must not stop the others. report(listener, e); } } private void report(BallListener listener, RuntimeException error) { try { errorLog.listenerFailed(listener, error); } catch (RuntimeException logFailure) { // A broken error log must not stop the others either. System.err.println("A listener failed (" + error + ") and so did the error log (" + logFailure + ")"); } } private final class Registration implements Subscription { private final BallListener listener; Registration(BallListener listener) { this.listener = listener; } @Override public void cancel() { // Removed by identity, so an equal listener subscribed separately stays subscribed. registrations.remove(this); } }}The demo in demo/Main.java subscribes four listeners: the scoreboard, the commentary, a console ticker that prints each ball, and the milestone alerts. Then it plays two overs and a bit:
0.1 Kohli 4 score 4/0
0.2 Kohli 6 score 10/0
0.3 Kohli 2 score 12/0
0.4 Kohli 4 score 16/0
0.5 Kohli 6 score 22/0
0.6 Kohli 4 score 26/0
1.1 Kohli 6 score 32/0
1.2 Kohli 4 score 36/0
1.3 Kohli 6 score 42/0
1.4 Kohli 4 score 46/0
1.5 Kohli 2 score 48/0
1.6 Kohli 2 score 50/0
push: Kohli reaches 50
2.1 Kohli 1 score 51/0
2.2 Gill out score 51/1
push: WICKET! Gill is out for 0
2.3 Rahul 4 score 55/1
error: a listener failed: odds feed is down
2.4 Rahul 1 score 56/1
scoreboard: IND 56/1 (2.4 ov)
commentary: 2.4 Rahul, 1 runFollow the output from the top. Each ball prints one ticker line. On 1.6, Kohli moves from 48 to 50, and the alert listener sends one push. On 2.2, Gill is out and a wicket push goes out. Before 2.3, the demo subscribes an odds feed that throws every time. The ball is still recorded, every other listener still runs, and the error log reports the failure. The demo then cancels the odds feed's subscription, and 2.4 runs cleanly. The last two lines show that the scoreboard and the commentary followed every ball.
The ticker is worth a second look. It is a fourth consumer, written after the score service, and adding it took one class and one subscribe call. That is requirement 5 met.
What it costs
The pattern makes one kind of change cheap and another kind expensive.
Adding a listener is cheap. A stats tracker is one new class that implements BallListener, and one subscribe call where the app starts. The score service does not change.
Adding a new kind of event is expensive. Suppose listeners must also hear when an innings ends. BallListener gets a second method, onInningsEnd, and every listener must now implement it, even the ones that do not care. A Java default method, default void onInningsEnd(...) { }, softens this: listeners that do not care inherit an empty version. Some designs use one listener interface per event type instead.
There are quieter costs too.
- The flow is harder to follow. Reading
recordBallno longer tells you what happens after a ball. You have to find everysubscribecall. A debugger or a log line per listener helps. - Forgotten listeners stay alive. The subject's list holds a reference to every listener. A screen that subscribes when it opens and never cancels when it closes stays in memory, and keeps getting called, for as long as the subject lives.
- No listener should rely on the order. Listeners run in the order they subscribed, but that is a detail of the list, not a promise. If the commentary needs the scoreboard to have updated first, the two are not independent, and they should be one listener or share data another way.
When direct calls are better
If there are one or two consumers and the list will not grow, call them directly. A score service that only ever updates one scoreboard does not need an interface, a list and error handling around a single call:
public void recordBall(Ball ball) { totalRuns += ball.runs(); ballsBowled++; scoreboard.update(totalRuns, wickets, ballsBowled);}The pattern starts to pay off when the consumers are many, unrelated, or added by people who should not have to edit the subject.
Observer or a message queue?
The question comes up because both send one event to many receivers. The difference is in where the receivers live and what happens when things go wrong.
| Observer | Message queue or pub-sub broker | |
|---|---|---|
| Where the receivers live | In the same program, as objects in a list | In other services, often on other machines |
| Who knows the receivers | The subject holds a reference to each one | The publisher knows only a topic name |
| When receivers run | During the subject's call, one after another | Later, at their own pace |
| If a receiver is down | The call fails now, and the subject must handle it | The broker keeps the message and delivers it when the receiver is back |
| Example | The score service and its scoreboard | The score service publishing to a topic that the notification service reads |
In short, Observer connects objects inside one program. A message queue connects programs. A large system often uses both. The score service might use Observer for its own screens, and one of its listeners publishes each ball to a queue for other services.
In an interview
Observer shows up inside many low-level design questions: display boards in a parking lot, price alerts in a stock trading app, bid updates in an auction, notification systems, chat rooms, and elevator displays on every floor. It appears whenever one change must reach several parts of the system.
We suggest presenting it in this order:
- Name the subject and the events. "The score service is the subject, and each ball is an event."
- Write the listener interface and the event first. Decide push or pull out loud.
- Write
subscribe, its handle and the notify loop, then say what happens when a listener throws, is slow, or leaves during a notification. These three cases are where a listener list goes wrong.
Common mistakes:
- No
tryaround each listener. One broken listener then stops all the others, and the subject looks broken too. - Iterating a plain list that listeners can change. It works in testing, then throws a
ConcurrentModificationExceptionor silently skips listeners the first time someone leaves during an event. - Never leaving. The subject keeps every listener alive. Keep the handle
subscribereturns, and cancel it when the listener's owner goes away. - Events that carry only the change. A listener that joins late, or misses one event, counts from the wrong starting point and stays wrong. Send the totals.
- Mutable events. If listeners receive an object they can change, one listener can change what the next one sees. Use records whose fields are themselves unchangeable.
- Slow work inside
onBall. A network call in a listener delays every listener after it, and the next event too. - Listeners that depend on each other's order. If one listener needs another to run first, they are one job, not two.
Summary
- Use the Observer pattern when one object changes and an open-ended set of others must react, without the first knowing about them.
- The subject keeps a list of listeners behind one interface, builds one event, and calls each listener with it.
- Push an unchangeable snapshot in the event, so late or slow listeners still see the right data.
- Catch each listener's exceptions separately, use a list that is safe to change during a loop, and keep slow work out of the listener's method.
- Adding a listener is cheap. Adding a new kind of event touches every listener, unless the interface gives it a default.
- For one or two fixed consumers, direct calls are simpler.