Java memory overflow OOM using Mat analysis

Example

package com.rumenz;

import java.util.ArrayList;
import java.util.List;

public class OutOfMemory {

    public static void main(String[] args) {
         List<UserTest> res=new ArrayList<>();
         while (true){
             res.add(new UserTest());
         }
    }
}

class UserTest{

}

VM add parameters

-Xms20m -Xmx20m

Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at com.rumenz.OutOfMemory.main(OutOfMemory.java:11)

Explanation:

The heap memory size of the JVM controlled by the VM parameter is only 20m. The program keeps creating objects, and the objects allocate memory on the heap. They keep adding objects to the List without garbage collection, resulting in heap memory overflow (OutOfMemoryError) .

Mat tool analysis heap

1. Download Mat analysis software: https://www.eclipse.org/mat/d...

2. Add the VM parameter: -XX:+HeapDumpOnOutOfMemoryError to open the heap memory overflow and export the heap memory to the file, the default is in the root directory of the project. If you need to specify other paths with -XX:HeapDumpPath=/tmp, a similar name will be generated java_pid28790.hprof file.

3. Use Mat to open the hprof file

Java memory overflow OOM using Mat analysis

java.lang.Object[14053] Meaning:

List is essentially an Object[] array, and 14053 is the number of objects stored in it.

  • Shallow Heap (shallow heap) means: the actual heap size occupied by the object (not including the size of other referenced objects)
  • Retained Heap means: the actual occupation of the object + the size of the referenced object contained

Shallow Heap calculation method

In this case: Shallow Heap occupies 112448 bytes, and Retained Heap occupies 337296 bytes.

List res=new ArrayList<>(); res is a local variable, memory is allocated on the stack, res stores the heap memory address (reference) of the UserTest instance object, and pointer compression is turned on in JDK1.8 (-XX:+UseCompressedOops ), in the 64-bit system, the reference takes up 4 bytes, and the reference pointer in the 64-bit system without pointer compression takes up 8 bytes.

当前案例未打开指针压缩:
14053个引用地址占用内存大小: `14053*8=112424`,`Shallow Heap`占用`112448`字节,还有24字节明显就是res容器本身占用的内存大小.

Array shallow heap occupies memory calculation:

16 bytes of overhead 对象的头
4 bytes length 存储容器长度
4 bytes padding 字节对其

16 bytes of overhead + 4 bytes length + 4 bytes padding = 24 bytes

Retained Heap calculation method

Retained Heap Size=Shallow Heap Size+The actual size of the referenced object

Shallow Heap has been calculated

The actual size of the referenced object: In this case, since UserTest is an empty object, each UserTest instance object only occupies 16 bytes of object header. There are 14053 instance objects in total, so a total of 14053*17=224848 is occupied.

Retained Heap=112424+224848=337296和Mat分析的结果一致.

Guess you like

Origin blog.csdn.net/qwe123147369/article/details/109111987