Video in progress
What happens if a listener or observer is registered and never removed?
The event source holds a strong reference to the listener, so the listener and everything it holds escape the GC: a "lapsed listener" memory leak. On top of that, "dead" objects keep receiving events and work with stale state.
📖 Answer
public class PriceFeed {
private final List<PriceListener> listeners = new CopyOnWriteArrayList<>();
public void subscribe(PriceListener l) { listeners.add(l); }
public void unsubscribe(PriceListener l) { listeners.remove(l); }
}
// for every WebSocket session
var view = new ClientPriceView(session); // holds a buffer and the session
feed.subscribe(view);
// the session closed, unsubscribe was never called
On a server that has been running for a week, listeners holds thousands of closed sessions. In a heap dump, PriceFeed.listeners shows up with the largest retained size. Every price update tries to write to dead sessions: wasted CPU and error logs.
Design solutions:
- Return the subscription as an object:
public AutoCloseable subscribe(PriceListener l) {
listeners.add(l);
return () -> listeners.remove(l);
}
The caller closes it when the session closes, so the lifecycle is explicit.
- Tie it to the owner's lifecycle:
@PreDestroyin Spring,afterConnectionClosedin WebSocket. - Weak references (
WeakReference,WeakHashMap) are sometimes used, but if the listener is a lambda, nobody else holds it and it disappears immediately. That gives unexpected "silent" bugs, so I prefer an explicit unsubscribe.
Spring's ApplicationEventPublisher is free of this problem: listeners are beans, and the context manages their lifecycle.
Sign up to mark studied questions and save your progress.