JVM memory leak investigation (visual vm)


JVM memory leak investigation (visual vm)

 

Memory leak: The end of the object usage, the memory space occupied by the object is not recycled during garbage collection

Cause: The object is referenced by long-lived variables, such as static variables

Consequences: If a large number of objects are used but cannot be recycled, it may cause a memory overflow (cannot allocate memory for new objects)

 

 

***************************

Examples

 

class MyObject{

    private int _1m=1024*1024;
    private byte[] b;

    public MyObject(){
        this.b=new byte[_1m];
    }
}

public class Test11 {

    private static List<MyObject> list=new ArrayList<>();

    public static void main(String[] args) throws Exception {
        for (int i=0;i<1000;i++){
            list.add(new MyObject());
            System.out.println("add "+i);

            try{
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        System.out.println(list);
    }
}

Note: The objects created in the loop body are added to the list. The list is a global variable, and the object will not be released after the method line ends, causing memory leak

 

********************

Console output

 

Virtual machine parameters: -Xms500m -Xmx500m

。。。
add 240
add 241
add 242
add 243
add 244
add 245
add 246
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at runtime.MyObject.<init>(Test11.java:12)
	at runtime.Test11.main(Test11.java:22)

Description: The object myObject created in the loop cannot be released, causing memory overflow

 

 

***************************

Visual vm memory leak investigation

 

visual gc tags

      

      

During the operation before and after, the space used by the old generation gradually increased, and eventually the memory overflowed, judging that it may cause a memory leak

 

sampler: heap dump, execute heap dump again after a while

      

 

Comparison of two heap dumps before and after

      

      

Comparison found that MyObject objects increased significantly

 

myObject ==》 open in new tab

       

 

myObject references

      

Memory leak objects are in the arrayList linked list

 

 

Published 387 original articles · Like 98 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_43931625/article/details/105241467