- With the command line tool jmap
- By using a provided MBean (Java Management Extension – JMX) and the tool jconsole
Of course, there is the possibility to use the Java Virtual Machine Tool Interface (JVMTI) to produce a dump – but therefore you would have to implement an agent in C. Many Profiling Tools (like JProfiler) provide a JVMTI agent to create and evaluate a heapdump with a GUI.
To automatically generate a heap dump when an OutOfMemoryError is thrown you have to provide this JVM command line parameter:
The parameter causes the JVM to dump a HPROF headump to the current directory if an OutOfMemoryError occurs. The name of the dump is by convention java_pid.hprof. To specify the directory and the name of the file by yourself, you can add the parameter -XX:HeapDumpPath=path_to_file to the JVM command line options.
The automatic production of dumps with these parameters is not always useful. In some situations you want to produce a heapdump at any given time during application execution. In this case Java version 1.4.2_09, 1.5.x and 1.6.x provide the tool jmap. A HPROF heapdump can be requested by executing the following command:
jmap -dump:file=path_to_file java_process_id.
The provided Java process id determines which local JVM should be dumped. The process Id can be determined with the JVM Tool jps (Note: The jmap tool is not available on every platform and JVM version). You can alternatively use the JVM parameter -XX:+HeapDumpOnCtrlBreak and send a SIGQUIT signal (-3 kill for Unix and Ctrl-Break for Windows) to the running Java process – the signal will also create a heapdump without aborting the JVM.
With Java 6, Sun introduced a JMX MBean which provides methods for generating a heapdump. To create a heapdump via JMX you first start the integrated JMX console with the command jconsole and connect it to the corresponding JVM. For a local connection you don’t need any additional configuration of the JVM – for a connection to a remote machine you have to configure JMX correctly.
You can use the MBean Explorer of jconsole to find the correct MBean within the JVM. The MBean com.sun.management.HotSpotDiagnostic contains the alluded method dumpHeap (String, boolean). With the help of the first method parameter you can set the path and the name of the Heapdump. The screenshot shows the view of the MBean. Pressing on the dumpHeap button will create a heapdump with the given name.
The next part of this series will get into more details how to analyse heapdumps and find memory leaks and common memory antipatterns.
Information about heapdump generation with the IBM JVM can be found in the IBM JVM Diagnosis Documentation.
Information about BEA JRockit and the JRockit Memory Leak Detector can be found in the JRockit Dokumentation.