SteelReed

Search

Search posts, questions…

3. Advanced Java

Observer: from a listener list to Spring events and an outbox

Refactor a network manager that calls its subscriber directly into Observer, reproduce four ways a publisher breaks (self-unsubscribing listeners, exceptions, leaks, threads), write a sturdier publisher, then move to Spring: @EventListener, @TransactionalEventListener, and when you need a message broker with an outbox.

18 Nov 20267 min readMid

–

1. The problem

NetworkManager calls DataSyncManager directly and sets its sync strategy itself. Adding an offline banner means editing it. After switching to a listener list, one exception from the banner means the sync manager never learns the network is down; opening and closing 1,000 screens leaves 1,000 listeners in memory.

2. Key idea

Observer inverts the dependency: the publisher (which owns the state) knows only a NetworkListener interface, and whoever cares subscribes. The publisher is like an SMS gateway that only keeps a contact list: if you don't want messages, you unsubscribe, or it keeps texting forever.

The naive version (an ArrayList and a for loop calling each listener) works in a demo but breaks four ways:

Scenario Consequence Fix
A listener unsubscribes while being notified 2 listeners: one silently skipped; 3: ConcurrentModificationException iterate over a snapshot (CopyOnWriteArrayList)
One listener throws listeners after it are never called try/catch per listener
Forgetting to unsubscribe the publisher holds the listener, the listener holds its outer object: a leak subscribe returns an AutoCloseable
Synchronous notify, many threads a slow listener blocks the publisher a single-thread executor if order matters

One more bug: subscribe(this) inside a constructor leaks a half-built object. JDK 21's javac -Xlint:this-escape catches it.

2.1 In Spring: inside the transaction or after commit?

ApplicationEventPublisher is the publisher, @EventListener the subscriber.

Approach Use when Don't use when
@EventListener (same thread, same transaction) work that must succeed with the business operation: auditing a failed email would roll back the booking
@TransactionalEventListener(AFTER_COMMIT) outbound work you can lose: email, cache eviction work that mustn't be lost: an app crash after commit loses it
Broker + transactional outbox other services, durability, retries two classes in the same service talking

Ordering between listeners: trust only @Order. In DDD these are domain events (BookingConfirmed).

3. In Java

JAVA
static final class NetworkMonitor {
    private final List<NetworkListener> listeners = new CopyOnWriteArrayList<>();
    private volatile boolean online;
 
    AutoCloseable subscribe(NetworkListener l) {     // close() unsubscribes
        listeners.add(l);
        l.onChange(online);                          // late joiners get the current state
        return () -> listeners.remove(l);
    }
 
    synchronized void setOnline(boolean value) {
        if (online == value) return;                 // notify only on a real change
        online = value;
        for (NetworkListener l : listeners) {        // iterate over a snapshot
            try { l.onChange(value); }
            catch (RuntimeException e) { log.warn("listener failed", e); }  // don't starve the others
        }
    }
}
// banner throws: sync still sees online=true; 1000 screens with try-with-resources: 2 listeners left
Spring events: AFTER_COMMIT and the dual write
JAVA
@Transactional
public Booking book(BookingRequest request) {
    Booking booking = bookings.save(/* ... */);
    events.publishEvent(new BookingCreated(booking.getId(), request.requestId()));
    return booking;
}
 
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void onBooked(BookingCreated event) { /* runs only if committed */ }
  • An AFTER_COMMIT listener runs in memory after the commit; if the process dies, a deploy replaces it or the listener throws at that moment, the work is lost without a trace. Writing to the DB from it needs REQUIRES_NEW; since Spring 6.1, a plain @Transactional on such a listener is rejected at startup.
  • Dual write: publishing to Kafka inside the transaction creates ghost events when the commit fails; publishing after commit loses events on a crash. The fix is writing the event to an outbox table in the same transaction, a relay pushing it to the broker, and idempotent consumers.
  • Asynchronous notify that keeps order: one newSingleThreadExecutor is a FIFO queue; a multi-thread pool is faster but "offline" can arrive before "online".

4. Working with AI

Delegate to AI: decoupling modules with Spring events, tests for throwing and self-unsubscribing listeners.

Check yourself:

  • The listener list is a CopyOnWriteArrayList or iterated as a copy.
  • Each listener is wrapped in try/catch; one failure doesn't block the rest.
  • Every subscribe has a lifecycle-bound way out (close, @PreDestroy).
  • Work that mustn't be lost isn't in an AFTER_COMMIT listener; there's an outbox.
  • No subscribe(this) in a constructor.

5. Exercises

Exercise 1: Review "send to Kafka when a booking succeeds"

AI wrote @EventListener void onBooked(BookingCreated e) { kafka.send("bookings", e); }, noting "only sent when the booking succeeds". True? Name the failure scenarios and fix it.

Solution to Exercise 1
  • @EventListener runs inside book's transaction. If Kafka accepts the event and the commit then fails (constraint violation, timeout), there's an event for a booking that doesn't exist. If Kafka fails, the exception rolls back the booking.
  • Switching to AFTER_COMMIT isn't enough: an app crash between commit and send loses the event.
  • Fix: write to an outbox in the same transaction, a relay pushes to Kafka; consumers are idempotent on bookingId. Tests: force the commit to fail after publishing and assert no message; kill the relay mid-way and assert the message arrives after restart.

Exercise 2: Asynchronous notify that keeps order

NetworkMonitor notifies synchronously, so a 50 ms listener blocks the thread reporting network changes. AI proposes Executors.newFixedThreadPool(4) for delivery. What's wrong? Propose a way to keep order and deliver everything on shutdown.

Solution to Exercise 2
  • Four threads run in parallel, so order is lost: "offline" can reach a listener before the "online" that happened earlier, and listeners see the wrong state.
  • Use newSingleThreadExecutor: one thread is a FIFO queue, and the publisher returns immediately. On shutdown: shutdown() then awaitTermination(5, SECONDS) so queued events finish.
  • An unbounded queue grows if a listener is too slow. For state like "online or not", only the latest value matters, so undelivered changes can be coalesced.

Summary

  • The publisher knows only an interface; it notifies on real changes.
  • Snapshot iteration, try/catch per listener, an unsubscribe handle.
  • No subscribe(this) in a constructor.
  • @EventListener shares the transaction; AFTER_COMMIT runs after it but isn't durable.
  • Work that mustn't be lost goes through an outbox and a broker.

Next: Part 4: Adapter and Factory.

Practice interview questions on this topic

All OOP & Design questions →All Spring Boot questions →

Loading comments…