Common ways to get JVM heap memory dumps

1. Introduction to heap memory dump

Heap dump (Heap Dump) refers to a snapshot of the JVM heap memory at a certain moment, and is generally hprofsaved in a binary file in the format. It can be used to analyze memory leaks and optimize memory usage of Java programs.

Common memory dump analysis tools include: jhat , JVisualVM , and the Eclipse-based MAT tool.

The following describes common methods for obtaining heap memory dumps.

2. Use JDK built-in tools

JDK has many built-in diagnostic tools, which are located JDK_HOME/binin the directory. Generally speaking, this directory can be included in the system PATH path and can be called directly on the command line.
The JDK's built-in heap memory dump tools include:

2.1 jmapTools

jmapIt can be used to output statistics of JVM memory, and supports access to local JVM and remote JVM instances.

Use -dumpthe option to get a heap memory dump, the command is:

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

After -dump:the option, the following parameters can be specified:

  • live: Optional parameter; indicates that only surviving objects are output, that is, FullGC will be executed first to clear the parts that can be recycled.
  • format=b: Optional parameter, specifying the dump file as a binary format. When dumping heap memory, the default is the binary format.
  • file: Specifies the save path of the dump file.
  • pid: Specifies the pid of the Java process.

An example of use is as follows:

jmap -dump:live,format=b,file=/tmp/dump.hprof 12587
# 或者
jmap -dump:file=/tmp/dump.hprof 12587

The pid of the JVM process is generally jpsobtained through the command, of course, you can also use jcmdthe command or pscommand to query.

2.2 jcmdTools

jcmdIt is a versatile command-line diagnostic tool. Its working principle is to send the command to be executed to a specific JVM instance, so it is only supported on the local machine.

One of the commands is GC.heap_dumpthat can be used to obtain a heap memory dump, only need to specify the pid, the command format is:

jcmd <pid> GC.heap_dump <file-path>

Example usage is also similar:

jcmd 12587 GC.heap_dump /tmp/dump.hprof

Like jmap, memory dump files are binary.
Because the command is passed as a parameter to the specific JVM for execution, the file path should preferably be an absolute path.

2.3 JVisualVM Tools

JVisualVM is a graphical interface tool that can be used to monitor, analyze and diagnose Java applications.

img

The graphical interface is simple and elegant, and powerful, and supports many plug-ins.

One of the functions is to grab a heap memory snapshot, open the program, right-click on the visible Java process, and select "Heap Dump" to create a new memory dump file and automatically save it in the new open in a tab.

insert image description here

After the completion, we can see the directory information of the dump file in the basic information (Basic Info).

3. Automatically perform a heap memory dump

The tools introduced above are all executed manually. Sometimes, we hope that when a memory overflow error occurs java.lang.OutOfMemoryError, the JVM will automatically perform a heap memory dump, so as to facilitate investigation and analysis afterwards. The JVM provides a command-line startup parameter HeapDumpOnOutOfMemoryErrorin the format:

java -XX:+HeapDumpOnOutOfMemoryError

If you do not HeapDumpPathspecify the dump path with the option, it will be automatically saved to the startup directory, and the format of the file name is: java_pid<pid>.hprof.

HeapDumpPathAn example of using the specified parameter is as follows:

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

If a memory overflow occurs during the running of a Java program, you will see something like this in the log:

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 in 0.029 secs]
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at com.baeldung.heapdump.App.main(App.java:7)

The automatically created dump file here is named java_pid12587.hprof.

As you can see, this option is very useful and has little overhead for a normally running program. It is therefore strongly recommended to enable this option, especially in a production environment.

Of course, this option can also be dynamically set through MBean, such as setting the value of the option HotSpotDiagnosticin the JMX client :HeapDumpOnOutOfMemoryErrortrue

insert image description here

For more information on MBeans and JMX, please refer to: JMX and related tools: the mountain is small, the truth is clear

4. JMX method

Finally, let's take a look at how to get a heap memory dump through JMX. Essentially calling HotSpotDiagnosticthis MBean, which provides a dumpHeapmethod with parameters:

  • outputFile: The path of the dump file, usually .hprofending with the suffix.
  • live: If set to true, only live objects will be dumped, jmapsimilar to the use of .

Here is an example of usage:

4.1. JMX Client Tool

HotSpotDiagnosticThe easiest way to manipulate MBeans is as a graphical interface client, eg JConsole, JVisualVMetc.

Open it JConsole, connect to the specified Java process, switch to MBeansthe tab, locate com.sun.management.under the package HotSpotDiagnostic, and execute the corresponding dumpHeapmethod.

insert image description here

Then fill in the corresponding parameters in p0and slots , and execute .p1outputFilelivedumpHeap

4.2. Call programmatically

First, you need to obtain MBeanServerthe instance, and then obtain HotSpotDiagnosticMXBeanthe MBean registered by the system, and then call dumpHeapthe method. The sample code is as follows:

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);
}

Please note that hprofthe file cannot be overwritten, if the file already exists, an error will be reported:

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

5. Summary

This article describes several ways to obtain a heap memory dump. To sum it up briefly:

  1. It is strongly recommended to specify JVM startup parameters HeapDumpOnOutOfMemoryError.
  2. If jmapit cannot be used, other alternatives can be used, such as jcmd, JVisualVM, JMX, etc.
  3. For the code corresponding to this article, please refer to: GitHub repository .

Guess you like

Origin blog.csdn.net/renfufei/article/details/108785603