LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 35 OF 48

Observer Pattern in Java: Listeners, Push vs Pull, Pub/Sub

The Observer pattern with a parcel tracking example: why a subject should not call every consumer by name, the listener interface, subscribe and unsubscribe, push versus pull, memory leaks from forgotten listeners, failing and slow listeners, how it differs from pub/sub with a broker, where Java uses it, and where it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 146 lines, with a small main() demo. Save it as ParcelTracker.java, then run javac ParcelTracker.java && java ParcelTracker.

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/** Observer pattern: a parcel announces status changes, and any number of listeners react. */
public class ParcelTracker {

    enum ParcelStatus { PACKED, IN_TRANSIT, OUT_FOR_DELIVERY, DELIVERED }

    // ---------- 1. The problem: the parcel calls every consumer by name ----------
    static final class TightlyCoupledParcel {
        private ParcelStatus status = ParcelStatus.PACKED;

        void moveTo(ParcelStatus next) {
            status = next;
            // Every new consumer means editing this method, and one failure stops the rest.
            System.out.println("  [tight] sms: parcel is " + status);
            System.out.println("  [tight] dashboard refreshed");
            System.out.println("  [tight] eta recalculated");
        }
    }

    // ---------- 2. The clean version ----------

    /** The event: small and immutable, so no listener can change what others see. */
    record StatusChange(String parcelId, ParcelStatus from, ParcelStatus to, String hub) {}

    /** The observer interface: the only thing the subject knows about its listeners. */
    interface ShipmentListener {
        void onStatusChange(StatusChange change);
    }

    /** Returned by subscribe; closing it stops the events. Closing twice is harmless. */
    interface Subscription extends AutoCloseable {
        @Override
        void close();
    }

    /** The subject. */
    static final class ParcelShipment {
        private final String id;
        private ParcelStatus status = ParcelStatus.PACKED;
        // Copy-on-write: a listener may unsubscribe while we are notifying.
        private final List<ShipmentListener> listeners = new CopyOnWriteArrayList<>();

        ParcelShipment(String id) { this.id = id; }

        Subscription subscribe(ShipmentListener listener) {
            listeners.add(listener);
            return () -> listeners.remove(listener);
        }

        int listenerCount() { return listeners.size(); }

        void moveTo(ParcelStatus next, String hub) {
            if (next == status) {
                return; // no change, no noise
            }
            StatusChange change = new StatusChange(id, status, next, hub);
            status = next; // update first, then notify
            for (ShipmentListener listener : listeners) {
                try {
                    listener.onStatusChange(change);
                } catch (RuntimeException e) {
                    System.out.println("  a listener failed (" + e.getMessage() + "), others still notified");
                }
            }
        }
    }

    // ---------- concrete observers ----------

    static final class CustomerSmsAlert implements ShipmentListener {
        @Override
        public void onStatusChange(StatusChange c) {
            if (c.to() == ParcelStatus.OUT_FOR_DELIVERY || c.to() == ParcelStatus.DELIVERED) {
                System.out.println("  sms: parcel " + c.parcelId() + " is " + c.to());
            }
        }
    }

    static final class ShopDashboard implements ShipmentListener {
        private final Map<ParcelStatus, Integer> counts = new EnumMap<>(ParcelStatus.class);

        @Override
        public void onStatusChange(StatusChange c) {
            counts.merge(c.to(), 1, Integer::sum);
            System.out.println("  dashboard: " + counts);
        }
    }

    static final class EtaPredictor implements ShipmentListener {
        @Override
        public void onStatusChange(StatusChange c) {
            String eta = switch (c.to()) {
                case PACKED -> "3 days";
                case IN_TRANSIT -> "2 days";
                case OUT_FOR_DELIVERY -> "today by 6 pm";
                case DELIVERED -> "done";
            };
            System.out.println("  eta: " + eta + " (seen at " + c.hub() + ")");
        }
    }

    /** A broken webhook, to show that one failure does not stop the loop. */
    static final class FlakyWebhook implements ShipmentListener {
        @Override
        public void onStatusChange(StatusChange c) {
            throw new IllegalStateException("shop webhook timed out");
        }
    }

    public static void main(String[] args) {
        System.out.println("Problem: the parcel calls everyone by name");
        new TightlyCoupledParcel().moveTo(ParcelStatus.IN_TRANSIT);

        System.out.println();
        System.out.println("Observer: the parcel only knows ShipmentListener");
        ParcelShipment parcel = new ParcelShipment("P-7731");
        List<Subscription> subscriptions = new ArrayList<>();
        subscriptions.add(parcel.subscribe(new CustomerSmsAlert()));
        subscriptions.add(parcel.subscribe(new FlakyWebhook()));
        Subscription dashboard = parcel.subscribe(new ShopDashboard());
        subscriptions.add(dashboard);
        subscriptions.add(parcel.subscribe(new EtaPredictor()));
        // A late subscriber written as a lambda: no edit to ParcelShipment needed.
        subscriptions.add(parcel.subscribe(c -> System.out.println("  points: +5 for " + c.parcelId())));

        System.out.println("scan at Pune hub:");
        parcel.moveTo(ParcelStatus.IN_TRANSIT, "Pune hub");

        System.out.println("dashboard screen closed, so it unsubscribes");
        dashboard.close();
        dashboard.close(); // harmless

        System.out.println("scan at the local station:");
        parcel.moveTo(ParcelStatus.OUT_FOR_DELIVERY, "local station");

        System.out.println("listeners before cleanup: " + parcel.listenerCount());
        subscriptions.forEach(Subscription::close); // owners close handles: no lapsed listeners
        System.out.println("listeners after cleanup: " + parcel.listenerCount());
        parcel.moveTo(ParcelStatus.DELIVERED, "doorstep"); // nobody listening, nothing printed
    }
}

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.

The naive version
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.

In one sentence
  • 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.

The observer side
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.

ParcelShipment
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.

Two styles
  • 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.

The leak
  • 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.

Real-world rules
  • 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.

Key differences
  • 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 / skip it
  • 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.

Where you have seen it
  • 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.

Where it fits
  • 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.

Common mistakes
  • 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

Interview questions

What problem does the Observer pattern solve?

It lets one object announce a change to any number of interested objects without depending on their concrete classes. New reactions are added by writing a new listener, not by editing the subject.

What is the difference between push and pull in Observer?

In push, the subject sends the changed data in the event, so observers need nothing else. In pull, the subject only signals that something changed and observers query it for what they need, which is flexible but couples them to the subject and they may read a newer state.

What is the lapsed listener problem?

A listener that is never unsubscribed stays referenced by the subject, so it cannot be garbage collected and keeps receiving events. Return a subscription handle and close it when the listener’s owner is done; weak references are a last resort because they make behaviour depend on the garbage collector.

How is Observer different from publish/subscribe?

In Observer the subject holds direct references to its observers and usually calls them synchronously in the same process. In pub/sub a broker sits between publishers and subscribers, who only share a topic, and delivery is often asynchronous, buffered and across services.

What happens if one observer throws an exception?

In a naive loop it stops the remaining observers from being notified. Catch exceptions per listener, log them, and continue, so one faulty consumer cannot hide the change from the others.

How do you make observer notification thread-safe?

Use a CopyOnWriteArrayList or iterate over a snapshot so listeners can subscribe or unsubscribe during notification. Build an immutable event after the state change, and hand slow listeners to an executor so they do not block the thread that made the change.

Why was java.util.Observable deprecated?

It is a class rather than an interface, so subjects had to extend it, its event model is weak (an untyped Object argument), and it gives no guarantees about ordering or thread safety. Since Java 9 the advice is to use java.beans property change support, java.util.concurrent.Flow, or your own small listener interface.

Where would you use Observer in a vending machine or elevator design?

In a vending machine, the machine notifies a listener after each sale so an operator dashboard can alert on low stock. In an elevator, the car notifies floor displays and button panels of its position and direction, keeping the scheduling logic free of UI code.