Week 64 — What is a heap dump and why can it be useful?
Question of the Week #64
What is a heap dump and why can it be useful?
4 Replies
While Java stores local variables in the stack, the content of objects is typically stored on the heap.
For diagnosing and debugging purposes, it is possible to create a snapshot of the heap called a heap dump.
A heap dump typically contains what is stored on the heap of a running Java application at the time the heap dump is created.
Since it contains the content of objects, it can be used for diagnosing memory leaks or to find out which parts of the application uses which amount of memory using a tool like Eclipse Memory Analyzer tool which is capable of processing heap dumps.
Java can automatically create a heap dump when a program crashes due to being out of memory. This can be configured using the flag
-XX:+HeapDumpOnOutOfMemoryError
.
For example, take the following program:
When running this program with the command java -XX:+HeapDumpOnOutOfMemoryError OOM.java
, it will run into an OutOfMemoryError
and automatically create a heap dump saved in a hprof
file located in the current directory (if writable).
On the other hand, running it using java -XX:-HeapDumpOnOutOfMemoryError OOM.java
(with a -
instead of a +
) will run out of memory without generating a heap dump.This heap dump can then be analyzed using a tool like Eclipse MAT.
When opening the heap dump, it shows objects by their size with some other information as shown in the first image.
Tools like that also often allow creating histograms showing the amount of memory consumed by class. In case of the above program, most memory is used by
long[]
s.Aside from creating a heap dump while an application runs out of memory, it is also possible to create it while the application is running.
This can be done using the
jcmd
tool. This requires first finding the process ID of the Java program to create a heap dump of.
After obtaining the process ID, it is possible to use jcmd
to create a heap dump by running the following command using the actual process ID instead of PID
(this example creates the heap dump in /tmp/dump.hprof
):
📖 Sample answer from dan1st
A heap dump is a snapshot of the state of all objects in heap memory. It can help in solving problems related to memory shortage.
Submission from ebli