Observer Design Pattern in Java
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
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Subject | Holds state and the observer list; notifies on change | WatchedProduct |
| Observer | Interface with the notification method | PriceWatcher |
| Concrete Observers | React to notifications in their own way | EmailAlert, PushAlert, PriceHistoryLog |
| Client | Creates observers and subscribes them | main |
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.
PriceWatcher references and calls each one when the price changes.WatchedProduct(subject) holds zero or morePriceWatchers.- The association points at the interface, not at concrete observers, so the subject compiles without knowing about email or push.
- Three concrete observers implement the interface (dashed line, hollow triangle).
notifyWatchers()is private: only the subject decides when to notify.
5. Step-by-Step Execution Flow
- The client creates the product and three observers, and calls
subscribe()for each. - The client calls
changePrice("6299"). - The subject stores the old price, updates its state, and calls
notifyWatchers(old, new). - The loop calls
onPriceChange()on each observer in subscription order. EmailAlertsees the price is at or below its target, sends the email and unsubscribes itself.PushAlertandPriceHistoryLogreact 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.PropertyChangeSupportwithPropertyChangeListener, andjava.util.concurrent.Flow(Java 9+) for asynchronous streams with backpressure. The oldjava.util.ObserverandObservablehave been deprecated since Java 9. - Spring:
ApplicationEventPublisherpublishes events and@EventListenermethods observe them. Listeners run synchronously on the publishing thread unless you add@Asyncor configure an executor, and@TransactionalEventListenercan delay a listener until the transaction commits.
7. Problem Without the Pattern
An order service that calls every interested module itself:
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());
}
}
}
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.
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
WatchedProductis the subject;PriceWatcheris the observer interface.- The observer list is a
CopyOnWriteArrayList, soEmailAlertcan unsubscribe itself during the loop without aConcurrentModificationException. - Notifications push the old and new price, and the product itself for pull-style access.
Expected output
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
- The first drop triggers only the push alert; 7499 is above the email target.
- At 6299 the email goes out once and its observer removes itself.
- The rise to 6799 triggers nothing but the history log.
- The final drop sends a push but no second email.
Practical Example: Typed Order Event Bus
Problem: fix section 7. Modules subscribe to the order events they care about, failures stay isolated, and a module can stop listening at runtime.
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
public class OrderEventBusDemo {
// Events
sealed interface OrderEvent permits OrderPlaced, OrderCancelled { String orderId(); }
record OrderPlaced(String orderId, String customerEmail, long amountInPaise) implements OrderEvent { }
record OrderCancelled(String orderId, String reason) implements OrderEvent { }
// A small typed event bus: the subject for many event types
static final class EventBus {
private final Map<Class<?>, List<Consumer<Object>>> listeners = new ConcurrentHashMap<>();
<E> AutoCloseable subscribe(Class<E> type, Consumer<? super E> listener) {
Consumer<Object> wrapper = event -> listener.accept(type.cast(event));
listeners.computeIfAbsent(type, t -> new CopyOnWriteArrayList<>()).add(wrapper);
return () -> listeners.get(type).remove(wrapper); // closing the handle unsubscribes
}
void publish(Object event) {
for (Consumer<Object> listener : listeners.getOrDefault(event.getClass(), List.of())) {
try {
listener.accept(event);
} catch (RuntimeException e) { // one broken listener must not stop the others
System.out.println(" [bus] listener failed: " + e.getMessage());
}
}
}
}
// The publisher only knows the bus, not who listens
static final class OrderService {
private final EventBus bus;
OrderService(EventBus bus) { this.bus = bus; }
void placeOrder(String orderId, String email, long amountInPaise) {
System.out.println("Order " + orderId + " placed");
bus.publish(new OrderPlaced(orderId, email, amountInPaise));
}
void cancelOrder(String orderId, String reason) {
System.out.println("Order " + orderId + " cancelled");
bus.publish(new OrderCancelled(orderId, reason));
}
}
public static void main(String[] args) throws Exception {
EventBus bus = new EventBus();
bus.subscribe(OrderPlaced.class, e -> System.out.println(" [inventory] reserve items for " + e.orderId()));
bus.subscribe(OrderPlaced.class, e -> System.out.println(" [email] confirmation to " + e.customerEmail()));
bus.subscribe(OrderPlaced.class, e -> { throw new IllegalStateException("loyalty service is down"); });
AutoCloseable analytics = bus.subscribe(OrderPlaced.class,
e -> System.out.println(" [analytics] revenue +" + e.amountInPaise() / 100));
bus.subscribe(OrderCancelled.class, e -> System.out.println(" [inventory] release items for " + e.orderId() + " (" + e.reason() + ")"));
OrderService orders = new OrderService(bus);
orders.placeOrder("ORD-501", "asha@example.com", 249_900);
orders.cancelOrder("ORD-501", "customer request");
analytics.close(); // analytics stops listening
orders.placeOrder("ORD-502", "ravi@example.com", 64_000);
}
}
Important classes and methods
EventBusis a general subject: it keeps a listener list per event class.subscribe()returns anAutoCloseablehandle; closing it unsubscribes, which makes cleanup explicit.publish()catches each listener's exception, so one failure does not stop the others.- Events are records inside a sealed interface: immutable, so all listeners see the same data.
Expected output
Order ORD-501 placed
[inventory] reserve items for ORD-501
[email] confirmation to asha@example.com
[bus] listener failed: loyalty service is down
[analytics] revenue +2499
Order ORD-501 cancelled
[inventory] release items for ORD-501 (customer request)
Order ORD-502 placed
[inventory] reserve items for ORD-502
[email] confirmation to ravi@example.com
[bus] listener failed: loyalty service is down
How it runs
- For ORD-501, the loyalty listener fails, but analytics still runs after it.
- The cancellation reaches only the
OrderCancelledlistener. - After
analytics.close(), ORD-502 is no longer tracked.
Real-World Enterprise Example: Transaction Feed with java.util.concurrent.Flow
Problem: a bank streams transactions to several consumers. Notification must be asynchronous so the producer is not slowed down, and slow consumers need backpressure instead of unlimited queues.
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Flow;
import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.TimeUnit;
public class TransactionFeedDemo {
record Transaction(String id, String account, long amountInRupees) { }
// Base subscriber: requests one item at a time (backpressure) and records when the stream ends
abstract static class OneAtATimeSubscriber implements Flow.Subscriber<Transaction> {
private final CountDownLatch done;
private Flow.Subscription subscription;
OneAtATimeSubscriber(CountDownLatch done) { this.done = done; }
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(1); // ask for the first item only
}
@Override
public void onNext(Transaction tx) {
handle(tx);
subscription.request(1); // ready for the next one
}
@Override
public void onError(Throwable error) { done.countDown(); }
@Override
public void onComplete() { done.countDown(); }
abstract void handle(Transaction tx);
}
// Observer 1: flags large transactions
static final class FraudMonitor extends OneAtATimeSubscriber {
final List<String> alerts = new ArrayList<>(); // touched by one delivery thread at a time
FraudMonitor(CountDownLatch done) { super(done); }
void handle(Transaction tx) {
if (tx.amountInRupees() >= 100_000) alerts.add(tx.id() + " on " + tx.account() + " (Rs. " + tx.amountInRupees() + ")");
}
}
// Observer 2: keeps a running balance per account
static final class BalanceProjection extends OneAtATimeSubscriber {
final TreeMap<String, Long> balances = new TreeMap<>(); // sorted by account for stable output
BalanceProjection(CountDownLatch done) { super(done); }
void handle(Transaction tx) { balances.merge(tx.account(), tx.amountInRupees(), Long::sum); }
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch done = new CountDownLatch(2);
FraudMonitor fraud = new FraudMonitor(done);
BalanceProjection balances = new BalanceProjection(done);
try (SubmissionPublisher<Transaction> feed = new SubmissionPublisher<>()) {
feed.subscribe(fraud);
feed.subscribe(balances);
System.out.println("Subscribers: " + feed.getNumberOfSubscribers());
List<Transaction> txs = List.of(
new Transaction("TX-1", "ACC-A", 12_000),
new Transaction("TX-2", "ACC-B", 150_000),
new Transaction("TX-3", "ACC-A", -2_500),
new Transaction("TX-4", "ACC-C", 99_999),
new Transaction("TX-5", "ACC-B", -40_000));
txs.forEach(feed::submit); // blocks only if a subscriber's buffer is full
} // close() signals onComplete to every subscriber
boolean finished = done.await(5, TimeUnit.SECONDS);
System.out.println("Both subscribers completed: " + finished);
System.out.println("Fraud alerts: " + fraud.alerts);
System.out.println("Balances: " + balances.balances);
}
}
Important classes and methods
SubmissionPublisher(Java 9+) is the subject. It delivers items to each subscriber asynchronously, by default onForkJoinPool.commonPool(), with a per-subscriber buffer of 256 items.- Each subscriber calls
request(1), asking for one more item only when it is ready. That is backpressure:submit()blocks if a subscriber's buffer is full. - Closing the publisher calls
onComplete()on every subscriber; theCountDownLatchwaits for both. - Each subscriber receives items one after another, never concurrently, so its plain list and map are safe.
Expected output
Subscribers: 2
Both subscribers completed: true
Fraud alerts: [TX-2 on ACC-B (Rs. 150000)]
Balances: {ACC-A=9500, ACC-B=110000, ACC-C=99999}
How it runs
- Both subscribers register, and five transactions are submitted.
- Deliveries run in the background; the two subscribers progress independently.
- After completion, the fraud monitor has flagged the one transaction of at least Rs. 100,000, and the projection has summed each account.
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
CopyOnWriteArrayListfor 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
| Aspect | Observer | Publish-Subscribe (broker) | Mediator | Chain of Responsibility |
|---|---|---|---|---|
| Who knows whom | Subject holds observer references | Neither side knows the other; a broker sits between | Colleagues know only the mediator | Each handler knows the next |
| Receivers | All subscribers | All subscribers of a topic | Chosen by the mediator | Usually one handler, or each in turn |
| Scope | Usually one process | Across processes and services | One process | One process |
| Delivery | Typically synchronous | Asynchronous and often durable | Synchronous | Synchronous |
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 thrownQ3. 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.