How to get a heap dump of a remote machine via JMX?

3 min

When hunting memory leaks, you need a basis to work with. One of the most valuable things is a memory dump of the Java Virtual Machine. Those snapshots of the current state of the JVM are called heap dumps. They contain all the objects living in the JVM and a lot of other information needed to debug certain operations problems. So, how to get a heap dump of a remote machine? The following steps show you how to get a heap dump off of a remote JVM, e.g. running on your test server.

  1. Enable JMX by adding the following system properties to the java command line arguments. Note that disaling security is of course not recommended, but for a local development environment, it may be okay for you. For Tomcat, add it to CATALINA_OPTS in catalina.sh

-Djava.rmi.server.hostname=myserver
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=11391
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false

  • Connect to the remote machine using VisualVM via JMX: myserver:11391
  • Go to the MBeans tab, open the com.sun.management folder and select the HotSpotDiagnostic MBean.
  • In the Operations tab, enter the filename (e.g. “dump1.hprof“) into the input field p0. Keep the value “true” in the p1 field. Click on the dumpHeap button. The JVM will halt for a moment to write the file.

Info box: Method successfully invoked ©Bosch.IO
Application of hot spot diagnostic MBean ©Bosch.IO

  1. Find the heap dump, it will be in the current working directory of the process. If you don’t know where the cwd of the process is, do a ps for the process to get the pid and use pwdx to find the current working directory:

root@xxxxx:/opt/apache-tomcat-6.0.20/logs# pwdx 4653
4653: /home/tomcat
root@xxxxx:/opt/apache-tomcat-6.0.20/logs# ls -al /home/tomcat
-rw-------  1 tomcat tomcat 353689250 2011-10-13 10:26 dump1.hprof

Hint: Although .hprof files are binaries, they usually have a very good compression ratio, so try bzipping them before transferring them to save time and bandwidth (in this case, from 350MB to 50MB):

root@xxxxx:/home/tomcat# bzip2 dump1.hprof
root@xxxxx:/home/tomcat# ls -al
-rw-------  1 tomcat tomcat 52833332 2011-10-13 10:26 dump1.hprof.bz2