Identifying and fixing Java memory leaks relies on profiling tools that observe live memory usage plus heap dump analyzers that inspect a memory snapshot after the fact, combined with disciplined resource management in code.
Key Points: • Profilers like VisualVM, JProfiler, and YourKit attach to a running JVM and show real-time heap usage, object counts, and GC activity to spot growth trends. • Heap dump analyzers such as Eclipse Memory Analyzer (MAT) parse a .hprof heap dump and highlight the dominator tree and suspected leak suspects. • jmap can trigger a heap dump and jstat can monitor GC statistics from the command line without a GUI. • Code-level discipline matters as much as tooling: always close streams, connections, and sessions, ideally via try-with-resources, and avoid unbounded static collections that retain object references. • Comparing heap dumps taken at different points in time, before and after a suspected leaking operation, is a reliable way to confirm which objects are accumulating.
Example: A team noticed steadily climbing heap usage in production; taking a heap dump with jmap and opening it in Eclipse MAT revealed a static HashMap cache that was never evicting entries, which they fixed by switching to a bounded, expiring cache.
Interview Tip: A concise interview answer is:
"I'd use a profiler like VisualVM or JProfiler to watch heap trends live, and if a leak is confirmed, take a heap dump and analyze it in Eclipse MAT to find the dominator objects holding memory. On the code side, I'd check for unclosed resources and static collections that grow without bound."