Jmap and jhat are a couple of tools really useful to analyze the memory consume of a java program. Both are included in the JVM 1.6 so there is no need to install any extra stuff.
Jmap allows you to create a dump of the java memory heap at any moment in the life of your running application. It will contain all the live objects and classes at that moment. To create the heap dump it’s as easy as:
jmap -dump:file=my_stack.bin 4365
Where my_stack.bin is the name of the file where you want the dump and 4365 is the pid of the java application process.
If you are running a servlet application under a java server and it ends with a:
java.lang.OutOfMemoryError: Java heap space
You can trigger a dump of the java heap at the OutOfMemory moment specifying these parameters to the server:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/sturlese/stack_test/
This will create a .hprof file (named with the pid’s process) containing the dump in the specified path.
HeapDumpPath param is not compulsory. If we don’t specify it the dump will be created in the folder where Tomcat launches the webapps.
Now we have the dump of the java heap. To analyze it we will use jhat. Once we launch jhat specifying the dump to analyze it will start an HTTP server (in the port 7000 by default) and will let you surf along all the classes and objects. You will be able to check how many instances of each class where alive in the moment the heap was created. To launch jhat:
jhat my_stack.bin
It’s easy to get an OutOfMememory exception when opening the java heap. The dump file can be very memory consuming if you app was in the moment it was taken. If you experience the problem you should give to the JVM as much memory as you can:
jhat -J-mx2000m my_stack.bin
Now is the moment to point your web browser to http://localhost:7000 and start analyzing the heap!
Tags: Java, jhat, jmap, Open source
[...] ⇒ Analyzing Java Heaps with jmap and jhat [...]
if you are getting OOM when using jhat try eclipse mat.