Looking at a heap dump is a great way of to ensure that your code is performing as you designed it. It also extremely useful for finding memory leaks.
The basic tools needed to generate a heap dump are available as part of the JDK or off the web. There are multiple analysis tools available either off the web or included in the JDK (starting with JDK 6).
|The calls below fail to work on OS X. The following from Ken Sipeis claimed to fix it. (Thanks Chris)Let’s get to fixing the issue1. Download JSR-223’s engines https://scripting.dev.java.net/files/documents/4957/37593/jsr223-engines.zip
2. Download Rhino http://www.mozilla.org/rhino/download.html
4. Copy rhino1_7R1/js.jar to /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/lib/ext/
now jrunscript -q should look like this:
… and jrunscript will put you in a js shell.
Also something I didn’t realize until I was preparing for this post… jmap worked for the console dump if I sudo’d the command. However it would not do a file dump. I did the file dump using jconsole and jmx. Now that the scripting issue is fixed, jmap is improved in the following manner:
1. if you type jmap , it now prompts you for your admin password (instead of just failing)
You can instruct the JVM to generate a dump file whenever an OutOfMemory error is thrown. This is done by adding the following parameters to the command line.
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<path to dump file>
You can use the jmap tool that comes with JDK 1.5 to generate a heap dump manually.
|I was not able to get this to work on OS X.|
jmap -heap:format=b -d64 <jvm pid>
This generates a file called heap.bin.
The jmap tool for JDK 6 has been upgraded and the options have changed.
|I have not tried this to ensure the options are correct|
jmap -J-d64 -dump:format=b,file=<path to dump file> <jvm pid>
There are several tools available to analyze heap dump files.
This easy to use tool is available as part of the JDK 6 installation as the command jhat. It is available for JDK 5 from https://hat.dev.java.net/. Launching the tools creates a web server on port 7000 that can be used to view the heap analysis.
|I was not able to get either form to work on OS X.|
java -Xmx512m -jar ha26.jar <path to dump file>
jhat <path to dump file> Note : when generating heaps, it's almost always a good idea to use the :live option to only dump living objects. The times when you care about dead objects in the heap are few and far between.