Tuesday, October 7, 2008

Great tool to analyze a JVM memory dump

In the old days of Java, when you had an OutOfMemory exception, you had to begin a very painful exercise of trying to determine the source of the error. This was difficult to do since one had to reproduce and try to isolate the cause of the problem.

Now, we have heap dumps and there are a number of ways to get heap dumps out of a JVM but at a bare minimum you need to have Sun JVM's great flag on at all times:
-XX:+HeapDumpOnOutOfMemoryError

This causes the JVM to dump a snapshot of the current heap when there is an OutOfMemory exception.
This flag causes no runtime overhead, since it only comes into play when the OOM happens - the JVM then checks to see if it is set and if so will dump the heap.

There are a number of tools available to examine a heap dump.
The most basic comes with the JDK itself (starting with JDK 6): jhat
Its usage is fairly straightforward (don't forget the -J parameter to enlarge the heap of jhat itself) but its fairly basic.
It's UI is a basic HTML one.


It has a query language which is useful. It is based on Javascript for fancier queries but I had a hard time with the syntax whenever I tried to do anything fancy. It's documentation is really lacking in that regard.
However, since jhat is open source it's relatively easy to write queries in Java and compile them into jhat.

Another option is a profiler like Yourkit
It can open hprof files and its UI is pretty good as well (definitely better then jhat's)
It's commercial so that of course is a huge drawback. In addition, it is fairly slow in opening large dumps.

The best option is a relatively new tool. (and its the reason I decided to write this post - everyone needs to know about this tool) Actually it has been around for a bit but it has recently been added to Eclipse.
I am talking about Eclipse's Memory Analyzer Tool. It used to be known as SAP Memory Analyzer but was recently added to Eclipse. The new version is like its SAP predecessor but it just seems slightly more polished and ready for prime time.
It opens dumps fairly quickly and uses less memory too (It does create lots of index files on the disk but that's not that big of a deal)

It also has a query language and while it's similar to jhat's query language (they both call it OQL though this one is not Javascript based), it just seems more straightforward to use. Plus the built in queries just seem more useful and plentiful. I haven't tried adding queries to MAT though.

You can download a 32 bit version or a 64 bit version if you want to open larger heaps here.

1 comment:

Markus Kohler said...

thanks for the nice review about MAT :)

You may want to check some examples of how to use MAT at my
Java Performance blog

Regards,
Markus