Patterns for behaviour · Chapter 16

Observer pattern

Let one object announce changes to any number of listeners without knowing who they are. Java and Python code, push vs pull, leaks, exceptions, ordering, async and pub/sub.

IntermediateInterview priority: High45 min
On this page
  1. The problem: who needs to know?
  2. The idea: subscribe once, get told when it happens
  3. Build it step by step
  4. Push or pull?
  5. The details that bite
  6. Where this breaks
  7. Lightweight forms
  8. Observer, pub/sub, mediator: how they differ
  9. When not to use it
  10. In the interview
  11. Quiz

The problem: who needs to know?

A weather station measures the temperature. A phone app, a billboard and a frost alarm all want to react when it changes. There are two obvious ways to build this, and both hurt.

Option 1: the station calls everyone directly.

public void setTemperature(double celsius) {
    this.temperature = celsius;
    phoneApp.show(celsius);
    billboard.display(celsius);
    frostAlarm.check(celsius);
    // marketing wants a logger next month: edit this method again
}

The station now depends on every class that cares about it. Adding a logger, or removing the billboard, means editing and re-testing the station. In a real system this is the OrderService.placeOrder() that ends with fifteen lines calling email, inventory, analytics, loyalty points and fraud checks.

Option 2: everyone keeps asking. Each display asks the station every few seconds, "anything new?" This is polling.

Polling: most of the questions get the answer "no change"

  1. The weather station measures the temperature. A phone app, a billboard and a frost alarm all want to know when it changes. One way: each of them asks the station every few seconds, “anything new?” That’s called polling, and most answers are “no”.

Polling wastes work when nothing changes, and is still late when something does: with a 10-second poll, a frost warning arrives on average 5 seconds after the frost, up to 10. Polling faster cuts the delay but multiplies the wasted questions.

The idea: subscribe once, get told when it happens

The Observer pattern turns it around. Interested objects, the observers, register with the object that has the information, the subject. When its state changes, the subject loops over its list and calls each observer's update(). The subject knows only the Observer interface, never the concrete classes.

Observers subscribe; the subject notifies all of them

  1. The Observer pattern flips it around. Interested objects subscribe to the station, called the subject. When the temperature changes, the station calls notify(), which calls update() on every observer.
RoleIn this exampleResponsibility
SubjectWeatherStationKeeps a list of observers; offers subscribe / unsubscribe; notifies them on change
Observer (interface)TemperatureObserverThe one method the subject calls: update(celsius)
Concrete observersPhoneApp, FrostAlarm, a loggerDecide for themselves what to do with the news

The result is loose coupling: the subject and its observers can change independently, and observers can join or leave while the program runs. Another name you will hear is publish/subscribe at the class level; the system-design version with a broker in the middle is compared with Observer later on this page.

Build it step by step

1. The observer interface: one method.

2. The subject: a list, subscribe (which returns a handle to unsubscribe), and a private notify loop. Two details already matter: it notifies only when the value actually changes, and one failing observer must not stop the others.

3. Concrete observers: each one small, holding its own state (the frost alarm remembers whether it is already ringing).

4. The client wires them together.

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

// One file for reading; to run it: javac Demo.java && java Demo
// 1. The observer interface
@FunctionalInterface
interface TemperatureObserver {
    void update(double celsius);
}

// 2. The subject
final class WeatherStation {
    // Copy-on-write: observers may subscribe or unsubscribe while we are notifying
    private final List<TemperatureObserver> observers = new CopyOnWriteArrayList<>();
    private double temperature = Double.NaN;          // "no reading yet"

    /** Returns a handle; call run() on it to unsubscribe. */
    public Runnable subscribe(TemperatureObserver o) {
        observers.add(o);
        return () -> observers.remove(o);
    }

    public double temperature() { return temperature; }

    public void setTemperature(double celsius) {
        if (Double.compare(celsius, temperature) == 0) return;   // only notify on change
        temperature = celsius;
        notifyObservers();
    }

    // Not called notify(): Object.notify() is final in Java and is about thread signalling.
    private void notifyObservers() {
        for (TemperatureObserver o : observers) {
            try {
                o.update(temperature);
            } catch (RuntimeException e) {
                System.err.println("observer failed: " + e);   // isolate failures
            }
        }
    }
}

// 3. Concrete observers
final class PhoneApp implements TemperatureObserver {
    public void update(double celsius) { System.out.println("Phone: " + celsius + " °C"); }
}

final class FrostAlarm implements TemperatureObserver {
    private final double threshold;
    private boolean ringing;

    public FrostAlarm(double threshold) { this.threshold = threshold; }

    public void update(double celsius) {
        if (celsius < threshold && !ringing) {
            ringing = true;
            System.out.println("FROST! Cover the plants.");
        } else if (celsius >= threshold) {
            ringing = false;
        }
    }
}

// 4. The client
public class Demo {
    public static void main(String[] args) {
        WeatherStation station = new WeatherStation();
        station.subscribe(new PhoneApp());
        station.subscribe(new FrostAlarm(2.0));
        Runnable stopLogging = station.subscribe(c -> System.out.println("log " + c));  // a lambda works too

        station.setTemperature(12);   // Phone: 12.0 °C, log 12.0
        station.setTemperature(1);    // Phone: 1.0 °C, FROST!, log 1.0
        stopLogging.run();            // unsubscribe the logger
        station.setTemperature(0);    // Phone: 0.0 °C (alarm already ringing, logger gone)
    }
}

New listeners, no edits

A logger subscribes at run time; the station's code is unchanged

  1. That gives loose coupling. A new Logger can subscribe while the program runs, and the station’s code doesn’t change. Updates arrive the moment something happens, instead of whenever someone next asks.

The logger joined with one subscribe call. WeatherStation was not opened, and neither was any other observer. Compare that with Option 1, where every new reaction meant editing setTemperature.

Push or pull?

What does update() carry? There are two styles, and a common middle way.

Styleupdate signatureGood atWeak at
Push the dataupdate(double celsius)Observers get exactly what changed; no call back to the subjectThe interface fixes what is sent; adding humidity changes every observer
Pull from the subjectupdate(WeatherStation s), then s.temperature()Observers read only what they need; the interface never changesObservers depend on the subject's API; by the time they read, the value may have changed again
Event objectupdate(WeatherChanged e) with old, new, timeStable interface; new fields don't break old observers; a snapshot, so it can't change under youOne more small class per kind of event

For anything beyond a toy, prefer an immutable event object. Java's own PropertyChangeEvent (with old and new values) and every UI framework's Event follow this style. It matters most when notification is asynchronous: a pull observer running later on another thread reads whatever the value is then, not the change it was told about.

The details that bite

The basic loop is five lines. These are the questions that separate a working version from a correct one.

A failing observer

Without the try/catch, an exception thrown by the second observer stops the loop, so the third never hears about the change, and the exception bubbles up into setTemperature(), whose caller did nothing wrong. Isolate each call and log the failure. (Some frameworks deliberately let it propagate; know which yours does.)

Changing the list during notification

A one-shot alert that unsubscribes itself inside update() removes an element from the list being iterated. With a plain ArrayList in Java that throws ConcurrentModificationException; in Python it silently skips the next observer. Iterate over a snapshot (list(self._observers)), or use a copy-on-write list, as above.

Order and re-entrancy

The pattern promises nothing about the order in which observers run. If the billboard must update after the database observer has saved, you have a hidden dependency: make it explicit (one observer that does both in order, or a pipeline) rather than relying on subscription order.

Re-entrancy is subtler: an observer that calls station.setTemperature() inside update() triggers a nested round of notifications before the first round has finished, so observers later in the outer loop are notified twice: once by the nested round and again by the outer one (and if the loop had captured the value before iterating, they would even receive the old value after the new one). Two observers that update each other can loop forever. Guard against it: don't let observers modify the subject, or queue changes and notify after the current round ends.

Synchronous or asynchronous?

As written, notification is synchronous: setTemperature() returns only when every observer has finished. A 2-second SMS observer makes every temperature update take 2 seconds.

Synchronous (default)Asynchronous (executor / event loop)
Caller waits forEvery observerNothing; returns at once
OrderDeterministic within a roundNot guaranteed; observers may run in parallel
ExceptionsVisible to the subject (catch them)Lost unless the executor logs them
Thread safetyObservers run on the caller's threadObservers run on other threads; shared state needs locks
If the process diesHalf the observers ranQueued notifications are lost

Going async in-process (for example, submitting each update to an ExecutorService) fixes slowness but not durability. If a notification must not be lost, it doesn't belong in memory at all: write it to a durable queue or use the outbox pattern, which is where Observer turns into pub/sub.

Where this breaks

addEventListener is an observer; always pair it with an unsubscribe

  1. You use observers daily: button.addEventListener("click", …) subscribes to a button. Watch out for one trap: observers that never unsubscribe keep living in the list, a common memory leak. The system design version of this idea, with a broker in between, is pub/sub.
import java.lang.ref.WeakReference;

// Inside WeakWeatherStation: the list holds weak references
private final List<WeakReference<TemperatureObserver>> observers = new CopyOnWriteArrayList<>();

public void subscribe(TemperatureObserver o) { observers.add(new WeakReference<>(o)); }

private void notifyObservers() {
    for (WeakReference<TemperatureObserver> ref : observers) {
        TemperatureObserver o = ref.get();
        if (o == null) observers.remove(ref);   // collected: clean up the dead entry
        else o.update(temperature);
    }
}
// Trap: station.subscribe(c -> screen.show(c)). If nothing else holds that lambda,
// it can be collected and stop firing at any time.

Lightweight forms

You rarely write the interface by hand today:

  • Java: any functional interface takes a lambda (Consumer<Double>). PropertyChangeSupport gives you a ready-made subject with old/new values. java.util.Observable exists but is deprecated since Java 9; don't use it. For streams of events with backpressure (a slow observer telling the subject to slow down), use java.util.concurrent.Flow, RxJava or Reactor.
  • Python: store plain callables (list[Callable[[float], None]]); any function or bound method is an observer.
  • JavaScript: EventTarget.addEventListener in browsers, EventEmitter in Node.js.
  • Frameworks: Spring @EventListener, Django signals (post_save.connect(handler)), C# event, Kotlin Flow, and the reactive state in Vue, MobX and Svelte.

Observer, pub/sub, mediator: how they differ

ObserverPub/sub (message broker)Mediator
Who knows whomSubject holds direct references to its observersNeither side knows the other; both know a topic on a brokerColleagues know only the mediator
WhereOne process, in memoryAcross services and machines (Kafka, SNS, Redis pub/sub, Google Pub/Sub)One process
DeliveryA method call, usually synchronousAsynchronous; durable if the broker stores messagesMethod calls
If a listener is downIt misses the eventA durable subscription catches up laterNot applicable
Use whenObjects in one program react to another object's changesServices react to events and must scale or survive failures independentlyMany objects interact in tangled ways and you want the rules in one place

An in-process event bus (Guava EventBus, Spring events) sits in between: observers subscribe to an event type instead of a specific subject, which decouples publishers from subscribers inside one program. See pub/sub and events for the distributed version, and Command for when you want to store the request itself rather than broadcast that something happened.

When not to use it

In the interview

Your turn: price alerts

Users set alerts like "tell me once when AAPL goes above 200". Many users watch the same stock, and an alert removes itself after firing. Sketch the classes and the notify loop, and say what goes wrong with a naive ArrayList loop.

Compare with our answer
interface PriceObserver { void onPrice(String symbol, double price); }

final class Ticker {
    private final Map<String, List<PriceObserver>> bySymbol = new ConcurrentHashMap<>();

    public void subscribe(String symbol, PriceObserver o) {
        bySymbol.computeIfAbsent(symbol, s -> new CopyOnWriteArrayList<>()).add(o);
    }
    public void unsubscribe(String symbol, PriceObserver o) {
        List<PriceObserver> list = bySymbol.get(symbol);
        if (list != null) list.remove(o);
    }
    public void publish(String symbol, double price) {
        for (PriceObserver o : bySymbol.getOrDefault(symbol, List.of())) {   // snapshot iteration
            try { o.onPrice(symbol, price); }
            catch (RuntimeException e) { System.err.println("alert failed: " + e); }
        }
    }
}

final class AboveAlert implements PriceObserver {
    private final Ticker ticker; private final String user; private final double limit;
    public AboveAlert(Ticker ticker, String user, double limit) {
        this.ticker = ticker; this.user = user; this.limit = limit;
    }
    public void onPrice(String symbol, double price) {
        if (price > limit) {
            System.out.println("Tell " + user + ": " + symbol + " is " + price);
            ticker.unsubscribe(symbol, this);              // one-shot: safe with copy-on-write
        }
    }
}

// Client
Ticker t = new Ticker();
t.subscribe("AAPL", new AboveAlert(t, "priya", 200));
t.publish("AAPL", 199.5);   // nothing
t.publish("AAPL", 201.0);   // Tell priya: AAPL is 201.0, then the alert removes itself
t.publish("AAPL", 205.0);   // nothing

With a plain ArrayList and a for-each loop, the alert removing itself throws ConcurrentModificationException in Java; in Python, removing from the list being iterated skips the next alert. At scale, with a million alerts on one symbol, you would not loop over them all: keep alerts in a sorted structure by threshold and fire only those the price has crossed.

A strong answer mentions: observers grouped by symbol, so a price only reaches its own watchers · one-shot unsubscribe inside the callback · safe iteration (snapshot or copy-on-write) · one failing alert isolated from the others · a sorted index by threshold when there are many alerts per symbol.

Observer on one page
  • Intent: one subject, many observers; when the subject changes it calls update() on each, knowing only the interface.
  • Beats polling: no wasted questions, no delay; beats direct calls: the subject doesn't depend on its listeners.
  • Push vs pull: push data, or let observers read the subject; prefer an immutable event object with old and new values.
  • Correct notify loop: iterate a snapshot or copy-on-write list · catch and log each observer's exception · notify only on real change · beware re-entrant updates.
  • Order is not guaranteed; don't let observers depend on each other.
  • Sync by default: a slow observer slows the subject. Async fixes speed, not durability.
  • Lapsed listener leak: always unsubscribe on a lifecycle hook; weak references help but can drop inline lambdas.
  • Don't notify inside an uncommitted transaction: after-commit listeners or an outbox.
  • In-process Observer → event bus → pub/sub broker as listeners move to other services and must survive crashes.
Your turn: the requirement changes

placeOrder() notifies four in-process observers: email, SMS, analytics and loyalty points. Two problems appear in production: the SMS provider sometimes takes 3 seconds, making checkout slow, and last week an analytics bug threw an exception that stopped the loyalty observer from running for a whole day. Then the business says: "loyalty points must never be lost, even if a server crashes." What do you change?

Compare with our answer
  • Isolate failures now: wrap each observer call in its own try/catch and log, so one bug cannot block the others.
  • Make slow observers asynchronous: hand SMS and email to an executor or a job queue, so checkout returns without waiting.
  • Notify after commit: run the listeners only after the order transaction succeeds, so nobody acts on a rolled-back order.
  • Durability for loyalty: in-memory observers cannot promise "never lost". Write an OrderPlaced row to an outbox table in the same transaction as the order, and have a relay publish it to a broker (Kafka, SQS); the loyalty service consumes it and is idempotent (keyed by order ID), because delivery is at-least-once.
  • Monitor it: alert on outbox lag and on consumer errors.

A strong answer mentions: per-observer exception isolation · async for slow observers · after-commit notification · an outbox plus broker for must-not-lose events · idempotent consumers · monitoring of the backlog.

Interactive labPractise it: polling vs observers, and a listener that joins lateOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. OrderService.placeOrder() ends with direct calls to email, inventory, analytics and fraud checks, and a new reaction is requested almost every month. Which change fits best?

2. A trading app's dashboard screen subscribes to a price feed when it opens. After users open and close it a few hundred times, memory keeps growing and closed screens still log price updates. What is the most likely cause and fix?

3. A subject notifies five observers in a for-each loop. The second one throws a NullPointerException, and users report that the fourth observer's emails stopped going out. What is the best fix in the subject?

4. A one-shot alert calls ticker.unsubscribe(this) from inside its update(). In Java, with observers stored in an ArrayList, this throws ConcurrentModificationException. Which fix is correct?

5. A listener sends a confirmation email when OrderPlaced is published inside the order's database transaction. Sometimes payment fails, the transaction rolls back, and the customer has already been emailed. What should change?

6. A PriceSubject notifies observers on a thread pool. Each observer is passed the subject and calls subject.price() when it runs. Some alerts report a price different from the one that triggered them. What is the best fix?

7. A shop's order service runs on 20 servers. The recommendation service, run by another team, needs every order event, and must catch up on anything it missed during its deploys. Which design fits?

8. A team switches their subject to hold observers through weak references to stop leaks. Now some handlers, registered as subject.subscribe(e -> screen.refresh(e)), stop firing after a few minutes. Why?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.