Heap dump is a snapshot of the Java memory. It contains information about the Java objects and classes in the heap at the moment the snapshot is triggered. It’s vital artifact to diagnose any Java memory related problems.

Heap dumps can be captured using several mechanisms. Here I am going to show a couple of effective ways.

Identify the Process Id

First, you need to identify the Java Process Id, for which you are going to capture Heap Dump. For this purpose, you can use “jps” (JVM Process Status) tool that is shipped in JDK. This tool list all the Java processes that are running on the target system and their process Id.

jps
30548 org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
36292 Jps
37320 AddressBook

The first field in each line is the process Id and the second field is the name of the Java program that is running. As per the above example ‘37320’ is the process Id of the AddressBook program.

Alternatively, if you are running on *nix operating system, you can also issue “ps” (process status) command and grep for java processes. Example:

ps -ef | grep 'java'

Capture Heap Dump – jmap

You can use the “jmap” tool to capture the heap dump. jmap prints heap memory details of a given process into a file. jmap tool is shipped with JDK. Here is how you should invoke it:

jmap -dump:live,file=<file-path> <pid>

where
pid: is the Java Process Id, whose heap dump should be captured
file-path: is the file path where heap dump will be written in to.

Example:

jmap -dump:live,file=/opt/tmp/AddressBook-heapdump.bin 37320

Note: It’s quite important that you pass the “live” option in the command line. If this option is passed then only the live objects in the heap are dumped. If your application is running with a large memory size then typically it would take a long time to capture the heap dump and even longer time for the tools to parse them.

“Live” objects are the one that has active memory references. For analyzing memory leaks just live objects are good enough.

Capture Heap Dump – HeapDumpOnOutOfMemoryError

You can also capture Heap Dump when JVM experienced OutOfMemoryError by passing ‘-XX:+HeapDumpOnOutOfMemoryError’ system property. This property is quite an effective property that I would recommend all JVMs to have this property configured. Due to heat of the moment, sometimes Operations team might forget to capture heap dump. It’s extremely hard to diagnose any memory problems without heap dumps. This Property can be the savior of the day in such circumstances.

Sample Usage:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/logs/heapdump

Now you have learned how to capture heap dumps. Next, read how to analyze Heap Dumps.