Heap dump
- Java course
- Expert
- Lesson 34/46
- 5 min
Learn memory analysis with jmap and heap dumps.
Taking a heap dump
A heap dump is a snapshot of the live objects on the heap; it is saved in .hprof format. It is taken with jcmd PID GC.heap_dump file.hprof or automatically at OOM with the -XX:+HeapDumpOnOutOfMemoryError flag.
The dump is used to find memory leaks. The largest objects, retained size and the dominator tree are inspected.
Heap dump analysis
In heap dump analysis retained size is key: it shows how much memory would free up if an object were removed. The dominator tree presents the objects holding the most memory hierarchically.
Analysis tools: Eclipse MAT suggests leak suspects, VisualVM does live monitoring, and the old jhat has been replaced by MAT. Once a leak is found the root reference (GC root) is traced.
Practice Write the HeapDumper class
Define class HeapDumper with a static String dump(int pid, String path) method that returns "jcmd " + pid + " GC.heap_dump " + path. In main print System.out.println(dump(1234, "/tmp/heap.hprof"));.
Starter code
// Define the HeapDumper class: dump method builds the jcmd command
// main: print the heap dump command for PID 1234Sample solution
class HeapDumper {
static String dump(int pid, String path) {
return "jcmd " + pid + " GC.heap_dump " + path;
}
public static void main(String[] args) {
System.out.println(dump(1234, "/tmp/heap.hprof"));
}
}Expected output
jcmd 1234 GC.heap_dump /tmp/heap.hprof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a heap dump capture?
- Stack traces
- Thread state
- Live objects Correct answer
- CPU samples
Explanation: A heap dump is a snapshot of live objects on the heap.
2 Complete the OOM flag
-XX:+____ -XX:HeapDumpPath=/tmp/dump.hprof
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dump.hprof
Explanation: This flag takes a heap dump at OOM.
3 Match the analysis tools
| Term | Meaning |
|---|---|
Eclipse MAT |
Finds leak suspects |
VisualVM |
Live monitoring |
jcmd |
Takes dump |
retained size |
Retained memory |