Observer: events and listeners
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Placing a ShopLite order must send an email, reserve stock and record analytics, and more reactions keep arriving. How do you stop placeOrder from calling every one of them?
The problem: one order, many reactions
Observer pattern is a design pattern where one object, the subject, tells a list of other objects, the observers, whenever something happens. The subject does not know who is listening, so reactions can be added without editing it.
When a ShopLite order is placed, an email goes out, stock is reserved and analytics records the sale. Here placeOrder calls each of them directly.
Example 1 · Without Observer: the order code calls everyone
class EmailService { void sendConfirmation(String orderId) { System.out.println(" email: confirmation for " + orderId); }}
class InventoryService { void reserveStock(String orderId) { System.out.println(" inventory: stock reserved for " + orderId); }}
class AnalyticsService { void trackSale(String orderId, int amount) { System.out.println(" analytics: sale of Rs " + amount); }}
class OrderService { private final EmailService email = new EmailService(); private final InventoryService inventory = new InventoryService(); private final AnalyticsService analytics = new AnalyticsService();
void placeOrder(String orderId, int amount) { System.out.println("Order " + orderId + " saved"); email.sendConfirmation(orderId); inventory.reserveStock(orderId); analytics.trackSale(orderId, amount); // loyalty points, fraud check, WhatsApp... each one means editing this method }}
public class DirectCallsDemo { public static void main(String[] args) { new OrderService().placeOrder("A101", 1499); }}Order A101 saved email: confirmation for A101 inventory: stock reserved for A101 analytics: sale of Rs 1499
What this code does
OrderServicecreates and calls three unrelated services. It cannot be tested or reused without all of them.- Every new reaction to an order lands in
placeOrder, the most important method in the shop.
OrderService now depends on every reaction. Each new one (loyalty points, a fraud check, a WhatsApp message) means editing the order code, and a slow or broken analytics call can break checkout.
Subject with subscribe, unsubscribe and notify
Subject is the object that owns an event and keeps the list of observers. It offers subscribe and unsubscribe, and when the event happens it notifies each observer by calling one method on it.
OrderService becomes the subject. It knows only a small OrderListener interface, and listeners sign up from outside.
Example 2 · OrderService as a subject with subscribe and unsubscribe
import java.util.ArrayList;import java.util.List;
interface OrderListener { void orderPlaced(String orderId, int amount);}
class OrderService { // the subject private final List<OrderListener> listeners = new ArrayList<>();
void subscribe(OrderListener listener) { listeners.add(listener); }
void unsubscribe(OrderListener listener) { listeners.remove(listener); }
void placeOrder(String orderId, int amount) { System.out.println("Order " + orderId + " saved"); for (OrderListener listener : listeners) { // notify listener.orderPlaced(orderId, amount); } }}
class EmailListener implements OrderListener { public void orderPlaced(String orderId, int amount) { System.out.println(" email: confirmation for " + orderId); }}
class AnalyticsListener implements OrderListener { public void orderPlaced(String orderId, int amount) { System.out.println(" analytics: sale of Rs " + amount); }}
public class SubjectDemo { public static void main(String[] args) { OrderService orders = new OrderService(); OrderListener analytics = new AnalyticsListener(); orders.subscribe(new EmailListener()); orders.subscribe(analytics); orders.subscribe((orderId, amount) -> System.out.println(" loyalty: +" + amount / 100 + " points")); orders.placeOrder("A101", 1499);
orders.unsubscribe(analytics); // analytics switched off orders.placeOrder("A102", 899); }}Order A101 saved email: confirmation for A101 analytics: sale of Rs 1499 loyalty: +14 points Order A102 saved email: confirmation for A102 loyalty: +8 points
What this code does
OrderServiceonly knows theOrderListenerinterface. Loyalty points were added as a one-line lambda listener, with no change to the order code.- After
unsubscribe, the second order reaches only email and loyalty. Listeners join and leave while the program runs.
An observer (also called a listener or subscriber) is any object that implements that interface, such as EmailListener or InventoryListener. Adding loyalty points is a new listener class plus one subscribe line.
Observers can join and leave while the program runs, so "tell me when this product is back" is just one more subscribe.
Event objects vs pushing raw values
Event object is one small immutable object, usually a record such as OrderPlaced, that carries all the data about something that happened. Each listener reads only the fields it needs.
The subject can push raw values or one event object. Below, an OrderPlaced record carries the order data to every listener.
Example 3 · An OrderPlaced event record instead of raw values
import java.util.ArrayList;import java.util.List;
record OrderPlaced(String orderId, String email, int amount, List<String> skus) {}
interface OrderListener { void onOrderPlaced(OrderPlaced event);}
class OrderService { private final List<OrderListener> listeners = new ArrayList<>();
void subscribe(OrderListener listener) { listeners.add(listener); }
void placeOrder(OrderPlaced event) { System.out.println("Order " + event.orderId() + " saved"); for (OrderListener listener : listeners) { listener.onOrderPlaced(event); } }}
class EmailListener implements OrderListener { public void onOrderPlaced(OrderPlaced e) { System.out.println(" email to " + e.email() + ": order " + e.orderId() + " confirmed"); }}
class InventoryListener implements OrderListener { public void onOrderPlaced(OrderPlaced e) { System.out.println(" inventory: reserve " + e.skus()); }}
class LoyaltyListener implements OrderListener { public void onOrderPlaced(OrderPlaced e) { System.out.println(" loyalty: +" + e.amount() / 100 + " points"); }}
public class EventObjectDemo { public static void main(String[] args) { OrderService orders = new OrderService(); orders.subscribe(new EmailListener()); orders.subscribe(new InventoryListener()); orders.subscribe(new LoyaltyListener()); orders.placeOrder(new OrderPlaced("A101", "riya@mail.com", 1799, List.of("EAR-01", "PEN-02"))); }}Order A101 saved email to riya@mail.com: order A101 confirmed inventory: reserve [EAR-01, PEN-02] loyalty: +17 points
What this code does
- Each listener reads only what it needs: email uses the address, inventory the SKUs, loyalty the amount.
- Adding a
cityfield toOrderPlacedlater changes no listener method, because the signatureonOrderPlaced(OrderPlaced)stays the same.
With raw values, orderPlaced(orderId, amount) must change whenever one more value is needed, and that breaks every listener. An event record can grow while the method signature stays the same.
Name events in the past tense (OrderPlaced, PaymentFailed): they describe something that already happened.
Find the bug
Spot the event bug
Each snippet has one wrong line. Tap it, then read the fix.
The shop now also wants the SKUs and the city.
Round 1 of 2Pitfalls: exceptions, ordering, modification and leaks
Lapsed listener is a listener that is no longer needed but was never unsubscribed. The subject's list still points to it, so it can never be garbage collected: a memory leak.
Notification is a plain loop, so one failing listener can stop the rest. Below, a plain loop is compared with a safe one, and then a listener leaves during notify.
Example 4 · One failing listener stops the rest, and the fix
import java.util.ArrayList;import java.util.List;
record OrderPlaced(String orderId, String email, int amount, List<String> skus) {}
interface OrderListener { void onOrderPlaced(OrderPlaced event);}
class OrderService { private final List<OrderListener> listeners = new ArrayList<>(); private final boolean safe;
OrderService(boolean safe) { this.safe = safe; }
void subscribe(OrderListener listener) { listeners.add(listener); }
void placeOrder(OrderPlaced event) { for (OrderListener listener : listeners) { if (!safe) { listener.onOrderPlaced(event); // one exception ends the loop continue; } try { listener.onOrderPlaced(event); } catch (RuntimeException e) { System.out.println(" [warn] listener failed: " + e.getMessage()); } } }}
public class ListenerFailureDemo { static void run(OrderService orders) { orders.subscribe(e -> System.out.println(" email sent")); orders.subscribe(e -> { throw new IllegalStateException("analytics server down"); }); orders.subscribe(e -> System.out.println(" stock reserved")); try { orders.placeOrder(new OrderPlaced("A101", "riya@mail.com", 1499, List.of("EAR-01"))); System.out.println(" order placed"); } catch (IllegalStateException e) { System.out.println(" placeOrder failed: " + e.getMessage()); } }
public static void main(String[] args) { System.out.println("Plain loop:"); run(new OrderService(false)); System.out.println("Safe loop:"); run(new OrderService(true)); }}Plain loop: email sent placeOrder failed: analytics server down Safe loop: email sent [warn] listener failed: analytics server down stock reserved order placed
What this code does
- In the plain loop, the analytics failure jumps out of
placeOrder: stock is never reserved and checkout reports a failure caused by a reporting tool. - The safe loop catches each listener's exception, logs it and moves on, so email and stock still happen and the order succeeds.
Example 5 · Unsubscribing during notify: ArrayList vs CopyOnWriteArrayList
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;
interface OrderListener { void onOrderPlaced(String orderId);}
class OrderService { private final List<OrderListener> listeners;
OrderService(List<OrderListener> listeners) { this.listeners = listeners; }
void subscribe(OrderListener l) { listeners.add(l); } void unsubscribe(OrderListener l) { listeners.remove(l); }
void placeOrder(String orderId) { for (OrderListener l : listeners) { l.onOrderPlaced(orderId); } }}
class WelcomeCoupon implements OrderListener { // only for the first order private final OrderService orders;
WelcomeCoupon(OrderService orders) { this.orders = orders; }
public void onOrderPlaced(String orderId) { System.out.println(" welcome coupon sent for " + orderId); orders.unsubscribe(this); // leaves while the subject loops }}
public class ModifyWhileNotifyDemo { static void run(OrderService orders) { orders.subscribe(new WelcomeCoupon(orders)); orders.subscribe(id -> System.out.println(" email for " + id)); orders.subscribe(id -> System.out.println(" stock for " + id)); try { orders.placeOrder("A101"); orders.placeOrder("A102"); } catch (ConcurrentModificationException e) { System.out.println(" ConcurrentModificationException"); } }
public static void main(String[] args) { System.out.println("ArrayList:"); run(new OrderService(new ArrayList<>())); System.out.println("CopyOnWriteArrayList:"); run(new OrderService(new CopyOnWriteArrayList<>())); }}ArrayList: welcome coupon sent for A101 ConcurrentModificationException CopyOnWriteArrayList: welcome coupon sent for A101 email for A101 stock for A101 email for A102 stock for A102
What this code does
- With
ArrayList, removing the coupon listener in the middle of theforloop breaks the loop's iterator: the next step throws, so A101 gets no email or stock and A102 is never placed. CopyOnWriteArrayListgives the loop a snapshot. The coupon leaves safely, A101 still gets email and stock, and A102 gets no coupon. It suits listener lists, which are read far more often than changed.
Wrap each call in try/catch, log the failure and carry on. Do not rely on the order in which listeners run either; if one listener needs another's result, make it an explicit step.
A CopyOnWriteArrayList loops over a snapshot, so a listener can unsubscribe safely while the subject is notifying. A listener that is never unsubscribed, such as a page that was closed, stays alive in the subject's list.
Predict the output
Predict the failing listener
Read the code, then pick what it prints.
The second listener throws an exception.
Listeners in the JDK and Spring application events
PropertyChangeSupport is a JDK helper class that works as a ready-made subject. It stores PropertyChangeListeners and fires a PropertyChangeEvent with the old and new value when a property changes.
The JDK ships a ready-made subject, PropertyChangeSupport. Below, it announces a price drop. Spring offers the same idea for whole applications.
@Servicepublic class OrderService { private final ApplicationEventPublisher events; // injected by Spring public OrderService(ApplicationEventPublisher events) { this.events = events; }
public void placeOrder(String orderId, int amount) { events.publishEvent(new OrderPlacedEvent(orderId, amount)); // after saving the order }}
@Componentclass LoyaltyListener { @EventListener void on(OrderPlacedEvent e) { /* add e.amount() / 100 points */ }}Example 6 · PropertyChangeSupport: a price-drop alert
import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;
class Product { private final PropertyChangeSupport changes = new PropertyChangeSupport(this); private final String name; private int price;
Product(String name, int price) { this.name = name; this.price = price; }
void addListener(PropertyChangeListener listener) { changes.addPropertyChangeListener(listener); }
void setPrice(int newPrice) { int old = price; price = newPrice; changes.firePropertyChange("price", old, newPrice); // skipped if old == new }
String name() { return name; }}
public class PriceWatchDemo { public static void main(String[] args) { Product watch = new Product("Smart watch", 2999);
watch.addListener(e -> System.out.println(" audit: " + e.getPropertyName() + " " + e.getOldValue() + " -> " + e.getNewValue())); watch.addListener(e -> { if ((int) e.getNewValue() < (int) e.getOldValue()) { System.out.println(" wishlist alert: price drop to Rs " + e.getNewValue()); } });
System.out.println("Sale starts:"); watch.setPrice(2499); System.out.println("Same price saved again:"); watch.setPrice(2499); System.out.println("Sale ends:"); watch.setPrice(2799); }}Sale starts: audit: price 2999 -> 2499 wishlist alert: price drop to Rs 2499 Same price saved again: Sale ends: audit: price 2499 -> 2799
What this code does
PropertyChangeSupportis a ready-made subject: it keeps the listener list and builds aPropertyChangeEventwith the property name, old value and new value.- Saving the same price again fires nothing, because
firePropertyChangeskips equal values. Only the first change is a drop, so the wishlist alert prints once.
In Spring, a service calls publishEvent(event) with an event object, here a record OrderPlacedEvent(String orderId, int amount). Any bean method annotated with @EventListener for that type is called.
By default the listeners run on the same thread, one after another, so a slow or failing listener still affects the publisher.
Next step
Check your understanding
12 quick questions