Video in progress
How can the Observer pattern cause a memory leak?
The subject keeps a strong reference to its listeners. If a listener isn't removed from the list when it's done, the GC can't collect it (or anything it holds). This is called the "lapsed listener" problem.
📖 Answer
A typical scenario: a long-lived object (say, a singleton EventBus) and short-lived ones (a handler created for every request, every WebSocket session).
class PriceFeed {
private final List<PriceListener> listeners = new CopyOnWriteArrayList<>();
void subscribe(PriceListener l) { listeners.add(l); }
void unsubscribe(PriceListener l) { listeners.remove(l); }
}
// on every new WebSocket connection
feed.subscribe(session::sendPrice);
// the connection closed, but unsubscribe was never called
A few days later the heap holds thousands of closed sessions, because listeners is holding on to them. In a heap dump the PriceFeed.listeners list shows up as huge.
How to prevent it:
- always call
unsubscribewhere you subscribed: infinally, in@PreDestroy, in the session-closed callback; - have
subscribereturn anAutoCloseable, and make whoever called it responsible for closing it; - sometimes people store listeners with a
WeakReference, but this is a trap with lambdas: if nobody else holds a reference to the lambda, it gets collected right away and the listener silently disappears.
Spring's @EventListener beans live as long as the context does, so this problem almost doesn't exist there.
Sign up to mark studied questions and save your progress.