November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Categories

November 2024
M T W T F S S
 123
45678910
11121314151617
18192021222324
252627282930  

Java Heap Dump and analyze

First get the Java Applications Process Id, one way to do this is with: jps

jmap -dump:format=b,file=dump.bin <javaProcessIdHere>

The size of the heap dump file will be same as the heap memory in use at the time the command is run. For large heap sizes this can take several minutes to run, and can stall (make it unresponsive) the application during this time.

To get a summary of Object Instances and Sizes you can use this command:

jmap -histo:live <javaProcessIdHere>

Generally, this command will run quickly, and should be used when taking a heap dump will be too costly in terms of time-taken/size etc.

To get Heap Dump on Out of Memory Exception (available from Java 1.5.0_07 onwards):

Add the following param: -XX:+HeapDumpOnOutOfMemoryError

If you want the dump to go in a particular path then add: -XX:+HeapDumpOnOutOfMemoryError XX:HeapDumpPath=/usr/local/dumps

To initiate Heap Dump from within the Application Code:

We can also use jmap from our code. To get a pid from code use we need to use java.lang.management.ManagementFactory.

String name = ManagementFactory.getRuntimeMXBean().getName();
String pid = name.substring(0, name.indexOf("@"));
After that we can start jmap process like this:
String[] cmd = { "jmap", "-dump:file=/usr/local/heapdumps/dump.bin", pid };
Process p = Runtime.getRuntime().exec(cmd);

A simple Shell Script to Take Heap Dump every 30 seconds:

while true
do
  jmap -dump:file=/tmp/java-`date +%s`.hprof <processIdOfJVM>
  sleep 30
done

Heap Dump Analysis Tools
  • Java Visual VM (part of JDK)
  • jhat – Java Heap Analysis Tool (Suitable for analyzing very big heap files)

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>