Observer

Mid-level Frequently asked 5 min

On this page

The question

How do event listeners work, and what pattern is behind them?

30-second answer

They use Observer. A subject keeps a list of listeners that share one interface, and when something happens it calls each in turn. New listeners need no change to the subject, so the two stay decoupled. In the simple form the calls are synchronous, so publish() returns only after every listener has finished, and a listener's exception reaches the publisher.

Understand it

A subject notifies its listeners

Step by step

Email, Stock and Analytics each register with OrderEvents. It keeps a list of listeners and knows them only by an interface.

Step 1 of 5
View as text

An OrderEvents box on the left joined by arrows to three listener boxes on the right: Email, Stock and Analytics.

Email, Stock and Analytics each register with OrderEvents. It keeps a list of listeners and knows them only by an interface. Dashed arrows appear, and the box reads 3 listeners.

An order is placed, so OrderEvents publishes one OrderPlaced event. Its code does not change when listeners are added. An event appears at the subject.

OrderEvents loops over its list and calls each listener in turn, on the same thread, so publish() returns only after the last one finishes. The event reaches the listeners, numbered 1, 2 and 3 in the order they run.

Analytics unsubscribes, so the next event reaches only Email and Stock. Forgetting this in a long-lived subject leaks memory. Analytics fades, and the box reads 2 listeners.

Email throws an exception. In this plain loop it stops the loop, Stock is never called, and the exception reaches the publisher. Email is marked failed, Stock fades, and a mark reads that the exception reached the publisher.

An OrderEvents box on the left joined by arrows to three listener boxes on the right: Email, Stock and Analytics.

Email, Stock and Analytics each register with OrderEvents. It keeps a list of listeners and knows them only by an interface. Dashed arrows appear, and the box reads 3 listeners.

An order is placed, so OrderEvents publishes one OrderPlaced event. Its code does not change when listeners are added. An event appears at the subject.

OrderEvents loops over its list and calls each listener in turn, on the same thread, so publish() returns only after the last one finishes. The event reaches the listeners, numbered 1, 2 and 3 in the order they run.

Analytics unsubscribes, so the next event reaches only Email and Stock. Forgetting this in a long-lived subject leaks memory. Analytics fades, and the box reads 2 listeners.

Email throws an exception. In this plain loop it stops the loop, Stock is never called, and the exception reaches the publisher. Email is marked failed, Stock fades, and a mark reads that the exception reached the publisher.

Takeaway: A subject calls every registered listener through one interface. It stays decoupled from who listens, but not from how long they take or whether they fail.

In-process observer vs broker pub/sub

Compare

Observer: the subject calls its listeners directly, inside one process. When Stock fails, the publisher sees the exception and the event is gone.

View as text

A publisher on the left and two consumers on the right, Email and Stock, with Stock marked down. Three rows below say where it runs, whether the publisher waits, and what a failure does.

Observer: the subject calls its listeners directly, inside one process. When Stock fails, the publisher sees the exception and the event is gone. The arrows run straight from the publisher to Email and Stock, and a failure arrow returns from Stock. The rows read one process, yes by default, and publisher sees it.

Pub/sub: a broker sits between them, usually across processes. When Stock is down, the publisher never notices, and the event waits for Stock to return. A Topic box stands between the publisher and the consumers. The arrow to Stock is dashed, and the event is held in the topic. The rows read many processes, no, and event waits.

A publisher on the left and two consumers on the right, Email and Stock, with Stock marked down. Three rows below say where it runs, whether the publisher waits, and what a failure does.

Observer: the subject calls its listeners directly, inside one process. When Stock fails, the publisher sees the exception and the event is gone. The arrows run straight from the publisher to Email and Stock, and a failure arrow returns from Stock. The rows read one process, yes by default, and publisher sees it.

Pub/sub: a broker sits between them, usually across processes. When Stock is down, the publisher never notices, and the event waits for Stock to return. A Topic box stands between the publisher and the consumers. The arrow to Stock is dashed, and the event is held in the topic. The rows read many processes, no, and event waits.

Takeaway: Observer decouples code inside one process; pub/sub puts a broker in the middle, which also decouples time, processes and failures, at the price of running a broker.

Observer or pub/subIf all listeners run inside one process and may fail with the operation, use Observer or Spring events. If consumers run in other processes or must not lose events when they are down, use pub/sub with a broker such as Kafka or RabbitMQ.noyesyesnoAll listeners inone process?Pub/subwith a brokerMust an eventsurvivea crash or a failure?Observeror Spring events
Observer or pub/subIf all listeners run inside one process and may fail with the operation, use Observer or Spring events. If consumers run in other processes or must not lose events when they are down, use pub/sub with a broker such as Kafka or RabbitMQ.noyesyesnoAll listeners inone process?Pub/subwith a brokerMust an eventsurvivea crash or a failure?Observeror Spring events
Observer or pub/sub: what must survive a failure?

In code

record OrderPlaced(String orderId) {}
interface OrderListener { void onOrderPlaced(OrderPlaced event); }

class OrderEvents {
    private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();

    void subscribe(OrderListener l) { listeners.add(l); }
    void unsubscribe(OrderListener l) { listeners.remove(l); }

    void publish(OrderPlaced event) {
        for (OrderListener l : listeners) l.onOrderPlaced(event);   // same thread, in order
    }
}

var events = new OrderEvents();
events.subscribe(e -> System.out.println("email " + e.orderId()));
events.subscribe(e -> System.out.println("stock " + e.orderId()));
events.publish(new OrderPlaced("42"));   // email 42, then stock 42
A subject and its listeners
@Service
class OrderService {
    private final ApplicationEventPublisher publisher;

    OrderService(ApplicationEventPublisher publisher) { this.publisher = publisher; }

    void place(String orderId) { publisher.publishEvent(new OrderPlaced(orderId)); }
}

@Component
class EmailListener {
    @EventListener                   // synchronous by default: runs on the caller's thread
    void on(OrderPlaced event) { System.out.println("email " + event.orderId()); }
}
The same thing with Spring events
publish calls each listener in turnThe caller calls publish on OrderEvents. OrderEvents calls Email and waits for it to return, then calls Stock and waits for it to return. Only then does publish return to the caller.publish(event)Email runspublish() waitsStock runspublish() waitspublish() returns
publish calls each listener in turnThe caller calls publish on OrderEvents. OrderEvents calls Email and waits for it to return, then calls Stock and waits for it to return. Only then does publish return to the caller.publish(event)Email runspublish() waitsStock runspublish() waitspublish() returns
publish() calls each listener in turn
private final ExecutorService notifier = Executors.newFixedThreadPool(4);

void publish(OrderPlaced event) {
    for (OrderListener l : listeners) {
        notifier.submit(() -> l.onOrderPlaced(event));   // returns at once; listeners may now run in any order
    }
}
Notify on other threads so a slow listener cannot delay the publisher

Solve it

One failing listener breaks checkout

OrderPlaced has three listeners: stock reservation, a confirmation email and analytics. When the analytics service is down, its listener throws, the stock is never reserved and the customer sees an error. Fix the design.

  1. Trace the call. publish calls each listener in turn on the caller’s thread. The first exception leaves the loop and reaches the checkout request.
  2. Sort the listeners. Stock reservation must succeed for the order to be valid. Email and analytics are best effort and must never fail an order.
  3. Isolate best effort. Call those listeners so that an exception is caught and logged per listener, or run them asynchronously.
  4. Keep essential work direct. Reserve stock as a normal call in the checkout flow, not as a listener whose failure is invisible.
  5. Check. In a test, register a listener that throws: the others still run and publish returns normally.
void publish(OrderPlaced event) {
    for (OrderListener l : listeners) {
        try {
            l.onOrderPlaced(event);
        } catch (RuntimeException e) {
            log.warn("listener {} failed for order {}", l, event.orderId(), e);   // the next one still runs
        }
    }
}

void checkout(Cart cart) {
    Order order = orders.create(cart);
    stock.reserve(order);                          // essential: a direct call that can fail the checkout
    events.publish(new OrderPlaced(order.id()));   // best effort: email, analytics
}
Each best-effort listener fails alone

How to answer

  • The subject depends on an interface, never on concrete listeners.
  • Listeners register and unregister at runtime.
  • By default, notification runs on the publisher's thread.
  • A slow listener slows the publisher, and a failing one can stop the rest.

Common mistakes

  • Assuming listeners run in parallel or in the background by default.
  • Forgetting to unsubscribe, which keeps listeners referenced and leaks memory.

Follow-up questions

What is the difference between Observer and pub/sub?

In Observer, the subject holds its listeners and calls them directly, usually synchronously and in one process. In pub/sub, a broker sits in between: publishers write to a topic and do not know the subscribers, who may be in other processes and may be down. That decouples time and failures too, at the price of running a broker and handling duplicates and eventual consistency.

  • Observer decouples code; pub/sub also decouples time and deployment.
  • Pub/sub keeps an event when a consumer is down, if the broker retains it.
  • Kafka and RabbitMQ are the usual brokers; Spring events are in-process Observer.

See it in the infographic: In-process observer vs broker pub/sub

One listener calls a slow external service, and placing an order got slow. What are your options?

The listener runs on the caller's thread, so the order waits for it. Make that listener asynchronous with @Async or an executor, so the caller returns early; note that its failures no longer reach the caller and a crash loses the event. If the work must not be lost, write it to an outbox or publish to a broker instead.

  • First confirm the listener really is synchronous.
  • An @Async listener needs its own error handling.
  • If it must survive a crash, use a broker or an outbox rather than an in-memory thread pool.

See it in the infographic: A subject notifies its listeners

Why would a subject keep its listeners in a CopyOnWriteArrayList?

A listener might unsubscribe while the subject is looping, or another thread might subscribe. With ArrayList, that throws ConcurrentModificationException or races. CopyOnWriteArrayList iterates over a snapshot and copies on each write, so reads take no lock. That suits listener lists, which are read often and changed rarely.

  • Iteration sees a stable snapshot.
  • Writes are expensive, because each one copies the array.
  • A listener added during a publish misses that event, since the loop uses the old snapshot.

How do Spring events behave by default?

publishEvent calls each @EventListener synchronously on the caller's thread. An exception from a listener propagates to the publisher and stops later listeners. For background handling, add @Async on the listener with @EnableAsync. @TransactionalEventListener waits for the transaction, and by default runs after commit.

Why is java.util.Observable deprecated?

It has been deprecated since Java 9. It is a class, so using it takes your one superclass; it does not say what order listeners run in; and its events carry only an untyped Object. Use PropertyChangeListener, Flow, a small typed listener interface or Spring events instead.

Check yourself

1. A subject loops over Email then Stock with no try/catch, and Email throws an exception. What happens?
Show answers
  • Stock is not called, and the exception reaches the publisher.: Correct. It is a plain loop on the publisher's thread, so the exception leaves the loop.
  • Stock still runs, and the exception is logged.: Incorrect. Nothing catches it, so the loop stops at Email.
  • Email is retried until it succeeds.: Incorrect. A plain Observer has no retry; that is something a broker's consumer can add.
2. The Stock service is down for an hour, and it must still see every order event when it returns. What do you need?
Show answers
  • Pub/sub with a broker that retains events: Correct. The broker keeps events until Stock returns, and the publisher never waits for it.
  • A listener registered with the subject: Incorrect. A listener in another process that is down cannot be called, so the event is lost.
  • An @Async event listener: Incorrect. The event sits in a thread pool's memory and needs the listener's process to be running.