“This is the 10th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

This section describes how to use the Memory Analyzer Tool (MAT), which helps Java programmers quickly analyze Memory and locate problems.

The MAT(Memory Analyzer Tool), a cross-platform eclipse-based Memory Analyzer Tool, is a fast and feature-rich JAVA Heap analysis Tool, which reads the dump file snapshot generated by the JAVA runtime environment at the application runtime. Can help us find memory leaks and reduce memory consumption. Use the memory analysis tool to analyze from many objects, quickly calculate the size of the object in memory, see who is blocking the garbage collector’s recycling work, and can intuitively view the possible result of the object through the report.

Official website address:www.eclipse.org/mat/.

Memory Analyzer can be used to process HPROF binary Heap Dump files, IBM system Dump files (after processing), and IBM Portable Heap Dump S (PHD) files from various platforms. Memory Analyzer can visually view Heap Dump files:

  1. Object information: classes, member variables, direct quantities, and reference values;
  2. Class information Class loaders, names, superclasses, static members;
  3. Garbage Collections Roots Objects reachable by the JVM;
  4. Thread stack and local variables Information about thread stacks and details about local variables at the time the snapshot was taken.

1 download MAT

The official download address: www.eclipse.org/mat/downloa… .

Once the download is complete, unzip the file memoryAnalyzer.exe and open it to use.

2 Obtain the Dump file

Heap Dump files can be obtained in many ways, usually through parameter configurations that trigger Heap Dump under specific conditions, or through tools. There are two common commands:

  1. Add JVM parameters at startup-XX:+HeapDumpOnOutOfMemoryError, an HPROF binary Heap Dump file will be automatically dumped after a system OutOfMemoryError occurs.
  2. This configuration will save the snapshot in the project directory or tomcat directory, or through-XX:HeapDumpPath=/xxx/heapdump.hprof To display the specified path.
  3. The OnOutOfMemoryError parameter also allows the user to specify a script to perform some actions when OOM appears, such asAutomatically restart Tomcat:-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/xxx/heapdump.hprof -XX:OnOutOfMemoryError="sh ~/restart.sh"
  4. Using the jmap parameter,jmap -dump:[live,]format=b,file=<filename>, will immediately take a snapshot of the raw heap dump to the specified file at the specified location.

3 Write an incorrect program

We write a simple code that loops to create a UUID string concatenation and add it to a list:

public class TestJvmOOM {
    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            String str = "";
            for (int j = 0; j < 100; j++) {
                str += UUID.randomUUID().toString();
            }
            list.add(str);
        }
        System.out.println("ok"); }}Copy the code

4 Dump Heap Dump

Set up the launch parameters, maximum memory is 4 m, and automatic Dump Heap Dump: – Xms4m – Xmx4m – XX: + HeapDumpOnOutOfMemoryError, IDEA so Settings:

OOM is thrown soon after running the program, and the Heap Dump file is automatically generated:

The default location is under the project directory:

Let’s start analyzing!

4 use MAT

Double-click the memoryAnalyzer.exe file to open:

Open Heap selects a Heap Dump File by clicking On File, and we select the File we just generated.

Selecting the open schema, we select the first Leak Suspects Report schema, which analyzes memory leaks, and click Finish to type the Heap Dump file:

The meanings of common choices:

  1. Leak Suspects Report: Memory leak suspicious reporting, automatically checking heap dumps for suspected leaks, reporting which objects are saved and why they are not garbage collected,The most common pattern.
  2. Component ReportComponent reports that analyze a set of objects for suspected memory problems: duplicate strings, empty collections, finalizers, weak references, and so on.
  3. Re-open previously run reports: Opens previous run reports;

4.1 OverView View

The larger the Dump file is, the longer it takes to open it. The OverView interface is as follows. The OverView view shows the summary of the Dump file and some common functions of MAT:

  1. Details: displays statistics about the size of HeapDump, the number of classes, the number of objects, and the number of Class loaders.
  2. Biggest Objects by Retained Size: A pie chart that visually displays the largest objects in dump, to the left when the mouse cursor moves over an areaInspectorandAttributesDetailed information is displayed in the window. Left-click on the block to obtain more detailed information from the menu.
  3. Actions: Several commonly used operations, includingHistogram, Dominator Tree, Top Consumers, Duplicate Classes.
  4. Reports: lists common report information, including Leak SuspectsandTop Components.
  5. Step By Step: Step-by-step guide to the use of features in a wizard manner, includingComponent Report.

Let’s take a look at other commonly used features.

4.2 Histogram

Histogram, used to show the number of instances of each type, as well as shallow and retained size:

  1. shallow size: shallow heap, which represents the memory footprint of the object itself, including the memory footprint of the object itself, and memory used “for reference” by other objects.
  2. Shallow heap for non-array objects = object header + sum of the size of each member variable + aligned fill. Where, the sum of the size of each member variable is the instance data. If there is inheritance, the parent class member variable needs to be included
  3. Shallow heap for objects of array type = object head + type variable size * array length + alignment fill, four or eight bytes (64-bit system) for reference type, or one byte for Boolean type. Here the size of the type variable * the length of the array is the array instance data, emphasizing that the variable is not actually the object itself.
  4. Retained heap: deep heap, a statistical result that circulates the memory occupied by specific objects referenced. However, deep heap is a bit different from object size. Deep heap refers to the size of memory that can be freed after an object is garbage collected. These freed objects are called Retained sets.

4.2.1 Outgoing reference and Incoming Reference

When you right-click on any object, you see a drop-down menu. If you select the ListObjects menu item, you can view the outgoing and incoming references of the object.

The Incomming Reference refers to the object that references the current object, and the Outgoing Reference refers to the object that the current object references. The incomming reference of an object keeps the object alive from being garbage collected; The Outgoing Reference shows the specific contents inside the object, which helps us analyze the properties of the object.

Char [] Incomming Reference:

As you can see, they are almost all referenced by the value property of a String, which is actually our concatenated UUID String.

4.3 Dominator Tree Dominator Tree

List the largest objects that are still active in the Heap Dump. By default, we sort them by retained size, so it’s easy to find the most memory.

The first largest object is the one that consumes the most memory, and its children in the tree are all directly or indirectly referenced by that object (meaning that when that object is reclaimed, its children are reclaimed as well).

In our Heap Dump, it is obvious that the ArrayList occupies the largest memory. The elements in the dominating tree are all the concatenated UUID strings. This is why OOM is created.

4.4 Thread Overview Thread view

Click on the yellow gear above to view Thread Overview while the Heap Dump file is being generated. You can view the running status of the Thread and analyze the exceptions thrown by the Thread.

Outofmemoryerrors are clearly thrown by the main Thread in our Heap Dump:

4.5 Leak analysis report

MAT analyzes Heap Dump files and detects the possibility of memory leaks, such as one or a group of abnormally large objects. The Leak Suspects are useful for generating a memory Leak analysis report that will help us quickly locate the cause of OOM.

Thread Overview in Heap Dump: Thread Overview in Heap Dump: Thread Overview

As you can see, 66.79% of the memory is occupied by the Object[] array, so it is suspicious that there is a high probability of memory overflow. Click Details for Details:

You can see that the collection stores a large number of UUID strings. In fact, it tells us if this is the cause of memory overflow, as we can see at the bottom of the details:

It is the large object array (list collection uses the elements stored in the array), because it needs to allocate contiguous memory, and the memory is not enough to cause OOM.

At this point, the analysis is finished!

If you need to communicate, or the article is wrong, please leave a message directly. In addition, I hope to like, collect, pay attention to, I will continue to update a variety of Java learning blog!