Video in progress

What is a heap dump, and how can you take one?

A heap dump is a snapshot of the entire heap at a given moment: all objects, their fields and the references between them. You can take it by hand with jcmd <pid> GC.heap_dump or automatically on an OOM.

📖 Answer

A heap dump is an .hprof file, and it is the most reliable way to find out where the memory is going.

# from a running process
jcmd 12345 GC.heap_dump /tmp/app.hprof

# the old way
jmap -dump:live,format=b,file=/tmp/app.hprof 12345

# automatically on an OOM
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps -jar app.jar

To open it, you use Eclipse MAT, VisualVM or the profiler in IntelliJ IDEA Ultimate. The "Leak Suspects" report in MAT often shows the problem on the very first screen.

What you need to know:

  • the application pauses while the dump is taken: on a large heap that is seconds;
  • the file size is roughly the used heap. An 8 GB heap needs 8 GB of disk space;
  • the dump can contain passwords, tokens and personal data. Don't drop it into a chat or any open place.

The live option does a GC first and writes only live objects, so the file is smaller.