Java Core & JVM (50 Qs)•Part 3: JVM Internals, Low-Latency Systems & Production Tuning (25 - 35)
How do you detect, analyze, and resolve a Java Memory Leak using Heap Dumps?
senior LevelCode ExampleMemory ManagementData Structures
In Simple Words:
A Java memory leak occurs when objects are no longer needed by application logic, but remain reachable via an unintended strong reference path from a GC Root (e.g., static collections, unclosed listeners, un-cleared ThreadLocal variables in pooled threads).
Production Diagnostics Workflow:
- Capture Heap Dump automatically on OOM:
bash
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps/heap.hprof - Capture Live Dump manually via
jcmd:bashjcmd <pid> GC.heap_dump /var/dumps/manual_dump.hprof - Analyze using Eclipse MAT (Memory Analyzer Tool):
- Run the Leak Suspects Report.
- Inspect the Dominator Tree: Identifies the single object instance retaining the largest retained heap size.
- Trace the Path to GC Roots excluding weak/soft references to discover the exact leak culprit.