Skip to lesson

Practice: order notification events

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

When a ShopLite order is placed, shipped or cancelled, email, SMS and stock must all react. Calling each one from the order code ties them together, and one failure can break the rest. This checkpoint reviews the event publisher fix.

Event classes: OrderPlaced, OrderShipped and OrderCancelled

An event is a small, unchangeable record of something that already happened, named in the past tense: OrderPlaced, OrderShipped, OrderCancelled.

Each event carries only the data listeners need, such as the order id, the customer and the SKUs (product codes).

Example 1 · Typed events under a sealed interface

OrderEventsDemo.javaJava
import java.util.List;
sealed interface OrderEvent permits OrderPlaced, OrderShipped, OrderCancelled {    String orderId();}
record OrderPlaced(String orderId, String customer, List<String> skus) implements OrderEvent { }
record OrderShipped(String orderId, String courier, String trackingId) implements OrderEvent { }
record OrderCancelled(String orderId, String reason, List<String> skus) implements OrderEvent { }
public class OrderEventsDemo {    static String describe(OrderEvent event) {        if (event instanceof OrderPlaced p) return p.customer() + " placed " + p.orderId() + " with " + p.skus().size() + " items";        if (event instanceof OrderShipped s) return s.orderId() + " shipped via " + s.courier();        if (event instanceof OrderCancelled c) return c.orderId() + " cancelled: " + c.reason();        throw new IllegalArgumentException("Unknown event");    }
    public static void main(String[] args) {        List<OrderEvent> history = List.of(                new OrderPlaced("SL-1001", "Asha", List.of("TSHIRT", "MUG")),                new OrderShipped("SL-1001", "Delhivery", "DL778899"),                new OrderCancelled("SL-1002", "customer changed mind", List.of("CAP")));        history.forEach(e -> System.out.println(describe(e)));        System.out.println(history.get(0));    }}
Output
Asha placed SL-1001 with 2 items
SL-1001 shipped via Delhivery
SL-1002 cancelled: customer changed mind
OrderPlaced[orderId=SL-1001, customer=Asha, skus=[TSHIRT, MUG]]

What this code does

  • Each event is a record named in the past tense, holding only what listeners need. Records also give a readable toString, shown on the last line.
  • sealed ... permits lists the three event types; no other class can implement OrderEvent.
  • instanceof with a pattern (event instanceof OrderPlaced p) checks the type and gives a typed variable in one step (Java 16 and later).

Records are a good fit because events never change after they are published. A sealed interface OrderEvent lists exactly which event types exist, so the compiler knows the full set and a reader sees every event in one place.

Event publisher with email, SMS and inventory listeners

An event publisher keeps a list of subscribers and calls each matching one when an event is published.

The publisher is the subject of the Observer pattern, and the listeners are its observers.

Example 2 · One publisher, three listeners

PublisherDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.function.Consumer;
sealed interface OrderEvent permits OrderPlaced, OrderShipped, OrderCancelled {    String orderId();}
record OrderPlaced(String orderId, String customer, List<String> skus) implements OrderEvent { }
record OrderShipped(String orderId, String courier, String trackingId) implements OrderEvent { }
record OrderCancelled(String orderId, String reason, List<String> skus) implements OrderEvent { }
interface Subscription {    void cancel();}
class EventPublisher {    private record Entry(String name, Class<? extends OrderEvent> type, Consumer<OrderEvent> handler) { }
    private final List<Entry> entries = new ArrayList<>();
    <E extends OrderEvent> Subscription subscribe(String name, Class<E> type, Consumer<? super E> handler) {        Entry entry = new Entry(name, type, event -> handler.accept(type.cast(event)));        entries.add(entry);        return () -> entries.remove(entry);    }
    void publish(OrderEvent event) {        System.out.println(event.getClass().getSimpleName() + " " + event.orderId());        for (Entry entry : List.copyOf(entries)) {            if (!entry.type().isInstance(event)) continue;            try {                entry.handler().accept(event);            } catch (RuntimeException ex) {                System.out.println("  [" + entry.name() + " failed: " + ex.getMessage() + ", others continue]");            }        }    }}
class EmailNotifier {    void placed(OrderPlaced e) { System.out.println("  Email to " + e.customer() + ": order " + e.orderId() + " confirmed"); }    void shipped(OrderShipped e) { System.out.println("  Email: " + e.orderId() + " shipped with " + e.courier() + ", track " + e.trackingId()); }}
class SmsNotifier {    void any(OrderEvent e) { System.out.println("  SMS: update on " + e.orderId()); }}
class InventoryUpdater {    private final Map<String, Integer> stock = new TreeMap<>();    InventoryUpdater(Map<String, Integer> start) { stock.putAll(start); }    void placed(OrderPlaced e) { e.skus().forEach(s -> stock.merge(s, -1, Integer::sum)); System.out.println("  Stock now " + stock); }    void cancelled(OrderCancelled e) { e.skus().forEach(s -> stock.merge(s, 1, Integer::sum)); System.out.println("  Stock back to " + stock); }}
public class PublisherDemo {    public static void main(String[] args) {        EventPublisher publisher = new EventPublisher();        EmailNotifier email = new EmailNotifier();        SmsNotifier sms = new SmsNotifier();        InventoryUpdater inventory = new InventoryUpdater(Map.of("TSHIRT", 10, "MUG", 4));
        publisher.subscribe("inventory", OrderPlaced.class, inventory::placed);        publisher.subscribe("inventory", OrderCancelled.class, inventory::cancelled);        publisher.subscribe("email", OrderPlaced.class, email::placed);        publisher.subscribe("email", OrderShipped.class, email::shipped);        publisher.subscribe("sms", OrderEvent.class, sms::any);
        publisher.publish(new OrderPlaced("SL-1001", "Asha", List.of("TSHIRT", "MUG")));        publisher.publish(new OrderShipped("SL-1001", "Delhivery", "DL778899"));        publisher.publish(new OrderCancelled("SL-1002", "out of budget", List.of("TSHIRT")));    }}
Output
OrderPlaced SL-1001
  Stock now {MUG=3, TSHIRT=9}
  Email to Asha: order SL-1001 confirmed
  SMS: update on SL-1001
OrderShipped SL-1001
  Email: SL-1001 shipped with Delhivery, track DL778899
  SMS: update on SL-1001
OrderCancelled SL-1002
  Stock back to {MUG=3, TSHIRT=10}
  SMS: update on SL-1002

What this code does

  • Each listener names the event class it wants, and gets that exact type: email::placed takes an OrderPlaced, no casting needed.
  • SMS subscribes to OrderEvent.class, so isInstance matches every event type and it hears about all three.
  • The order flow only calls publish; it never mentions email, SMS or stock, so a new listener needs no change there.

With typed subscriptions, a listener says which event class it wants, such as OrderPlaced.class, and receives that type directly, with no casting.

ShopLite's listeners: EmailNotifier (placed and shipped), SmsNotifier (every event, by subscribing to OrderEvent.class) and InventoryUpdater (takes stock on placed, returns it on cancelled).

Isolating a failing listener so others still run

Listener isolation means one broken listener cannot stop the others.

If the SMS gateway is down and its listener throws an exception inside a plain loop, the loop ends there, and the inventory listener after it never runs: the order is placed, but stock is never reduced.

One OrderPlaced event to three listeners. In a plain loop, email runs, SMS throws and the loop ends, so inventory never runs. With a try and catch around each call, the SMS failure is logged and inventory still runs.

Example 3 · Bug: a failing SMS listener stops stock updates

FailingListenerDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;
record OrderPlaced(String orderId, List<String> skus) { }
class NaivePublisher {    private final List<Consumer<OrderPlaced>> listeners = new ArrayList<>();    void subscribe(Consumer<OrderPlaced> l) { listeners.add(l); }
    void publish(OrderPlaced event) {        for (Consumer<OrderPlaced> l : listeners) {            l.accept(event);   // one exception ends the whole loop        }    }}
public class FailingListenerDemo {    public static void main(String[] args) {        NaivePublisher publisher = new NaivePublisher();        publisher.subscribe(e -> System.out.println("Email sent for " + e.orderId()));        publisher.subscribe(e -> { throw new IllegalStateException("SMS gateway timeout"); });        publisher.subscribe(e -> System.out.println("Stock reduced for " + e.skus()));
        try {            publisher.publish(new OrderPlaced("SL-1003", List.of("MUG")));        } catch (IllegalStateException ex) {            System.out.println("Publish crashed: " + ex.getMessage());        }        System.out.println("Was stock reduced? No: the third listener never ran.");    }}
Output
Email sent for SL-1003
Publish crashed: SMS gateway timeout
Was stock reduced? No: the third listener never ran.

What this code does

  • The SMS listener throws, the exception leaves the for loop, and the inventory listener after it is skipped.
  • The order still exists, so ShopLite would now sell stock it no longer has. Nothing in the inventory code is wrong; the publisher is.
  • The caller of publish also gets an exception about SMS, which has nothing to do with placing an order.

Example 4 · Fix: the publisher isolates each listener

IsolatedListenerDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.function.Consumer;
sealed interface OrderEvent permits OrderPlaced, OrderShipped, OrderCancelled {    String orderId();}
record OrderPlaced(String orderId, String customer, List<String> skus) implements OrderEvent { }
record OrderShipped(String orderId, String courier, String trackingId) implements OrderEvent { }
record OrderCancelled(String orderId, String reason, List<String> skus) implements OrderEvent { }
interface Subscription {    void cancel();}
class EventPublisher {    private record Entry(String name, Class<? extends OrderEvent> type, Consumer<OrderEvent> handler) { }
    private final List<Entry> entries = new ArrayList<>();
    <E extends OrderEvent> Subscription subscribe(String name, Class<E> type, Consumer<? super E> handler) {        Entry entry = new Entry(name, type, event -> handler.accept(type.cast(event)));        entries.add(entry);        return () -> entries.remove(entry);    }
    void publish(OrderEvent event) {        System.out.println(event.getClass().getSimpleName() + " " + event.orderId());        for (Entry entry : List.copyOf(entries)) {            if (!entry.type().isInstance(event)) continue;            try {                entry.handler().accept(event);            } catch (RuntimeException ex) {                System.out.println("  [" + entry.name() + " failed: " + ex.getMessage() + ", others continue]");            }        }    }}
class EmailNotifier {    void placed(OrderPlaced e) { System.out.println("  Email to " + e.customer() + ": order " + e.orderId() + " confirmed"); }    void shipped(OrderShipped e) { System.out.println("  Email: " + e.orderId() + " shipped with " + e.courier() + ", track " + e.trackingId()); }}
class SmsNotifier {    void any(OrderEvent e) { System.out.println("  SMS: update on " + e.orderId()); }}
class InventoryUpdater {    private final Map<String, Integer> stock = new TreeMap<>();    InventoryUpdater(Map<String, Integer> start) { stock.putAll(start); }    void placed(OrderPlaced e) { e.skus().forEach(s -> stock.merge(s, -1, Integer::sum)); System.out.println("  Stock now " + stock); }    void cancelled(OrderCancelled e) { e.skus().forEach(s -> stock.merge(s, 1, Integer::sum)); System.out.println("  Stock back to " + stock); }}
public class IsolatedListenerDemo {    public static void main(String[] args) {        EventPublisher publisher = new EventPublisher();        InventoryUpdater inventory = new InventoryUpdater(Map.of("MUG", 4));        publisher.subscribe("email", OrderPlaced.class, new EmailNotifier()::placed);        publisher.subscribe("sms", OrderEvent.class, e -> { throw new IllegalStateException("SMS gateway timeout"); });        publisher.subscribe("inventory", OrderPlaced.class, inventory::placed);
        publisher.publish(new OrderPlaced("SL-1003", "Ravi", List.of("MUG")));        System.out.println("publish returned normally");    }}
Output
OrderPlaced SL-1003
  Email to Ravi: order SL-1003 confirmed
  [sms failed: SMS gateway timeout, others continue]
  Stock now {MUG=3}
publish returned normally

What this code does

  • The same failing SMS listener now only produces a log line; email and inventory both run.
  • The try/catch lives once in EventPublisher.publish, so every current and future listener is protected.
  • A real system would also record the failed event for a retry. The point here is that one listener's problem stays its own.

The fix is a try/catch around each listener call inside the publisher, which logs the failure and moves on. The publisher, not every listener, owns this rule, so a new listener cannot forget it.

Find the bug

Find the publisher bug

Each publisher loses an event or hides a failure. Tap the line to fix.

The publish loop.

Round 1 of 2

Unsubscribing and testing listener order

Unsubscribing removes a listener so it gets no more events, for example a "first order" coupon listener that should fire once.

A Subscription handle returned from subscribe makes this easy: call cancel() on it.

Example 5 · Unsubscribe and test the listener order

ListenerOrderDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.function.Consumer;
sealed interface OrderEvent permits OrderPlaced, OrderShipped, OrderCancelled {    String orderId();}
record OrderPlaced(String orderId, String customer, List<String> skus) implements OrderEvent { }
record OrderShipped(String orderId, String courier, String trackingId) implements OrderEvent { }
record OrderCancelled(String orderId, String reason, List<String> skus) implements OrderEvent { }
interface Subscription {    void cancel();}
class EventPublisher {    private record Entry(String name, Class<? extends OrderEvent> type, Consumer<OrderEvent> handler) { }
    private final List<Entry> entries = new ArrayList<>();
    <E extends OrderEvent> Subscription subscribe(String name, Class<E> type, Consumer<? super E> handler) {        Entry entry = new Entry(name, type, event -> handler.accept(type.cast(event)));        entries.add(entry);        return () -> entries.remove(entry);    }
    void publish(OrderEvent event) {        System.out.println(event.getClass().getSimpleName() + " " + event.orderId());        for (Entry entry : List.copyOf(entries)) {            if (!entry.type().isInstance(event)) continue;            try {                entry.handler().accept(event);            } catch (RuntimeException ex) {                System.out.println("  [" + entry.name() + " failed: " + ex.getMessage() + ", others continue]");            }        }    }}
public class ListenerOrderDemo {    public static void main(String[] args) {        EventPublisher publisher = new EventPublisher();        List<String> calls = new ArrayList<>();
        publisher.subscribe("inventory", OrderPlaced.class, e -> calls.add("inventory"));        publisher.subscribe("email", OrderPlaced.class, e -> calls.add("email"));        Subscription coupon = publisher.subscribe("first-order-coupon", OrderPlaced.class, e -> calls.add("coupon"));        publisher.subscribe("sms", OrderEvent.class, e -> calls.add("sms"));
        publisher.publish(new OrderPlaced("SL-2001", "Meera", List.of("CAP")));        List<String> expected = List.of("inventory", "email", "coupon", "sms");        System.out.println("Order " + calls + (calls.equals(expected) ? " PASS" : " FAIL"));
        coupon.cancel();        calls.clear();        publisher.publish(new OrderPlaced("SL-2002", "Meera", List.of("MUG")));        System.out.println("After cancel " + calls + (calls.equals(List.of("inventory", "email", "sms")) ? " PASS" : " FAIL"));    }}
Output
OrderPlaced SL-2001
Order [inventory, email, coupon, sms] PASS
OrderPlaced SL-2002
After cancel [inventory, email, sms] PASS

What this code does

  • Recording listeners turn "who ran, in what order" into a list you can compare with the expected one. This is the shape of a unit test, written with plain main here.
  • subscribe returns a Subscription; calling cancel() removes the coupon listener, and the second event skips it.
  • Inventory was subscribed first, so it runs first. If the order matters, a test like this keeps it from changing by accident.

Listeners run in the order they subscribed, because the publisher keeps them in a list. If order matters (stock before the "order confirmed" email), test it: subscribe recording listeners that add their name to a list, publish one event, and compare the list with the expected order.

Predict the output

Who runs first

Listeners run in the order they subscribed.

What does the list contain after one OrderPlaced event?

List<String> calls = new ArrayList<>();
publisher.subscribe("stock", OrderPlaced.class, e -> calls.add("stock"));
publisher.subscribe("email", OrderPlaced.class, e -> calls.add("email"));
publisher.publish(new OrderPlaced("SL-1", "Ravi", List.of("MUG")));
System.out.println(calls);
The publisher loops over a copy of its list, so a listener that unsubscribes while an event is being delivered does not break the loop.

Finish up

Mark complete & continue

Next: Practice: Builder for complex order objects