Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

One, foreword

In this article, we summarize several different approaches to Java dump.

A Java Heap Dump is a snapshot of all the objects in the JVM’s memory at a specific time. They are useful for solving memory leaks and analyzing memory usage in Java applications.

Java Heap Dump is typically stored as a binary hprof file. We can open and analyze these files using tools like JHAT or JVisualVM. Again, it is common to use the MAT tool for analysis.

Second, JDK toolkit

The JDK comes with several tools for Heap Dump in different ways. All of these tools are located in the bin folder in the JDK home directory. Therefore, as long as the directories are included in the system path, we can launch them directly from the command line.

1, jmap

Jmap is a tool for printing statistics about memory in a running JVM. We can use it for local or remote processes.

To use Jmap Heap Dump, we need to use the Heap Dump parameter:

jmap -dump:[live],format=b,file=<file-path> <pid>
Copy the code

Along with this parameter, we should specify several parameters:

  • Live: If set, only objects with active references are printed and objects that are ready for garbage collection are discarded. This parameter is optional.
  • format = b: Specifies that the dump file will be in binary format. If not, the result is the same
  • File: indicates the file to be written
  • Pid: INDICATES the ID of a Java process

Here’s an example:

jmap -dump:live,format=b,file=/tmp/dump.hprof 12587
Copy the code

Note: We can easily get the PID of a Java process using the JPS command.

Jmap was introduced in the JDK as an experimental tool. Therefore, in some cases where this is not supported, it is best to use another tool instead.

2, JCMD

JCMD is a very complete tool that works by sending command requests to the JVM. We must use it on the same machine where the Java process is running.

Its most common command is gc. heap_dump, which can be used to Heap Dump by specifying the process PID and output file path:

jcmd <pid> GC.heap_dump <file-path>
Copy the code

We can execute it with the same arguments we used in the example above:

jcmd 12587 GC.heap_dump /tmp/dump.hprof
Copy the code

As with JMap, the generated dump is in binary format.

3, JVisualVM

JVisualVM is a tool with a graphical user interface that allows you to monitor, troubleshoot, and analyze Java applications. The GUI is simple, intuitive, and easy to use.

We can right-click on the Java process and select the “Thread Dump” option, which will create the dump and open it in a new TAB:

Note: We can find the path to the created file in the “Basic Information” section.

As of JDK 9, Visual VM is not included in the Oracle JDK and Open JDK distributions. Therefore, if we are using Java 9 or later, we can get JVisualVM from the VisualVM open Source project site. Address: visualvm. Making. IO /

Automatic heap dump

All tools are manually dumped at specified times. In some cases, we hope that in the event of a Java lang. When an OutOfMemoryError Heap Dump, to help us to analyze problems.

In this case, Java provides HeapDumpOnOutOfMemoryError command line parameters, thrown when the Java. Lang. OutOfMemoryError, the program will generate heap dump:

java -XX:+HeapDumpOnOutOfMemoryError
Copy the code

By default, it stores dump in the javA_pid .hprof file in the directory where we are running the application. If you want to specify another file or directory, you can set it in the HeapDumpPath parameter:

java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=<file-or-dir-path>
Copy the code

Using this parameter, we will be able to see the created file containing dump in the log when our application is out of memory:

java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Dumping heap to java_pid12587.hprof ...
Exception in thread "main" Heap dump file created [4744371 bytes in0.029 secs] Java. Lang. OutOfMemoryError: Requested array size exceeds the VMlimit
	at com.baeldung.heapdump.App.main(App.java:7)
Copy the code

In the example above, it was written to the javA_pid12587. hprof file.

As we can see, this parameter is very useful, and there is no overhead when running the application with it. Therefore, it is highly recommended that you always use this parameter, especially in production.

Finally, it can be used at run timeHotSpotDiagnostic MBeanTo specify this parameter. To do this, we can use the JConsole tool and putHeapDumpOnOutOfMemoryErrorThe VM parameter value is set to true:

Four, JMX

We will use the HotSpotDiagnostic MBean that was briefly introduced in the previous section. The MBean provides a dumpHeap method that takes two arguments:

  • OutputFile: dump file path. This file should have the hprof extension
  • Live: If set to true, it only dumps live objects in memory, as we saw earlier on JMap

There are two different ways to call this method to heap dump.

1, the JConsole

The easiest way to use HotSpotDiagnostic MBeans is to use a JMX client (such as JConsole)

When you open JConsole and connect to a running Java process, you can navigate to the MBeans TAB and clickcom.sun.managementGo to HotSpotDiagnostic. In operation, we can find the dumpHeap method we described earlier:

As shown, to perform the dumpHeap operation, we simply need to introduce the parameter outputFile and store it in the P0 and P1 text fields.

2, programming,

Another way to use HotSpotDiagnostic MBean is by calling it programmatically from Java.

To do this, we first need to get an instance of MBeanServer to get the MBeans registered in the application. After that, we just need to get an instance of the HotSpotDiagnosticMXBean and call its dumpHeap method.

import javax.management.MBeanServer;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Paths;

public class HeapDump {

    public static void dumpHeap(String filePath, boolean live) throws IOException {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(
          server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
        mxBean.dumpHeap(filePath, live);
    }

    public static void main(String[] args) throws IOException {
        String file = Paths.get("dump.hprof").toFile().getPath();

        dumpHeap(file, true); }}Copy the code

Note that the hprof file cannot be overwritten. Therefore, this should be taken into account when creating applications that print Heap dumps. If we don’t, we get an exception:

Exception in thread "main" java.io.IOException: File exists
	at sun.management.HotSpotDiagnostic.dumpHeap0(Native Method)
	at sun.management.HotSpotDiagnostic.dumpHeap(HotSpotDiagnostic.java:60)
Copy the code

Fifth, Arthas

Arthas is an open source Java diagnostic tool from Ali. Can view application thread status, JVM information, etc. In addition, it can diagnose service problems online, such as viewing the input and output parameters of method invocation, execution process, exceptions thrown, and output method execution time, which greatly improves the efficiency of troubleshooting online problems.

Arthas provides the heapdump Java heap command, which is similar to the heapdump function of the jmap command.

Dump to specified file:

[arthas@58205]$ heapdump /tmp/dump.hprof
Dumping heap to /tmp/dump.hprof...
Heap dump file created
Copy the code

Dump only live objects:

[arthas@58205]$ heapdump --live /tmp/dump.hprof
Dumping heap to /tmp/dump.hprof...
Heap dump file created
Copy the code

Dump to temporary files:

[arthas@58205]$ heapdump
Dumping heap to /var/folders/my/wy7c9w9j5732xbkcyt1mb4g40000gp/T/heapdump2019-09-03-16-385121018449645518991.hprof...
Heap dump file created
Copy the code

More reference: arthas. Gitee. IO/heapdumps ht…

Six, the conclusion

In this article, we’ve shown a variety of ways to use Java Heap Dump.

From the experience, we should remember to always use when running the Java application HeapDumpOnOutOfMemoryError parameters.