Design patterns through refactoring series: 1. Strategy · 2. Template Method and composition · 3. Observer and Spring events · 4. Adapter and Factory
Part 1 split a mobile app’s data sync into strategies but left a question open: who swaps the strategy when the network flaps? Observer’s answer: the object that owns the state notifies whoever cares. After this post you can write a publisher that survives a real app, and you’ll know when a Spring event is enough and when you need a message broker with an outbox.
1. v0: the publisher calls the subscriber directly
Key idea: in the v0 code the network class holds a reference to the sync class and plugs in strategies itself, so everything is glued together.
The comments in the repo list three problems with NetworkManagerV0:
- Tight coupling: the network class depends directly on the sync class, and on the strategy classes too.
- Hard-coded notification logic: “what to do when the network changes” lives in the network class, not in the classes that care.
- Adding a subscriber means editing the publisher: if a “you’re offline” banner or the photo uploader should react too, you edit
NetworkManagerV0.
2. v1: a subscriber list, notified on change
Key idea: Observer flips the dependency: the publisher only knows a NetworkListener interface, whoever cares subscribes, and it notifies only when the value differs.
The repo’s v1 does exactly that: NetworkManager has subscribe/unsubscribe, and DataSyncManager implements the subscriber interface and swaps its strategy in update. The repo notes two benefits (new subscribers without touching the publisher; relationships set up at runtime) and one drawback (call order isn’t what you’d expect).
sequenceDiagram
participant OS as Operating system
participant NM as NetworkMonitor
participant DS as DataSyncManager
participant UI as OfflineBanner
DS->>NM: subscribe(this)
UI->>NM: subscribe(this)
OS->>NM: setOnline(false)
NM->>DS: onChange(false)
DS->>DS: switch to LocalSync
NM->>UI: onChange(false)
UI->>UI: show banner
OS->>NM: setOnline(false)
Note over NM: unchanged, no notification
The simplest version most people write (close to the repo’s):
interface NetworkListener { void onChange(boolean online); }
static final class NaiveNetworkMonitor {
private final List<NetworkListener> listeners = new ArrayList<>();
private boolean online;
void subscribe(NetworkListener l) { listeners.add(l); }
void unsubscribe(NetworkListener l) { listeners.remove(l); }
void setOnline(boolean value) {
if (online == value) return; // notify on change only
online = value;
for (NetworkListener l : listeners) l.onChange(value);
}
}
It works in a demo, but fails in four ways in a real app.
3. Four ways Observer breaks, reproduced
Key idea: a naive publisher fails when a listener unsubscribes itself, when one listener throws, when nobody unsubscribes, and when threads or slow listeners show up.
| Scenario | Measured result | Consequence |
|---|---|---|
| A listener unsubscribes itself while notified | 2 listeners: no error, but the next listener is never called; 3 listeners: ConcurrentModificationException |
silent skip or a broken loop |
The first listener (banner) throws IllegalStateException |
the sync manager is never notified | a UI bug breaks data sync |
| 1000 screens subscribe and never unsubscribe on close | 1000 listeners still referenced | memory leak |
| Ordering and threads | synchronous notification, ArrayList and the online field aren’t thread-safe |
a slow listener blocks the publisher |
Code and output of the reproduced scenarios
A listener unsubscribing itself (one that “only needs to know the first time we’re online”):
var naive = new NaiveNetworkMonitor();
boolean[] syncNotified = {false};
NetworkListener once = new NetworkListener() {
public void onChange(boolean online) { naive.unsubscribe(this); }
};
naive.subscribe(once);
naive.subscribe(online -> syncNotified[0] = true);
naive.setOnline(true);
System.out.println("naive, 2 listeners: no exception, sync notified = " + syncNotified[0]);
// add a third listener to the same scenario and you get ConcurrentModificationException
naive, 2 listeners: no exception, sync notified = false
naive, 3 listeners: ConcurrentModificationException
A throwing listener: the exception propagates out of the loop and out of setOnline, so the sync manager behind it never learns the network changed.
naive: sync manager never notified (banner widget crashed)
Nobody unsubscribes (each screen subscribes when it opens, never unsubscribes when it closes):
var naive3 = new NaiveNetworkMonitor();
for (int screen = 0; screen < 1_000; screen++) {
byte[] screenState = new byte[10_000]; // captured by the lambda
naive3.subscribe(online -> { if (screenState.length < 0) System.out.println(); });
}
naive: listeners still referenced after closing 1000 screens = 1000
Ordering and threads. With an ArrayList, notification order is registration order, and registration order depends on initialisation order, so don’t rely on it. The repo misses the other two problems: a slow listener blocks whichever thread called setOnline, and the state isn’t safe when another thread reports network changes.
4. A sturdier publisher
Key idea: iterate over a snapshot, isolate each listener’s errors, return an unsubscribe handle, and register from outside rather than inside a constructor.
static final class NetworkMonitor {
private final List<NetworkListener> listeners = new CopyOnWriteArrayList<>();
private volatile boolean online;
/** Returns a handle; closing it unsubscribes. */
AutoCloseable subscribe(NetworkListener l) {
listeners.add(l);
l.onChange(online); // late subscribers get the current state
return () -> listeners.remove(l);
}
synchronized void setOnline(boolean value) {
if (online == value) return;
online = value;
for (NetworkListener l : listeners) { // iterates over a snapshot
try {
l.onChange(value);
} catch (RuntimeException e) { // one bad listener must not starve the rest
System.out.println(" listener failed: " + e.getMessage());
}
}
}
}
The same three scenarios again (the 1000 screens now use try-with-resources): the sync manager still gets notified, and only 2 listeners remain.
hardened: going online
listener failed: banner widget crashed
sync sees online=true
hardened: listeners left = 2
hardened: listeners after 1000 screens = 2
One more detail in the repo: DataSyncManager calls networkManager.subscribe(this) inside its own constructor. The object isn’t fully built yet; if the publisher notifies right away (or from another thread), the listener runs on a half-initialised object.
javac 21’s this-escape warning
5. Observer in Spring: events, transactions and message brokers
Key idea: in Spring, ApplicationEventPublisher is the publisher, @EventListener is the subscriber, and the container handles registration. The real questions are whether a listener runs inside the transaction or after the commit, and when you must leave the JVM with a broker + outbox.
Publishing an event after a successful booking (Spring code, not run for this post):
public record BookingCreated(long bookingId, long homestayId, String requestId) {}
@Service
@RequiredArgsConstructor
public class BookingService {
private final ApplicationEventPublisher events;
private final BookingRepository bookings;
@Transactional
public Booking book(BookingRequest request) {
Booking booking = bookings.save(/* ... */);
events.publishEvent(new BookingCreated(booking.getId(), booking.getHomestayId(), request.requestId()));
return booking;
}
}
@Component
class BookingEmailListener {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void onBooked(BookingCreated event) {
// runs only if the booking transaction committed
}
}
@EventListenerruns synchronously, on the same thread, in the same transaction by default. If the listener throws,book’s transaction rolls back: good for a mandatory check, bad if a failed email loses the booking.@Ordersets the order between listeners of the same event; without it, don’t rely on any order.@TransactionalEventListener(phase = AFTER_COMMIT)only runs after a successful commit. Add@Asyncif the request shouldn’t wait for the listener.
A dual write (writing to two systems without a shared transaction) is the bug in the repo’s v2 booking flow: it publishes a Kafka event in the postProcess hook, i.e. inside the transaction. If the commit fails, an event has gone out for a booking that doesn’t exist; publish after the commit and a crash in between loses the event. The fix is a transactional outbox: write the event to an outbox table in the same transaction and let another process read it and push it to the broker (see Idempotency in distributed systems and Message brokers and how to choose one).
AFTER_COMMIT: lost work on a crash and writing to the database in the listener
In DDD these are called domain events (BookingConfirmed, SeatsReleased): the aggregate records them, the application service publishes them after saving, and other bounded contexts listen; see DDD and package structure.
Exercises
Exercise 1: Notify asynchronously but keep the order
Task: the NetworkMonitor in section 4 notifies synchronously, so a slow listener blocks the thread reporting network status. Change it so the publisher returns immediately, every listener still receives the changes in the order they happened, and shutting down delivers whatever is still queued.
Solution to Exercise 1: a single-thread executor as a FIFO queue
static final class AsyncNetworkMonitor implements AutoCloseable {
private final List<NetworkListener> listeners = new CopyOnWriteArrayList<>();
// one thread = events are delivered in the order they were published
private final ExecutorService delivery = Executors.newSingleThreadExecutor(
Thread.ofPlatform().name("network-events").daemon().factory());
private boolean online;
AutoCloseable subscribe(NetworkListener l) {
listeners.add(l);
return () -> listeners.remove(l);
}
synchronized void setOnline(boolean value) {
if (online == value) return;
online = value;
delivery.execute(() -> {
for (NetworkListener l : listeners) {
try { l.onChange(value); }
catch (RuntimeException e) { System.out.println("listener failed: " + e.getMessage()); }
}
});
}
@Override public void close() throws InterruptedException {
delivery.shutdown(); // let queued events drain
if (!delivery.awaitTermination(5, TimeUnit.SECONDS)) delivery.shutdownNow();
}
}
One listener sleeps 50 ms per call, and the publisher flips the status 6 times in a row:
publisher returned after 0 ms
[sync:true, banner:true, sync:false, banner:false, sync:true, banner:true, sync:false, banner:false, sync:true, banner:true, sync:false, banner:false]
- A multi-threaded pool would be faster but loses ordering (“offline” could arrive before the “online” that happened before it). A single-thread executor is a FIFO queue.
newSingleThreadExecutor’s queue is unbounded, so a very slow listener makes it grow. For state like “online or not” only the latest value matters, so you can coalesce undelivered changes instead of delivering each one.
Remember
- Explain why a self-unsubscribing listener silently skips the next one with two listeners but throws CME with three.
- List the four ways a naive publisher breaks and the fix for each.
- Know when to use
@EventListener, when@TransactionalEventListener(AFTER_COMMIT), and why the latter isn’t durable. - Explain the dual write and why an outbox solves it.
- Know how to notify asynchronously while keeping the order.
Interview questions
Junior
What problem does the Observer pattern solve?
It lets one object tell several others when its state changes, without depending on each of them.
The publisher keeps a list of subscribers behind an interface and calls each one; whoever cares subscribes. Adding a subscriber doesn’t touch the publisher.
Mid
When writing an Observer publisher, what do you watch out for?
Snapshot iteration, per-listener error isolation, unsubscribing tied to a lifecycle, and never registering this in a constructor.
- Iterate over a snapshot (
CopyOnWriteArrayList) so self-unsubscribing listeners don’t break anything. - Catch exceptions per listener so one bad listener doesn’t block the rest.
- Return an unsubscribe handle and tie it to a lifecycle to avoid leaks.
- Notify only on change; don’t rely on order; consider async delivery if listeners can be slow.
How do @EventListener and @TransactionalEventListener differ?
@EventListener runs at publish time, on the same thread and in the same transaction; @TransactionalEventListener defers to a transaction phase, AFTER_COMMIT by default.
An @EventListener exception fails the publishing method. @TransactionalEventListener only runs if the commit succeeds; good for emails and cache eviction. It isn’t durable: a crash after the commit loses the listener’s work.
Why shouldn’t you call subscribe(this) inside a constructor?
Because the object isn’t fully built yet (a this-escape): the listener may run on an object whose fields are still null.
If the publisher notifies immediately, or another thread does, a subclass (if any) hasn’t run its constructor yet. Since JDK 21, javac -Xlint:this-escape warns about it. Register from outside once construction is done: a create() factory method, the wiring code, or @PostConstruct.
Senior
For “after a booking succeeds, do X”, when do you use a Spring event and when Kafka?
A Spring event when X lives in the same service and can be lost or redone; Kafka through an outbox when X is in another service or must be durable.
Spring events fit cache eviction and metrics, where the goal is decoupling modules. Kafka fits when you need durability, retries, several independent consumers or load buffering. Never publish to Kafka directly inside the database transaction: the dual write either emits events for rolled-back bookings or loses events on a crash after commit.
An Observer in your app is leaking memory. How do you investigate and fix it?
Take a heap dump, follow the paths from GC roots to objects that should be dead (typically a singleton’s listener list), then tie unsubscribing to the lifecycle.
- Heap dump with
jcmd <pid> GC.heap_dump, open it in Eclipse MAT, look at the dominator tree. - Fix:
subscribereturns an unsubscribe handle, closed with the lifecycle; add a listener-count metric to catch it early. WeakReferenceis only a safety net because lambda listeners can get collected too soon.
A slow listener blocks the publisher. How do you notify asynchronously without losing order?
Deliver events through a single-thread executor (a FIFO queue); the publisher just enqueues and returns.
- A multi-threaded pool is faster but reorders events.
- Bound the queue, or coalesce undelivered changes when only the latest value matters.
- Catch listener exceptions inside the task; on shutdown,
shutdownthenawaitTerminationso queued events are delivered. - If you need ordering per key rather than globally, use one queue per key (like Kafka partitions).
Useful phrases for interviews
- “The publisher depends only on the listener interface, so adding a subscriber never touches it.”
- “We iterate over a snapshot and isolate each listener’s exceptions, so one bad listener can’t starve the others.”
- “Forgetting to unsubscribe is the lapsed listener problem; subscribe returns a handle that we close with the component’s lifecycle.”
- “In-process events decouple code; a broker with an outbox decouples systems.”
- “An AFTER_COMMIT listener isn’t durable, so anything we can’t lose goes through the outbox.”
- “A single-thread executor keeps the order of notifications without blocking the publisher.”
Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.