Java Observer Pattern: Events, Listeners and Reactive Design Explained

Maya's bookstore is part of a small chain, and the staff dashboard shows the chain's share price — one number, watched by three things. A display on the wall shows the current price. An alert fires when the price crosses 150. A log records every change, so the support desk can answer "what was the price at noon?" The catch: new watchers keep arriving — a second display, a weekly report — and every one of them means an edit to the code that sets the price. The ticker knows its listeners by name, and that is the problem.

Post 1 asked what varies? Post 2, Java Singleton Pattern: Enum, Lazy Holder & Double-Checked Locking Explained, asked how many? Post 3, Java Factory Pattern: Factory Method vs Abstract Factory With Examples, asked who decides which object gets created? Post 4, Java Builder Pattern: Build Complex Objects Without Telescoping Constructors, asked how do you assemble one object, piece by piece? Post 5, Java Adapter and Facade Patterns: Integrate Incompatible Code Cleanly, asked how do you use an interface you cannot change — and hide a whole subsystem behind one call? Post 6, Java Decorator and Proxy Patterns: Add Behavior Without Changing Classes, asked how do you add behavior to an object without changing its class — and how do you guard one without touching it? This post asks a seventh question: how do many things learn about one change, without the thing that changed knowing any of them? The answer is the Observer pattern. The principle for this lesson: When many things care about one change, let the change announce itself.

1. The customer problem

Maya's requirement is plain: every price change must reach the display, the alert, and the log — and the next watcher must be addable without touching the ticker. One broken listener must not silence the rest, and a listener that leaves must not break the delivery for the ones that stay. One price, announced once, heard by whoever is listening.

She asked for two properties: the ticker must not know its listeners by name, and a listener must be addable or removable while the ticker is running. The test for this post is simple: add a fourth listener without touching the ticker, break one listener without losing the others, and remove a listener mid-day without corrupting the next announcement.

2. Clarify the ask: what varies, what stays

Before writing any code, split the problem again:

  • What stays stable: the price, the symbol, and the one method — onPriceChange. Every watcher already uses them, and they will not change.
  • What varies: who is listening, what each listener does with the price, and when each one subscribes or leaves. The watchers vary; the announcement does not.

Section 5 shows what happens without that split: the ticker calling the display, the alert, and the log directly by name — each new watcher an edit to the ticker, each broken watcher a silent gap in the log.

3. The minimum concept: one change, many listeners

The Observer pattern answers: how does one change reach many things without the changer knowing them? Four parts, each with one job:

  • The publisher — StockTicker: it owns the price, keeps the listener list, and announces each change.
  • The listener interface — PriceListener: one method, onPriceChange, that every watcher implements.
  • The concrete listeners — DisplayListener, AlertListener, LoggingListener: each one does its own job with the price it is given.
  • The client — the code that sets prices, which calls setPrice and never thinks about listeners at all.

The difference from post 6 is worth naming precisely. A decorator wraps one object to add behavior to it, and a proxy guards one object to control access to it — both are one-to-one, and the caller usually knows the wrapper is there. An observer is one-to-many: the ticker announces, and whoever is listening hears. The ticker never names its listeners, and the listeners never ask the ticker for anything — the change flows one way, from publisher to listener. The JDK once shipped its own observer — java.util.Observable and java.util.Observer. They are deprecated since Java 9, and one reason is instructive: Observable is a class, not an interface, so a ticker that already extends another class cannot be one. Write your own listener interface, as this post does. Post 8 swaps behavior at runtime instead of announcing changes.

One change, many listeners StockTicker.setPrice(152.0) DisplayListener AlertListener LoggingListener shows the price watches 150.0 records every update One price change reaches all three in the order they subscribed.

4. Build: one ticker, three listeners

Start with what stays stable — the interface, and the only imports this post needs:

import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

// One method: the publisher calls it when the price changes.
// A listener must return quickly and must never call back into the ticker.
interface PriceListener {
    void onPriceChange(String symbol, double price);
}

Now the publisher. It owns the price and the listener list, and it announces each change to the listeners in the order they subscribed:

// The publisher: it owns the price and the listener list.
// Listeners are notified in the order they subscribed.
final class StockTicker {
    private final String symbol;
    private double price;
    private final List<PriceListener> listeners = new ArrayList<>();

    StockTicker(String symbol) {
        this.symbol = symbol;
    }

    void subscribe(PriceListener listener) {
        listeners.add(listener);
    }

    void unsubscribe(PriceListener listener) {
        listeners.remove(listener);
    }

    void setPrice(double price) {
        this.price = price;
        notifyListeners();
    }

    double price() {
        return price;
    }

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

    private void notifyListeners() {
        for (PriceListener listener : listeners) {
            listener.onPriceChange(symbol, price);
        }
    }
}

The three listeners, each with one job. The display shows the price, the log records it — and keeps what it recorded, so the checks in section 6 can prove the delivery happened:

// Shows the price on the wall.
final class DisplayListener implements PriceListener {
    public void onPriceChange(String symbol, double price) {
        System.out.println("display: " + symbol + " " + price);
    }
}

// Records every update, and remembers what it recorded.
final class LoggingListener implements PriceListener {
    private final List<String> received = new ArrayList<>();

    public void onPriceChange(String symbol, double price) {
        received.add(symbol + " " + price);
        System.out.println("logged: " + symbol + " " + price);
    }

    int count() {
        return received.size();
    }

    List<String> received() {
        return List.copyOf(received);
    }
}

The alert is the careful one: it fires only when the price crosses 150.0 — not on every price above it. The first price only sets the baseline: there is nothing to cross yet.

// Fires only when the price crosses above 150.0.
final class AlertListener implements PriceListener {
    private static final double THRESHOLD = 150.0;
    private double lastPrice = Double.NaN;
    private int alerts;

    public void onPriceChange(String symbol, double price) {
        if (!Double.isNaN(lastPrice) && lastPrice <= THRESHOLD && price > THRESHOLD) {
            alerts++;
            System.out.println("alert: " + symbol + " crossed above " + THRESHOLD);
        }
        lastPrice = price;
    }

    int alerts() {
        return alerts;
    }
}

The whole thing working, end to end — four prices, three listeners, one announcement each:

public class TickerDemo {
    public static void main(String[] args) {
        StockTicker ticker = new StockTicker("ACME");
        ticker.subscribe(new DisplayListener());
        ticker.subscribe(new AlertListener());
        ticker.subscribe(new LoggingListener());
        ticker.setPrice(140.0);
        ticker.setPrice(152.0);
        ticker.setPrice(148.0);
        ticker.setPrice(155.0);
    }
}
display: ACME 140.0
logged: ACME 140.0
display: ACME 152.0
alert: ACME crossed above 150.0
logged: ACME 152.0
display: ACME 148.0
logged: ACME 148.0
display: ACME 155.0
alert: ACME crossed above 150.0
logged: ACME 155.0

Read that output out loud: every price reaches every listener, in subscription order, and the alert fires exactly twice — on the two crossings above 150.0, not on the 148.0 dip between them. The ticker never names a listener; the listeners never ask the ticker for anything. But the loop that delivers the announcement is doing three things it should not trust — and section 5 opens each one up.

5. Break it: the listener that silenced the rest, the delivery that broke the loop, and the price that changed mid-announcement

The first version works. Working is not the same as correct — and this version has three holes.

The first hole is the delivery loop itself: one listener throws, and every listener after it never hears the price. A listener whose alert service is down — a broken connection, a bad configuration — throws on every update:

// A listener that always throws — the alert service is down.
final class BrokenListener implements PriceListener {
    public void onPriceChange(String symbol, double price) {
        throw new IllegalStateException("alert service is down");
    }
}
StockTicker ticker = new StockTicker("ACME");
LoggingListener log = new LoggingListener();
ticker.subscribe(new DisplayListener());
ticker.subscribe(new BrokenListener());
ticker.subscribe(log);
try {
    ticker.setPrice(140.0);
} catch (IllegalStateException e) {
    System.out.println("caught: " + e.getMessage());
}
System.out.println("log entries: " + log.count());
display: ACME 140.0
caught: alert service is down
log entries: 0

Read that output again: the display heard the price, the exception reached the caller — and the log has no record of the change at all. The logging listener was subscribed, the price was set, and nothing in the log says so. One listener's failure became every listener after its silence. The ticker's job was to announce; instead, it let one listener's exception end the announcement.

The second hole is the list the loop walks: a listener that unsubscribes during delivery changes the list under the loop's feet. A listener that leaves after its first update — a one-shot report, a trial that expired — unsubscribes from inside its own notification:

// Unsubscribes itself the first time it hears a price.
final class SelfRemovingListener implements PriceListener {
    private final StockTicker ticker;
    private boolean removed;

    SelfRemovingListener(StockTicker ticker) {
        this.ticker = ticker;
    }

    public void onPriceChange(String symbol, double price) {
        if (!removed) {
            removed = true;
            ticker.unsubscribe(this);
            System.out.println("self-remover: unsubscribed");
        }
    }
}
StockTicker ticker = new StockTicker("ACME");
LoggingListener log = new LoggingListener();
ticker.subscribe(new DisplayListener());
ticker.subscribe(new SelfRemovingListener(ticker));
ticker.subscribe(log);
ticker.subscribe(new AlertListener());
try {
    ticker.setPrice(140.0);
} catch (ConcurrentModificationException e) {
    System.out.println("caught: " + e);
}
System.out.println("log entries: " + log.count());
display: ACME 140.0
self-remover: unsubscribed
caught: java.util.ConcurrentModificationException
log entries: 0

The loop walked the live list, the list changed mid-walk, and the walk died — the log and the alert never heard the price at all. And the failure depends on where the remover sits in the list, which is the worst kind of bug: with only three listeners, the same removal silently skips the listener after it instead of throwing — no exception, no record, just a missing entry. Same code, different order, different outcome. A delivery whose result depends on registration order is a delivery nobody can reason about.

The third hole is the smallest, and the easiest to miss in review: a listener that writes back to the ticker while the ticker is still announcing. A listener that "corrects" the price it just heard sets a new price — from inside its own notification:

// "Corrects" the price by setting a new one — from inside a notification.
final class MeddlingListener implements PriceListener {
    private final StockTicker ticker;
    private boolean corrected;

    MeddlingListener(StockTicker ticker) {
        this.ticker = ticker;
    }

    public void onPriceChange(String symbol, double price) {
        if (!corrected) {
            corrected = true;
            ticker.setPrice(999.0);
        }
    }
}
StockTicker ticker = new StockTicker("ACME");
LoggingListener log = new LoggingListener();
ticker.subscribe(new DisplayListener());
ticker.subscribe(new MeddlingListener(ticker));
ticker.subscribe(log);
ticker.setPrice(140.0);
System.out.println("ticker price: " + ticker.price());
System.out.println("log last entry: " + log.received().get(log.count() - 1));
display: ACME 140.0
display: ACME 999.0
logged: ACME 999.0
logged: ACME 999.0
ticker price: 999.0
log last entry: ACME 999.0

The nested announcement ran inside the outer one — and the outer one was still reading the ticker's price field. By the time the loop reached the log, the field said 999.0, so the log recorded 999.0 twice and never recorded 140.0 at all. Nothing threw, nothing looks wrong at a glance, and the record has lost a price entirely: two entries for a price that was set once, zero for the price the announcement was about. A listener that writes back to the ticker does not just reorder the record — it rewrites the announcement while it is still being delivered. The same shape of hole, without any meddling at all: a listener that takes seconds to return holds the publisher's thread, because setPrice returns only after every listener returns. A slow listener does not just delay itself — it delays every price after it, and the ticker with them. Slow work belongs on the listener's own thread, never in onPriceChange.

6. Harden it: isolate failures, snapshot the list, guard the delivery

The fix shape is the same every time: the implied rule, now written where the code can enforce it. First, the delivery: each listener gets its own try and catch, the loop walks a snapshot taken when the price changed, and a listener that tries to set a price mid-delivery is refused. Only the two methods change; the rest of StockTicker stays as section 4 wrote it:

// One new field on the ticker:
private boolean notifying;

void setPrice(double price) {
    if (notifying) {
        throw new IllegalStateException("a listener must not change the price during notification");
    }
    this.price = price;
    notifyListeners();
}

private void notifyListeners() {
    // Notify a snapshot: a listener that subscribes or unsubscribes
    // during delivery must not change this delivery.
    List<PriceListener> snapshot = new ArrayList<>(listeners);
    notifying = true;
    try {
        for (PriceListener listener : snapshot) {
            try {
                listener.onPriceChange(symbol, price);
            } catch (RuntimeException e) {
                System.out.println("listener failed: " + e.getMessage());
            }
        }
    } finally {
        notifying = false;
    }
}

Three things to notice. First, the catch names RuntimeException and nothing else: a listener's bug is contained and logged, and the loop goes on to the next listener — but an Error is not a listener misbehaving, it is the JVM failing, and the ticker must not swallow it. Second, the snapshot fixes the delivery at the moment the price changes: a listener that subscribes mid-delivery waits for the next price, and one that unsubscribes is still notified this once — the set of listeners for one announcement never changes halfway through. A snapshot is the right tool here because this ticker is single-threaded and the copy says exactly what it does in one line; CopyOnWriteArrayList is the answer for a ticker shared across threads, and it is a deliberate omission from this post, not an oversight. Third, the guard turns the rule from section 4 into code a listener cannot break by accident: a re-entrant setPrice throws, the per-listener catch logs it as a failed listener, and the delivery continues. The notifying flag itself is one boolean field on the ticker, set to false in the finally so no path can leave the ticker stuck.

Second, the order. Delivery order is registration order — the comment in subscribe's class already says so, and the check program below proves it by comparing the log's received list against the exact expected sequence. If order ever matters to a listener, that comment is the contract to read, not a behavior to guess at.

Third, the rule the code cannot enforce: a listener returns quickly and never blocks the publisher. The ticker delivers on the caller's thread, in order, one listener at a time — so a listener that waits on a network call or a disk write holds every listener behind it and every price after that. The interface comment says it, this section says it, and the field check repeats it: slow work belongs in the listener's own thread, and the notification loop is not the place for it.

Verify with explicit checks, not assertions — the same discipline as posts 1, 3, 4, 5, and 6. Assertions can be switched off at runtime. The check program throws on mismatch — and its counts prove the delivery survived a throwing listener, an unsubscribe, and a re-entrant price change:

public class ObserverDemo {
    public static void main(String[] args) {
        // 1. A throwing listener is isolated; the rest still hear.
        StockTicker ticker = new StockTicker("ACME");
        LoggingListener log = new LoggingListener();
        ticker.subscribe(new DisplayListener());
        ticker.subscribe(new BrokenListener());
        ticker.subscribe(log);
        ticker.setPrice(140.0);
        check("a throwing listener does not silence the rest", log.count() == 1);

        // 2. Unsubscribing during delivery is safe; the delivery finishes.
        StockTicker ticker2 = new StockTicker("ACME");
        LoggingListener log2 = new LoggingListener();
        ticker2.subscribe(new DisplayListener());
        ticker2.subscribe(new SelfRemovingListener(ticker2));
        ticker2.subscribe(log2);
        ticker2.subscribe(new AlertListener());
        ticker2.setPrice(140.0);
        check("delivery survives an unsubscribe", log2.count() == 1);
        check("the self-remover is gone", ticker2.listenerCount() == 3);

        // 3. The alert fires only on crossing 150.0.
        AlertListener alert = new AlertListener();
        StockTicker ticker3 = new StockTicker("ACME");
        ticker3.subscribe(alert);
        ticker3.setPrice(140.0);
        ticker3.setPrice(152.0);
        ticker3.setPrice(148.0);
        ticker3.setPrice(155.0);
        check("the alert fires on crossing, twice", alert.alerts() == 2);

        // 4. A listener that tries to change the price mid-delivery is refused.
        StockTicker ticker4 = new StockTicker("ACME");
        LoggingListener log4 = new LoggingListener();
        ticker4.subscribe(new DisplayListener());
        ticker4.subscribe(new MeddlingListener(ticker4));
        ticker4.subscribe(log4);
        ticker4.setPrice(140.0);
        check("a re-entrant price change is refused", ticker4.price() == 140.0);
        check("the log hears the price in order", log4.received().equals(List.of("ACME 140.0")));
    }

    static void check(String name, boolean condition) {
        if (!condition) {
            throw new IllegalStateException("FAILED: " + name);
        }
        System.out.println("ok: " + name);
    }
}
display: ACME 140.0
listener failed: alert service is down
logged: ACME 140.0
ok: a throwing listener does not silence the rest
display: ACME 140.0
self-remover: unsubscribed
logged: ACME 140.0
ok: delivery survives an unsubscribe
ok: the self-remover is gone
alert: ACME crossed above 150.0
alert: ACME crossed above 150.0
ok: the alert fires on crossing, twice
display: ACME 140.0
listener failed: a listener must not change the price during notification
logged: ACME 140.0
ok: a re-entrant price change is refused
ok: the log hears the price in order

When not to use an observer. An observer is a subscribe API, a listener list, and a delivery loop — and sometimes the change has exactly one audience. As a rule of thumb — not a law — if one thing cares, call it directly; if the set of listeners never changes, a plain loop over a fixed list beats a subscribe API; and if the event must be delivered exactly once, in a transaction, or in a guaranteed order across machines, an observer's fire-and-forget delivery is the wrong tool. The observer earns its keep when the audience is open-ended and the publisher must stay ignorant of it.

Next step, not this post: if listeners are slow, or the ticker produces prices faster than a listener can consume them, synchronous delivery has no answer — the ticker either waits or drops updates. The direction is java.util.concurrent.Flow, in the JDK since Java 9: a Publisher, a Subscriber, and a Subscription through which the subscriber requests exactly how many items it can take — that request is called backpressure. This post's ticker has none of that; it delivers every price to every listener, in order, on the caller's thread. Flow is where to look when that stops being enough.

7. Communicate: explain it to a human

The code is only half the job. Here is how you explain this change to Maya, without jargon:

"Before, the price code knew every watcher by name — the display, the alert, the log — and every new watcher meant editing the price code. Now the price code just announces: the price changed, here it is. Whoever is listening hears it, in the order they signed up, and a new watcher signs up without anyone touching the price code. One broken watcher cannot silence the rest, and one that leaves mid-day cannot break the announcement for the ones that stay. The one trade-off: the announcement is a promise to deliver, not a promise to be fast — a slow watcher holds everyone behind it, so slow work happens on the watcher's own time, not during the announcement."

If she understands that paragraph, she understands the design — and she can approve the next change with confidence, because she knows what "announced once, heard by all" guarantees and what it costs.

Field check

Six rules to carry into the rest of the track:

  1. The publisher announces; it never asks who is listening. If the ticker has to name its listeners, it is a method-call list wearing a subscribe API's name.
  2. One bad listener must never silence the rest. Isolate each listener's failure, log it, and keep delivering — the log's missing entry is the failure you will notice last.
  3. Notify a snapshot, not the live list. A listener that subscribes or leaves mid-delivery must not change the delivery in progress.
  4. Delivery order is a contract — write it down. Registration order is the order here; if a listener depends on going first or last, say so where it subscribes.
  5. A listener returns quickly and never calls back into the publisher. Slow work belongs on the listener's own thread, and a price set during an announcement is refused.
  6. No observer without more than one thing caring. One listener is a method call; a fixed list is a loop. A pattern is a tool, not a goal.

Previous in this track: Java Decorator and Proxy Patterns: Add Behavior Without Changing Classes · Continue: Java Strategy and State Patterns: Swap Behavior at Runtime

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

30 Core Java Basic Interview Questions for Freshers