00:00

Observer Design Pattern in Java

Last updated:

The observer design pattern in Java lets one object, the subject, notify a list of other objects, the observers, whenever something about it changes. Observers register and unregister themselves at runtime, and the subject never needs to know what they do with the news.

It matters because "when X happens, also do Y" requests keep growing. An order is placed, and inventory, email, loyalty and analytics all want to react. If the order service calls each of them directly, it becomes the place where every team's change lands, and one failing call can break the whole flow. Observer is a behavioral design pattern, and it is the foundation of event listeners, Spring application events and reactive streams.

1. What Is the Observer Design Pattern?

The GoF intent is: "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

The subject keeps a list of observers typed by a small interface, often with one method such as onPriceChange(). It offers subscribe() and unsubscribe() methods. When its state changes, it loops over the list and calls that method on each observer, passing the details of the change (the push model) or just a reference to itself so observers can read what they need (the pull model).

The subject depends only on the observer interface, never on concrete observers. That is loose coupling in its purest form: new reactions are added by writing a new observer and subscribing it, with no change to the subject (Open/Closed Principle), and each observer has one job (Single Responsibility Principle).

2. Key Components

ComponentResponsibilityIn the Basic Example
SubjectHolds state and the observer list; notifies on changeWatchedProduct
ObserverInterface with the notification methodPriceWatcher
Concrete ObserversReact to notifications in their own wayEmailAlert, PushAlert, PriceHistoryLog
ClientCreates observers and subscribes themmain

The client wires observers to the subject. After that, the subject and the observers talk only through the observer interface: the subject calls, each observer reacts, and observers can unsubscribe at any time, even from inside a notification.

3. When Is Observer Useful?

  • Watchlists: shoppers who want an alert when a product's price drops.
  • Domain events: several modules that react to "order placed" or "order cancelled".
  • Streams of updates: a feed of bank transactions consumed by a fraud monitor and a balance projection at their own pace.

4. UML Class Diagram

The diagram shows the Basic Example.

Observer UML class diagram WatchedProduct holds zero or more PriceWatcher observers and notifies them. EmailAlert, PushAlert and PriceHistoryLog implement PriceWatcher. subject WatchedProduct - watchers: List<PriceWatcher> - price: BigDecimal + subscribe(watcher) + unsubscribe(watcher) + changePrice(newPrice) - notifyWatchers(old, new) notifies 0..* «interface» PriceWatcher + onPriceChange(product, old, new) implements EmailAlert PushAlert PriceHistoryLog
Observer: the subject holds a list of PriceWatcher references and calls each one when the price changes.
  1. WatchedProduct (subject) holds zero or more PriceWatchers.
  2. The association points at the interface, not at concrete observers, so the subject compiles without knowing about email or push.
  3. Three concrete observers implement the interface (dashed line, hollow triangle).
  4. notifyWatchers() is private: only the subject decides when to notify.

5. Step-by-Step Execution Flow

  1. The client creates the product and three observers, and calls subscribe() for each.
  2. The client calls changePrice("6299").
  3. The subject stores the old price, updates its state, and calls notifyWatchers(old, new).
  4. The loop calls onPriceChange() on each observer in subscription order.
  5. EmailAlert sees the price is at or below its target, sends the email and unsubscribes itself.
  6. PushAlert and PriceHistoryLog react independently. Control returns to the subject, then to the client.

By default this is all synchronous: changePrice() returns only after every observer has finished.

6. Real-World Use Cases

  • E-commerce: price alerts, back-in-stock notifications and "order placed" handlers.
  • Payments and banking: payment status changes fanned out to ledgers, receipts and fraud scoring.
  • Notifications: one event triggering email, SMS and push senders that subscribe independently.
  • The JDK: Swing and AWT listeners such as ActionListener, java.beans.PropertyChangeSupport with PropertyChangeListener, and java.util.concurrent.Flow (Java 9+) for asynchronous streams with backpressure. The old java.util.Observer and Observable have been deprecated since Java 9.
  • Spring: ApplicationEventPublisher publishes events and @EventListener methods observe them. Listeners run synchronously on the publishing thread unless you add @Async or configure an executor, and @TransactionalEventListener can delay a listener until the transaction commits.

7. Problem Without the Pattern

An order service that calls every interested module itself:

OrderServiceWithoutObserver.java
public class OrderServiceWithoutObserver {

    static final class EmailService { void sendConfirmation(String orderId) { System.out.println("  email: confirmation for " + orderId); } }
    static final class InventoryService { void reserve(String orderId) { System.out.println("  inventory: reserved items for " + orderId); } }
    static final class LoyaltyService { void addPoints(String orderId) { throw new IllegalStateException("loyalty service is down"); } }
    static final class AnalyticsService { void track(String orderId) { System.out.println("  analytics: tracked " + orderId); } }

    // The order service knows, creates and calls every interested party itself
    static final class OrderService {
        private final EmailService email = new EmailService();
        private final InventoryService inventory = new InventoryService();
        private final LoyaltyService loyalty = new LoyaltyService();
        private final AnalyticsService analytics = new AnalyticsService();

        void placeOrder(String orderId) {
            System.out.println("Order " + orderId + " placed");
            inventory.reserve(orderId);
            email.sendConfirmation(orderId);
            loyalty.addPoints(orderId);          // throws, so analytics never runs
            analytics.track(orderId);
        }
    }

    public static void main(String[] args) {
        try {
            new OrderService().placeOrder("ORD-501");
        } catch (IllegalStateException e) {
            System.out.println("Order flow aborted: " + e.getMessage());
        }
    }
}
Console
Order ORD-501 placed
  inventory: reserved items for ORD-501
  email: confirmation for ORD-501
Order flow aborted: loyalty service is down
  • Tight coupling: the order service depends on four unrelated modules.
  • Every change lands here: adding SMS or removing analytics means editing and redeploying the order service.
  • Cascading failure: the loyalty outage stops analytics from running, and aborts the whole flow.
  • Hard to test: testing order placement needs all four services or their mocks.

8. Solution Using the Pattern

Let the order service publish an OrderPlaced event and let each module subscribe its own listener. The service knows nothing about who is listening.

New reactions are new subscribers; the order service never changes. The event bus catches each listener's exception, so a loyalty outage is logged and the other listeners still run. Tests for the order service only check that the right event was published. The Practical Example builds exactly this design.

9. Observer Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Price-Drop Alerts

Problem: shoppers watch a product. One wants an email once the price reaches a target, the app shows a push message on every drop, and analytics keeps a price history.

PriceDropAlertDemo.java
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class PriceDropAlertDemo {

    // Observer
    interface PriceWatcher {
        void onPriceChange(WatchedProduct product, BigDecimal oldPrice, BigDecimal newPrice);
    }

    // Subject
    static final class WatchedProduct {
        private final String name;
        private BigDecimal price;
        private final List<PriceWatcher> watchers = new CopyOnWriteArrayList<>();   // safe if a watcher unsubscribes mid-loop

        WatchedProduct(String name, String price) {
            this.name = name;
            this.price = new BigDecimal(price);
        }

        void subscribe(PriceWatcher watcher) { watchers.add(watcher); }
        void unsubscribe(PriceWatcher watcher) { watchers.remove(watcher); }
        String name() { return name; }

        void changePrice(String newPrice) {
            BigDecimal old = price;
            price = new BigDecimal(newPrice);
            System.out.println(name + ": " + old + " -> " + price);
            notifyWatchers(old, price);
        }

        private void notifyWatchers(BigDecimal oldPrice, BigDecimal newPrice) {
            for (PriceWatcher watcher : watchers) {
                watcher.onPriceChange(this, oldPrice, newPrice);
            }
        }
    }

    // Concrete observers
    static final class EmailAlert implements PriceWatcher {
        private final String email;
        private final BigDecimal targetPrice;

        EmailAlert(String email, String targetPrice) {
            this.email = email;
            this.targetPrice = new BigDecimal(targetPrice);
        }

        public void onPriceChange(WatchedProduct product, BigDecimal oldPrice, BigDecimal newPrice) {
            if (newPrice.compareTo(targetPrice) <= 0) {
                System.out.println("  [email] " + email + ": " + product.name() + " is now Rs. " + newPrice);
                product.unsubscribe(this);                  // one-time alert
            }
        }
    }

    static final class PushAlert implements PriceWatcher {
        public void onPriceChange(WatchedProduct product, BigDecimal oldPrice, BigDecimal newPrice) {
            if (newPrice.compareTo(oldPrice) < 0) {
                BigDecimal drop = oldPrice.subtract(newPrice);
                System.out.println("  [push] price drop of Rs. " + drop + " on " + product.name());
            }
        }
    }

    static final class PriceHistoryLog implements PriceWatcher {
        private final List<BigDecimal> history = new CopyOnWriteArrayList<>();

        public void onPriceChange(WatchedProduct product, BigDecimal oldPrice, BigDecimal newPrice) {
            history.add(newPrice);
        }

        List<BigDecimal> history() { return List.copyOf(history); }
    }

    public static void main(String[] args) {
        WatchedProduct headphones = new WatchedProduct("Wireless headphones", "7999");
        PriceHistoryLog log = new PriceHistoryLog();
        headphones.subscribe(new EmailAlert("asha@example.com", "6500"));
        headphones.subscribe(new PushAlert());
        headphones.subscribe(log);

        headphones.changePrice("7499");
        headphones.changePrice("6299");     // email target reached; the email alert unsubscribes itself
        headphones.changePrice("6799");
        headphones.changePrice("5999");     // no second email: Asha's alert is gone
        System.out.println("History: " + log.history());
    }
}

Important classes and methods

  • WatchedProduct is the subject; PriceWatcher is the observer interface.
  • The observer list is a CopyOnWriteArrayList, so EmailAlert can unsubscribe itself during the loop without a ConcurrentModificationException.
  • Notifications push the old and new price, and the product itself for pull-style access.

Expected output

Console
Wireless headphones: 7999 -> 7499
  [push] price drop of Rs. 500 on Wireless headphones
Wireless headphones: 7499 -> 6299
  [email] asha@example.com: Wireless headphones is now Rs. 6299
  [push] price drop of Rs. 1200 on Wireless headphones
Wireless headphones: 6299 -> 6799
Wireless headphones: 6799 -> 5999
  [push] price drop of Rs. 800 on Wireless headphones
History: [7499, 6299, 6799, 5999]

How it runs

  1. The first drop triggers only the push alert; 7499 is above the email target.
  2. At 6299 the email goes out once and its observer removes itself.
  3. The rise to 6799 triggers nothing but the history log.
  4. The final drop sends a push but no second email.

10. Best Practices and Common Mistakes

Best practices

  • Keep observer methods fast; move slow work to an executor or a queue.
  • Pass immutable event objects, such as records, so observers cannot change what others see.
  • Return a subscription handle and always unsubscribe when an observer's lifetime ends.
  • Thread safety: use CopyOnWriteArrayList for listener lists that are read far more often than changed, and decide whether observers may be called on another thread.

Common mistakes

  • Lapsed listeners: forgotten subscriptions keep observers alive and leak memory.
  • Unhandled exceptions that stop the remaining observers.
  • Relying on notification order between independent observers.
  • Overengineering: an event bus for a single, fixed collaborator that a direct method call handles clearly.

11. When to Use and When Not to Use

Use it when the set of interested parties changes over time or across deployments, when the subject should not depend on its consumers, or when consumers live in other modules owned by other teams.

Avoid it when the flow must be strictly ordered and transactional across all steps, when there is exactly one consumer that will never change, or when hidden indirect calls would make an already complex flow impossible to follow.

12. Advantages and Disadvantages

Advantages

  • Loose coupling between producers and consumers.
  • Open/Closed: new reactions without touching the subject.
  • Runtime flexibility: subscribe and unsubscribe at any time.
  • Natural fit for UIs, events and streams.

Disadvantages

  • Hidden control flow: it is hard to see who reacts to what.
  • Unspecified order and possible cascades of updates.
  • Memory leaks from listeners that are never removed.

13. Comparison with Similar Patterns

AspectObserverPublish-Subscribe (broker)MediatorChain of Responsibility
Who knows whomSubject holds observer referencesNeither side knows the other; a broker sits betweenColleagues know only the mediatorEach handler knows the next
ReceiversAll subscribersAll subscribers of a topicChosen by the mediatorUsually one handler, or each in turn
ScopeUsually one processAcross processes and servicesOne processOne process
DeliveryTypically synchronousAsynchronous and often durableSynchronousSynchronous

Choose Observer for in-process notifications to a changing set of listeners. Choose publish-subscribe through Kafka or RabbitMQ when consumers are other services and events must survive restarts. Choose a Mediator when the coordination logic itself is complex, and a Chain of Responsibility when one request should be handled by the first suitable handler. See the Apache Kafka tutorial for the distributed version.

14. Summary

  • The observer design pattern in Java lets a subject notify any number of observers when its state changes.
  • Purpose: decouple the source of a change from the code that reacts to it.
  • Components: Subject, Observer interface, Concrete Observers, Client.
  • The subject keeps a list and calls each observer; observers subscribe and unsubscribe at runtime.
  • Used for alerts, domain events, Swing listeners, Spring application events and Flow streams.
  • Benefits: loose coupling and easy extension.
  • Isolate failures, keep observers fast, remove listeners you no longer need, and avoid the deprecated java.util.Observable.

15. Java Design Pattern Interview Questions and Answers

Q1. Why were java.util.Observer and Observable deprecated in Java 9?

The JDK documentation explains that their event model is quite limited, the order of notifications is unspecified, and state changes are not in one-to-one correspondence with notifications. Observable is also a class, so your subject must extend it, and it is not serializable. The suggested replacements are java.beans listeners for property changes and java.util.concurrent.Flow for reliable, ordered messaging between threads.

Q2. A screen component subscribes to a price feed but is never garbage-collected after it closes. Why?

This is the lapsed listener problem: the subject's list still holds a strong reference to the observer, so it stays reachable. Unsubscribe when the observer's lifetime ends, ideally through a handle that fits try-with-resources or a lifecycle hook. Weak references are an alternative, but they make removal timing unpredictable.

try (AutoCloseable subscription = bus.subscribe(PriceChanged.class, screen::refresh)) {
    screen.showUntilClosed();
}   // unsubscribed here, even if an exception was thrown
Q3. A Spring @EventListener sends a confirmation email, but sometimes the order transaction rolls back afterwards. How do you fix it?

A plain @EventListener runs immediately, inside the publisher's transaction, so the email can go out for an order that is later rolled back. Use @TransactionalEventListener, whose default phase is AFTER_COMMIT, so the listener runs only once the order is safely stored. For delivery that must survive crashes, write the event to an outbox table in the same transaction.

Q4. What is the difference between the push and pull models of Observer?

In the push model, the subject sends the changed data with the notification, such as old and new price, which is simple and avoids extra calls. In the pull model, the subject sends only a reference to itself, and observers read what they need, which suits observers that need different data. Many designs mix both: push a small event and let observers pull more if required.

Q5. How does an in-process Observer differ from publishing an event to Kafka?

In-process observers live in the same JVM, are usually called synchronously, and lose undelivered events if the process crashes. Kafka stores events durably and lets consumers in other services read them later, at their own pace, and replay them. In-process observers suit module boundaries inside one service; a broker suits communication between services.