How can the Observer pattern cause a memory leak, and how would you prevent it?
A Subject's observer list holds a strong reference to every attached observer for as long as the Subject itself is alive. If an observer — say, a UI component or a session-scoped object — gets logically discarded elsewhere in the application but is never explicitly detached, the Subject keeps it, and everything it in turn references, reachable in memory indefinitely, even though nothing else in the program still needs it. This is a genuinely common real bug, especially in long-lived subjects like application-wide event buses. The fix is discipline plus tooling: always pair every attach() with a corresponding, reliably-called detach(), often tied to a component's own lifecycle hooks (like a UI framework's onDestroy), or use weak references for the observer list so an observer can be garbage collected even if something forgot to detach it explicitly.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response