Notes
The problem
Here is the naive version. When the shipment moves to a new status, it calls the SMS sender, the dashboard and the arrival time predictor directly. It works, but the shipment now depends on three unrelated classes. Adding loyalty points or a webhook means editing the shipment again. Testing a status change needs all three dependencies. And if the SMS call throws an exception, the dashboard never hears about it.
void moveTo(ParcelStatus next) {
status = next;
sms.send(phone, "Now " + next);
dashboard.refresh(id, next);
eta.recalculate(id, next);
// next sprint: loyalty points?
// and a webhook for the shop?
} The idea
The idea in one sentence: an object keeps a list of interested objects and calls each of them when its state changes. The object that changes is the subject. The objects that react are the observers, often called listeners. The key point is that the subject only knows one small interface. It has no idea whether the listener sends a text, draws a chart or writes to a database.
- an object keeps a list of
- interested objects and calls
- each of them when its state
- changes
- subject: the one that changes
- observer: the one that reacts
- the subject only knows the
- observer interface
The structure
Here are the participants in our example. HubScanner is the client: a warehouse scanner that moves a parcel to a new status. ParcelShipment is the subject. It holds a list of ShipmentListener objects, which is the observer interface. CustomerSmsAlert, ShopDashboard and EtaPredictor are concrete observers. Each one implements the interface and decides for itself what to do with the news.
The code: listener
The observer side is tiny. A StatusChange record carries the parcel id, the old status, the new status and the hub. Because it is a record, it is immutable, so no listener can change what the others will see. The ShipmentListener interface has a single method, on status change. Subscribing returns a Subscription handle, which the caller closes to stop listening. We will see why that handle matters in a minute.
record StatusChange(String parcelId,
ParcelStatus from, ParcelStatus to,
String hub) {}
interface ShipmentListener {
void onStatusChange(StatusChange c);
}
interface Subscription
extends AutoCloseable {
@Override void close();
} The code: subject
The subject has three jobs. Subscribe adds a listener and returns a handle that removes it. Move to first updates its own status, and only then builds the event and calls every listener. The list is a copy on write array list, so a listener may unsubscribe while we are looping without breaking the loop. Each call is wrapped so that one failing listener cannot stop the others from being told.
List<ShipmentListener> listeners =
new CopyOnWriteArrayList<>();
Subscription subscribe(ShipmentListener l) {
listeners.add(l);
return () -> listeners.remove(l);
}
void moveTo(ParcelStatus next, String hub) {
var c = new StatusChange(id, status,
next, hub); status = next;
for (var l : listeners) safeCall(l, c); Run-through
Let us run one scan. The hub scanner calls move to with out for delivery. The shipment updates its status and builds one status change event. It then walks its list. The SMS notifier texts the customer, the shop dashboard bumps its counter, and the arrival predictor computes a new time. The shipment did not name any of them, and none of them know about each other.
Push vs pull
There are two styles. In push, the event carries the data, like our status change record, so observers need nothing else. The risk is that the event keeps growing to suit every listener. In pull, the subject only says something changed and passes itself, and each observer asks for what it needs. That is flexible, but observers now depend on the subject's getters, and by the time they read, the state may already have moved on. Push of a small immutable event is the usual default.
- push: the event carries data
- onStatusChange(change)
- + observers need nothing else
- - event grows to fit everyone
- pull: the event is a nudge
- onChanged(shipment)
- then shipment.status()
- + observers read what they need
- - may read a newer state
- - observers depend on subject
Lapsed listeners
Now the classic bug. A dashboard screen subscribes to a shipment. The user closes the screen, but nobody unsubscribes. The shipment's list still holds a reference, so the garbage collector cannot free the screen, its charts or anything else it points to. Worse, it keeps receiving events and doing work. This is called the lapsed listener problem. The fix is simple discipline: keep the subscription handle and close it when the owner goes away.
- a dashboard screen subscribes
- the user closes the screen
- nobody unsubscribes
- the shipment list still holds
- it, so the garbage collector
- cannot free it, and it keeps
- getting events
- fix: keep the Subscription,
- close it when the owner dies
Failing and slow
A few rules from real systems. Catch exceptions per listener, so one broken webhook does not hide the change from everyone else. Never rely on the order listeners are called. Notify only after the state is final, or a listener may see half an update. Listeners run on the caller's thread, so a slow one, like an SMS call, blocks the scanner. Hand slow work to an executor. And watch out for a listener that changes the subject again, which can recurse forever.
- catch per listener: one
- exception must not stop
- the rest
- do not rely on call order
- notify after state is final
- slow work (SMS, HTTP):
- hand off to an executor
- avoid loops: a listener that
- changes the subject again
- can recurse forever
Observer vs pub/sub
How is this different from publish subscribe? In Observer, the subject holds direct references to its listeners, usually in the same process, and calls them right away. In pub sub, a broker sits in the middle. The publisher only knows a topic name, the broker routes messages to subscribers, and delivery is often asynchronous and across services. Brokers such as Kafka or RabbitMQ can buffer, retry and replay. Pub sub is Observer stretched across a network, with more decoupling and more moving parts.
- observer:
- subject holds the listeners
- usually same process, sync
- pub/sub:
- publisher knows only a topic
- a broker routes messages
- often async, across services
- can buffer, retry, replay
When to use it
Use Observer when several parts of a system react to one change and that list will keep growing, or when the subject lives in a lower layer that must not depend on the code reacting to it. Skip it when there is exactly one consumer that will never change, because a direct call is clearer. Skip it when the steps must happen in a strict order, or when the caller needs an answer back. Events also make the flow harder to follow in a debugger, which is a real cost.
- use it when:
- several parts react to a change
- the list will grow over time
- the subject is in a lower
- layer than the reactions
- skip it when:
- exactly one fixed consumer
- the order of steps matters
- you need a result back
In Java
You have used this pattern already. Java beans fire property change events to property change listeners, with a helper class called property change support. Swing buttons call action listeners. The Flow interfaces added in Java nine define publishers and subscribers for asynchronous streams. Spring lets beans publish application events and handle them with the event listener annotation. The old Observable class still exists, but it has been deprecated since Java nine, so write your own small interface instead.
- PropertyChangeListener and
- PropertyChangeSupport
- Swing ActionListener and other
- UI listeners
- java.util.concurrent.Flow
- (reactive streams, async)
- Spring @EventListener
- java.util.Observable: deprecated
- since Java 9, do not use
In LLD interviews
In machine coding rounds, listen for the words notify, alert or update the display. A vending machine alerts the operator when a slot is low. An elevator updates the display on every floor. A parking lot refreshes the free spot boards at each entrance. An auction tells every bidder about a new highest bid. A common mistake is to call the display directly from the core class. Put a listener interface between them and say why: the core stays testable and new consumers are free.
- vending machine: low stock
- alert to the operator
- elevator: floor displays and
- call buttons light up
- parking lot: free-spot boards
- auction: tell every bidder
- stock alert, price watch
- notification service channels
- chess or games: UI redraws
Mistakes to avoid
The mistakes interviewers look for. No way to unsubscribe, which leads to leaks. Notifying before the state is updated. Letting one exception end the loop. Passing a mutable event that one listener can change for the others. Using a plain array list and getting a concurrent modification exception when a listener unsubscribes during notification. Running slow work on the caller's thread. And reaching for a full message broker when one in process listener list would do.
- no way to unsubscribe
- notifying before the state
- is updated
- one exception stops the loop
- mutable event objects
- ArrayList modified while
- iterating it
- slow listener on the
- caller thread
- a broker for one class