SyntaxPilot
Courses/Low-Level Design/Lesson 35
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 35 of 90

Observer pattern

Observer patternsubjectobserversubscribe and unsubscribenotifypush vs pull modelevent listenersevent buslapsed listener problemweak referencesjava.util.Observer deprecationPropertyChangeListener

These are the notes for Low-Level Design (LLD) episode 35, the second behavioural pattern (patterns about how objects share work and talk to each other). The Observer pattern answers one question: when one object changes, how do many others find out, without the first one knowing who they are? We start with a newspaper subscription, watch Asha's food-delivery order crash because no rider has been assigned yet, and invent the pattern as the fix. Then: push vs pull, event listeners and an event bus, the lapsed listener memory leak (with a real OutOfMemoryError), weak references, and what Java itself offers (java.util.Observer, deprecated since Java 9, and java.beans.PropertyChangeListener). Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: a newspaper subscription

The newspaper In code
The newspaper office prints today's news The subject: the object whose state changes and that others care about
Homes that get the paper; the office only has a list of addresses Observers: objects that want to hear about changes (to observe = to watch)
Sign up any day, cancel any day Subscribe / unsubscribe: join or leave the list while the program runs
The paper reaches everyone on the list every morning Notify: go through the list and call each observer

State means the data an object holds right now (an order's status: PLACED, COOKING, ...).

2. The problem: an order that calls everyone

Three classes care about an order: the customer app, the restaurant and the rider. Order holds all three as fields and calls each one by name. The rider is only assigned later, when one accepts the order:

class CustomerApp { void show(String s)   { System.out.println("App:        your order is " + s); } }
class Restaurant  { void update(String s) { System.out.println("Restaurant: order is " + s); } }
class Rider       { void alert(String s)  { System.out.println("Rider:      pick-up status " + s); } }

class Order {                                            // knows EVERY class that cares
    CustomerApp app = new CustomerApp();
    Restaurant restaurant = new Restaurant();
    Rider rider;                                         // assigned later, once a rider accepts
    void setStatus(String status) {
        System.out.println("-- " + status + " --");
        app.show(status);
        restaurant.update(status);
        rider.alert(status);
    }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order();
        order.setStatus("PLACED");                       // no rider yet
        order.setStatus("COOKING");
    }
}
-- PLACED --
App:        your order is PLACED
Restaurant: order is PLACED
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Rider.alert(String)" because "this.rider" is null
    at Order.setStatus(Main.java:13)
    at Main.main(Main.java:19)

null means "no object yet"; calling a method on it throws NullPointerException.

Why it failed

  • Order is hard-wired to every class that cares about it. This is tight coupling (episode 10): one class depends on the exact details of many others.
  • If one of them is missing (null), the whole status update crashes.
  • Every new listener (an SMS service, a rating screen) means editing Order again.
  • Order should only know that someone is listening, and listeners should join and leave at runtime: a list of listeners plus one shared method.

3. The fix: subscribe and notify

import java.util.*;
interface OrderObserver { void onStatus(String orderId, String status); }   // the observer

class Order {                                            // the subject
    private final String id;
    private final List<OrderObserver> observers = new ArrayList<>();
    Order(String id) { this.id = id; }
    void subscribe(OrderObserver o)   { observers.add(o); }
    void unsubscribe(OrderObserver o) { observers.remove(o); }
    void setStatus(String status) {
        System.out.println("-- " + status + " --");
        for (OrderObserver o : observers) o.onStatus(id, status);     // notify
    }
}
class CustomerApp implements OrderObserver {
    public void onStatus(String id, String s) { System.out.println("App: order " + id + " is " + s); }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order("A-42");
        order.subscribe(new CustomerApp());
        order.subscribe((id, s) -> System.out.println("Restaurant: " + s));
        order.setStatus("PLACED");                       // no rider yet: nobody crashes
        OrderObserver ravi = (id, s) -> System.out.println("Rider Ravi: " + s);
        order.subscribe(ravi);                           // a rider accepts
        order.setStatus("PICKED UP");
        order.unsubscribe(ravi);                         // his job is done
        order.setStatus("DELIVERED");
    }
}
-- PLACED --
App: order A-42 is PLACED
Restaurant: PLACED
-- PICKED UP --
App: order A-42 is PICKED UP
Restaurant: PICKED UP
Rider Ravi: PICKED UP
-- DELIVERED --
App: order A-42 is DELIVERED
Restaurant: DELIVERED
  • OrderObserver is the observer interface: one method, onStatus.
  • Order is the subject: it keeps a List<OrderObserver>, subscribe adds, unsubscribe removes, and the loop in setStatus is notify.
  • CustomerApp is a concrete observer; the restaurant and rider subscribe with lambdas (the interface has one method, so it is a functional interface).
  • No rider yet means the rider is simply not on the list: nothing to call, nothing to crash.
  • Order does not name a single listener class.

4. It has a name: the Observer pattern

   +------------------------------+          +----------------------------+
   | Order            «subject»   |<>------->| «interface» OrderObserver  |
   | - observers: List            | 0..*     | + onStatus(id, status)     |
   | + subscribe(o)               |          +----------------------------+
   | + unsubscribe(o)             |               ^         ^         ^
   | + setStatus(s)  -> notify    |               :         :         :  (implements)
   +------------------------------+         CustomerApp  Restaurant  Rider

The classic intent (SourceMaking): "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." One-to-many: one subject, any number of observers. The same idea goes by publish-subscribe (pub-sub): publishers send, subscribers receive.

Role In our example Job
Subject Order Keeps the list; notifies on every change
Observer OrderObserver The one method all listeners implement
Concrete observer CustomerApp, the restaurant and rider lambdas React to the news

5. Push vs pull

Push model Pull model
What the subject sends The data: onStatus(id, status) Itself: changed(this)
Observer then Uses what it was given Calls getters for what it needs
Good Simple; observers don't depend on the subject class Flexible; each observer reads different fields
Bad Everyone gets the same data, needed or not Observers depend on Order's getters

Pull model, run for real:

import java.util.*;

interface OrderObserver { void changed(Order order); }      // PULL: we pass the subject

class Order {
    private final String id; private String status = "PLACED"; private int etaMinutes = 40;
    private final List<OrderObserver> observers = new ArrayList<>();
    Order(String id) { this.id = id; }
    String getId() { return id; }
    String getStatus() { return status; }
    int getEtaMinutes() { return etaMinutes; }
    void subscribe(OrderObserver o) { observers.add(o); }
    void update(String status, int eta) {
        this.status = status; this.etaMinutes = eta;
        for (OrderObserver o : observers) o.changed(this);
    }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order("A-42");
        order.subscribe(o -> System.out.println("App: " + o.getStatus() + ", arriving in " + o.getEtaMinutes() + " min"));
        order.subscribe(o -> System.out.println("Restaurant: order " + o.getId() + " is " + o.getStatus()));
        order.update("COOKING", 30);
    }
}
App: COOKING, arriving in 30 min
Restaurant: order A-42 is COOKING

6. Event listeners and an event bus

In real apps observers are usually called listeners, and the news is an event: a message that says "this just happened". With many kinds of events, a central event bus keeps a map from a topic ("order.delivered") to its handlers. Publishers and subscribers only know the bus and the topic name, never each other. A Consumer<String> is Java's functional interface for "a function that takes a value and returns nothing".

import java.util.*;
import java.util.function.Consumer;

class EventBus {                                         // one central board for all events
    private final Map<String, List<Consumer<String>>> subs = new HashMap<>();
    void subscribe(String topic, Consumer<String> handler) {
        subs.computeIfAbsent(topic, t -> new ArrayList<>()).add(handler);
    }
    void publish(String topic, String data) {
        for (Consumer<String> h : subs.getOrDefault(topic, List.of())) h.accept(data);
    }
}
public class Main {
    public static void main(String[] args) {
        EventBus bus = new EventBus();
        bus.subscribe("order.delivered", id -> System.out.println("Rating screen for " + id));
        bus.subscribe("order.delivered", id -> System.out.println("Rider paid for " + id));
        bus.subscribe("payment.failed",  id -> System.out.println("Retry payment for " + id));

        bus.publish("order.delivered", "A-42");          // publisher doesn't know who listens
        bus.publish("payment.failed", "B-7");
        bus.publish("order.cancelled", "C-1");           // nobody listens: nothing happens
    }
}
Rating screen for A-42
Rider paid for A-42
Retry payment for B-7

(The last event has no subscribers, so nothing happens and nothing crashes: getOrDefault returns an empty list.)

7. The trap: the lapsed listener

A subject that lives a long time (a price feed) keeps a list of listeners. Screens subscribe when they open... and nobody unsubscribes when they close:

import java.util.*;

interface Listener { void onPrice(int price); }
class PriceFeed {                                        // the subject lives all day
    final List<Listener> listeners = new ArrayList<>();
    void subscribe(Listener l)   { listeners.add(l); }
    void unsubscribe(Listener l) { listeners.remove(l); }
}
class MenuScreen implements Listener {                   // opened and closed again and again
    final byte[] pictures = new byte[100_000];           // 100 KB of food photos
    public void onPrice(int price) { }
}
public class Main {
    public static void main(String[] args) {
        PriceFeed feed = new PriceFeed();
        for (int i = 1; i <= 100_000; i++) {
            MenuScreen screen = new MenuScreen();
            feed.subscribe(screen);                      // screen opens
            // ... user looks, then closes the screen; we forget to unsubscribe
            if (i % 2_000 == 0) System.out.println(i + " screens opened, listeners: " + feed.listeners.size());
        }
    }
}
...
10000 screens opened, listeners: 10000
12000 screens opened, listeners: 12000
14000 screens opened, listeners: 14000
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at MenuScreen.<init>(Main.java:10)
    at Main.main(Main.java:17)

The closed screens can never be garbage-collected, because the feed's list still points to them. This is the lapsed listener problem, a memory leak (memory that is never given back). The fix is a matching unsubscribe for every subscribe:

import java.util.*;

interface Listener { void onPrice(int price); }
class PriceFeed {                                        // the subject lives all day
    final List<Listener> listeners = new ArrayList<>();
    void subscribe(Listener l)   { listeners.add(l); }
    void unsubscribe(Listener l) { listeners.remove(l); }
}
class MenuScreen implements Listener {                   // opened and closed again and again
    final byte[] pictures = new byte[100_000];           // 100 KB of food photos
    public void onPrice(int price) { }
}
public class Main {
    public static void main(String[] args) {
        PriceFeed feed = new PriceFeed();
        for (int i = 1; i <= 100_000; i++) {
            MenuScreen screen = new MenuScreen();
            feed.subscribe(screen);                      // screen opens
            feed.unsubscribe(screen);                    // screen closes: unsubscribe
            if (i % 25_000 == 0) System.out.println(i + " screens opened, listeners: " + feed.listeners.size());
        }
    }
}
25000 screens opened, listeners: 0
50000 screens opened, listeners: 0
75000 screens opened, listeners: 0
100000 screens opened, listeners: 0

Weak references

A normal reference is strong: while anything points to an object strongly, the garbage collector (the part of Java that frees unused memory) must keep it. A WeakReference<T> does not keep its object alive: once no strong references remain, the object can be collected and get() returns null.

import java.lang.ref.WeakReference;

public class Main {
    public static void main(String[] args) {
        Object screen = new Object();                    // a strong reference
        WeakReference<Object> weak = new WeakReference<>(screen);
        System.out.println("before: " + (weak.get() != null));
        screen = null;                                   // nobody holds it strongly now
        System.gc();
        System.out.println("after gc: " + (weak.get() != null));
    }
}
before: true
after gc: false

A subject can store listeners as weak references so closed screens disappear on their own. The catch: a lambda that only the list points to disappears too, and you cannot predict when the collector runs (System.gc() is only a request). Unsubscribing explicitly is still the clearest fix.

8. What Java gives you

java.util.Observable (a class) and java.util.Observer (an interface) have existed since Java 1.0:

import java.util.Observable;
import java.util.Observer;

class OrderStatus extends Observable {                   // the old JDK subject (Java 1.0)
    void set(String s) { setChanged(); notifyObservers(s); }
}
public class Main {
    public static void main(String[] args) {
        OrderStatus status = new OrderStatus();
        Observer app = (subject, arg) -> System.out.println("App got: " + arg);
        status.addObserver(app);
        status.set("COOKING");
    }
}
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
App got: COOKING

The Javadoc marks them @Deprecated(since="9"): "This class and the Observer interface have been deprecated." The reasons given: the event model is quite limited, the order of notifications is unspecified, and state changes are not one-for-one with notifications. Deprecated means "still there, but you shouldn't use it in new code". Being a class, Observable also forces your subject to extends Observable, using up its one superclass. For a richer event model the Javadoc points to the java.beans package (and to java.util.concurrent for ordered messages between threads, and the Flow API for reactive streams):

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

class Order {
    private final PropertyChangeSupport changes = new PropertyChangeSupport(this);
    private String status = "PLACED";
    void addListener(PropertyChangeListener l) { changes.addPropertyChangeListener(l); }
    void setStatus(String s) {
        String old = status; status = s;
        changes.firePropertyChange("status", old, s);    // tells listeners old AND new value
    }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order();
        order.addListener(e -> System.out.println(e.getPropertyName() + ": "
                + e.getOldValue() + " -> " + e.getNewValue()));
        order.setStatus("COOKING");
        order.setStatus("COOKING");                      // same value: no event
        order.setStatus("ON THE WAY");
    }
}
status: PLACED -> COOKING
status: COOKING -> ON THE WAY

PropertyChangeSupport keeps the listener list for you; firePropertyChange sends a PropertyChangeEvent with the property's name, old value and new value, and fires only when the value really changed.

Common mistakes

Mistake What you see Why Fix
Subject calls each class by name NullPointerException: Cannot invoke "Rider.alert(String)" because "this.rider" is null Hard-wired to every listener A list of observers
Subscribe without unsubscribe java.lang.OutOfMemoryError: Java heap space The list keeps closed objects alive Unsubscribe on close (or weak references)
Unsubscribing while the list is being looped java.util.ConcurrentModificationException The list changed during the for loop Loop over a copy: List.copyOf(observers)
Using java.util.Observable Note: Main.java uses or overrides a deprecated API. Deprecated since Java 9 Your own interface, or java.beans
Observer changes the subject inside onStatus No error: an endless notify loop A change triggers a change Don't set state while notifying; only fire on real changes
Unsubscribing with a new lambda Nothing is removed A new lambda is a different object Keep the same reference to remove it

The ConcurrentModificationException case, run for real (the rider leaves while being notified):

import java.util.*;

interface OrderObserver { void onStatus(String status); }
class Order {
    final List<OrderObserver> observers = new ArrayList<>();
    void setStatus(String s) { for (OrderObserver o : observers) o.onStatus(s); }
}
public class Main {
    public static void main(String[] args) {
        Order order = new Order();
        OrderObserver[] rider = new OrderObserver[1];
        rider[0] = s -> {
            System.out.println("Rider: " + s);
            if (s.equals("DELIVERED")) order.observers.remove(rider[0]);   // leave DURING notify
        };
        order.observers.add(rider[0]);
        order.observers.add(s -> System.out.println("App: " + s));
        order.observers.add(s -> System.out.println("Restaurant: " + s));
        order.setStatus("DELIVERED");
    }
}
Rider: DELIVERED
Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1095)
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1049)
    at Order.setStatus(Main.java:6)
    at Main.main(Main.java:19)

Mini project: a railway platform announcer

A train's platform changes; the station board and Priya's SMS listen; Priya unsubscribes once she boards; no event when the platform doesn't really change.

Solution
import java.util.*;

interface PlatformListener { void platformChanged(String train, int from, int to); }

class Train {                                               // subject
    private final String name; private int platform;
    private final List<PlatformListener> listeners = new ArrayList<>();
    Train(String name, int platform) { this.name = name; this.platform = platform; }
    void subscribe(PlatformListener l)   { listeners.add(l); }
    void unsubscribe(PlatformListener l) { listeners.remove(l); }
    void setPlatform(int p) {
        if (p == platform) return;                          // no real change: no event
        int old = platform; platform = p;
        for (PlatformListener l : List.copyOf(listeners)) l.platformChanged(name, old, p);
    }
}
public class Main {
    public static void main(String[] args) {
        Train rajdhani = new Train("12951 Rajdhani", 3);
        rajdhani.subscribe((t, a, b) -> System.out.println("Board:  " + t + " now on platform " + b));
        PlatformListener priya = (t, a, b) -> System.out.println("SMS to Priya: " + t + " moved " + a + " -> " + b);
        rajdhani.subscribe(priya);
        rajdhani.setPlatform(5);
        rajdhani.setPlatform(5);                            // same platform: nothing
        rajdhani.unsubscribe(priya);                        // Priya has boarded
        rajdhani.setPlatform(6);
    }
}
Board:  12951 Rajdhani now on platform 5
SMS to Priya: 12951 Rajdhani moved 3 -> 5
Board:  12951 Rajdhani now on platform 6

List.copyOf(listeners) loops over a copy, so a listener can safely unsubscribe while being notified.

Practice

1. Add unsubscribe(topic, handler) to the event bus and show that a removed handler is no longer called.

Answer
import java.util.*;
import java.util.function.Consumer;

class EventBus {
    private final Map<String, List<Consumer<String>>> subs = new HashMap<>();
    void subscribe(String topic, Consumer<String> h) { subs.computeIfAbsent(topic, t -> new ArrayList<>()).add(h); }
    void unsubscribe(String topic, Consumer<String> h) {
        List<Consumer<String>> list = subs.get(topic);
        if (list != null) list.remove(h);
    }
    void publish(String topic, String data) {
        for (Consumer<String> h : List.copyOf(subs.getOrDefault(topic, List.of()))) h.accept(data);
    }
}
public class Main {
    public static void main(String[] args) {
        EventBus bus = new EventBus();
        Consumer<String> rating = id -> System.out.println("Rating screen for " + id);
        bus.subscribe("order.delivered", rating);
        bus.publish("order.delivered", "A-42");
        bus.unsubscribe("order.delivered", rating);         // keep the same object to remove it
        bus.publish("order.delivered", "A-43");
        System.out.println("done");
    }
}
Rating screen for A-42
done

2. Push or pull: the app needs status and delivery time, the restaurant needs only the status, the billing service needs the total. Which model fits better?

Answer

Pull: each observer reads only what it needs through getters, and adding a field later doesn't change the observer interface. (Push with a small immutable event object, such as a record OrderChanged(...), is also fine.)

3. Why is a forgotten unsubscribe worse in a long-running server than in a small program?

Answer

The subject lives as long as the server runs (days), so every leaked listener stays in memory for days. In a short program everything is freed when the program ends.

Quick quiz

Order order = new Order("A-42");
OrderObserver app = (id, s) -> System.out.println("App: " + s);
order.subscribe(app);
order.setStatus("PLACED");
order.unsubscribe(app);
order.setStatus("COOKING");
order.subscribe(app);
order.setStatus("DELIVERED");

(a) App: PLACED (b) App: PLACED, App: COOKING (c) App: PLACED, App: DELIVERED (d) nothing

Answer

(c). The app hears PLACED, misses COOKING while unsubscribed, and hears DELIVERED after subscribing again. Observers only hear events while they are on the list.

Interview questions

  1. What is the Observer pattern? A behavioural pattern defining a one-to-many dependency: when the subject changes, all subscribed observers are notified automatically.
  2. Participants? Subject (keeps the list, notifies), observer interface, concrete observers.
  3. Push vs pull? Push sends the data in the notification; pull sends the subject and observers query it.
  4. What is the lapsed listener problem? Listeners that are never unsubscribed stay referenced by the subject and cannot be garbage-collected: a memory leak.
  5. How do you prevent it? Pair every subscribe with an unsubscribe (for example in a screen's close method), return a subscription handle that removes itself, or use weak references.
  6. Why was java.util.Observable deprecated? Since Java 9: limited event model, unspecified notification order, and it's a class you must extend. Use your own interfaces, java.beans, java.util.concurrent, or the Flow API.
  7. Observer vs event bus? In Observer, observers subscribe to a specific subject; with an event bus, publishers and subscribers only share a topic and the bus, and don't know each other.
  8. Observer vs Mediator? Observer broadcasts one-way to whoever subscribed; a Mediator coordinates many objects talking to each other through one central object.
  9. Thread safety? If observers subscribe from other threads, use a CopyOnWriteArrayList or synchronize; notify over a snapshot.
  10. Where do you see it? GUI listeners (ActionListener), PropertyChangeListener, message queues and pub-sub systems, reactive streams.

Glossary

Term Meaning, with an example
Behavioural pattern A pattern about how objects share work and communicate
Observer pattern One subject notifies many observers when it changes
Subject The object whose state changes. Order
Observer An object that wants to hear about changes. CustomerApp
State The data an object holds right now. An order's status
Subscribe / unsubscribe Join / leave the subject's list. order.subscribe(ravi)
Notify Call every observer on the list. The for loop in setStatus
One-to-many dependency One subject, any number of dependents
Tight coupling One class depends on the exact details of others (episode 10)
Push model The subject sends the data: onStatus(id, status)
Pull model The subject sends itself; observers call getters: changed(this)
Listener / event listener Another name for an observer. PropertyChangeListener
Event A message saying something happened. "order delivered"
Event bus A central object that routes events by topic from publishers to subscribers
Topic The name of a kind of event. "order.delivered"
Publish-subscribe (pub-sub) Publishers send events, subscribers receive them, without knowing each other
Consumer<T> Functional interface: takes a value, returns nothing. id -> System.out.println(id)
Handler The code that reacts to an event
Lapsed listener problem A listener never unsubscribed stays referenced and can't be freed
Memory leak Memory that is never given back while the program runs
OutOfMemoryError Thrown when the heap (Java's object memory) is full
Garbage collector The part of Java that frees memory no longer referenced
Strong reference A normal reference; it keeps the object alive
Weak reference WeakReference<T>: doesn't keep the object alive; get() returns null after collection
java.util.Observer / Observable The JDK's original observer types; deprecated since Java 9
Deprecated Still available, but not recommended for new code
PropertyChangeListener java.beans listener that receives a PropertyChangeEvent with old and new values
PropertyChangeSupport Helper that keeps the listener list and fires change events
ConcurrentModificationException Thrown when a list is changed while a for loop is going through it
List.copyOf Makes an unmodifiable copy of a list, safe to loop over
null "No object"; calling a method on it throws NullPointerException

Summary

  • Calling every interested class by name couples the subject to all of them, and crashed when the rider was null.
  • Observer: the subject keeps a list, observers implement one method, and they subscribe, unsubscribe and get notified.
  • Push sends data; pull sends the subject. An event bus routes events by topic.
  • Every subscribe needs an unsubscribe, or you get the lapsed listener leak; weak references are a backup.
  • java.util.Observer is deprecated since Java 9; use your own interface or java.beans.PropertyChangeListener.

Next episode: The Command pattern: turn a request into an object for undo, redo, queues and logs.