jmap and jstack – getting a heap dump and stack trace from a running JVM

The project I’m working on currently has many server side java components running on linux. One of these in particular has been experiencing severe memory leaks when running in our production environment (but not UAT, surprisingly!)

It turns out there is a tool provided with sun’s jdk 1.5 + which will allow you to get a snapshot of the heap for a running process, without you having to have started the jvm with any particular options set. This tool is called jmap

running:
jmap -histo pid
where pid is the process id on a linux box

will give you a snapshot of the heap which looks like the below:

java -histo pid

Object Histogram:

Size    Count   Class description
-------------------------------------------------------
77928   583 char[]
55696   131 byte[]
8816    29  * ObjArrayKlassKlass
8520    355 java.lang.String
8272    215 java.lang.Object[]
4080    85  java.nio.HeapByteBuffer
3984    83  java.nio.HeapCharBuffer
3608    41  java.lang.Class
2456    19  int[]
1368    57  java.util.Hashtable$Entry
1288    16  * ConstMethodKlass
1208    31  java.lang.String[]
1120    14  java.util.HashMap$Entry[]
1040    10  java.util.Hashtable$Entry[]
1008    14  java.lang.reflect.Field
960 3   * InstanceKlassKlass
etc.

The most useful thing here is probably the object class count. There is a chance this could help you identify an area of your app which is producing an unexpected number of instances of a given class. Other jmap options give you a dump file in different formats – so this is worth investigating too.

There is an equivalent tool jstack (jstack pid), which dumps stack information for each of the running threads. Probably useful for diagnosing deadlocks etc.

The nice thing about both of these tools is that you don’t need to have started the jvm with any specific options. These tools just connect and work – so you don’t need to have planned your memory leak in advance :)

They only work on unix right now, unfortunately.
There is a good article on new tools with jdk1.6 here

nb. if jstack fails you may be able to get a thread dump on unix using kill -3 {pid}
Here is another useful link for suggestions on diagnosing performance problems

And here is a good link to help diagnose java app problems in general


You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

AddThis Social Bookmark Button

Leave a Reply