I want test for Monitor Used
Object as GC root ,code just like as follow
package cn.jast.jvm.gcroot;
/**
* Monitor Used - objects used as a monitor for synchronization
*
* Created by jast90 on 2021/1/9
*/
public class GCRootMonitorUsed {
BigClass bigClass = new BigClass();
BigClass lock = new BigClass();
public static void main(String[] args) {
PrintMemoryUtil.printMemory();
GCRootMonitorUsed gcRootMonitorUsed = new GCRootMonitorUsed();
System.out.println("after create big class");
PrintMemoryUtil.printMemory();
System.gc();
System.out.println("first gc");
PrintMemoryUtil.printMemory();
synchronized (gcRootMonitorUsed.lock){
gcRootMonitorUsed = null;
System.gc();
System.out.println("second gc");
PrintMemoryUtil.printMemory();
System.gc();
System.out.println("third gc");
PrintMemoryUtil.printMemory();
}
}
/*
// move to a java file as not inner class
class BigClass{
private int _10MB = 10 * 1024 * 1024;
private byte[] memory = new byte[8 * _10MB];
}*/
}
package cn.jast.jvm.gcroot;
/**
* Created by jast90 on 2021/1/9
*/
public class PrintMemoryUtil {
public static void printMemory(){
System.out.println("free is :"+Runtime.getRuntime().freeMemory()/1024/1024 + "M");
System.out.println("total is :"+Runtime.getRuntime().totalMemory()/1024/1024 + "M");
}
}
and a result is:
free is :120M
total is :123M
after create big class
free is :40M
total is :203M
first gc
free is :42M
total is :203M
second gc
free is :42M
total is :203M
third gc
free is :42M
total is :203M
reference
question from:
https://stackoverflow.com/questions/65640706/how-to-understand-gc-root-by-monitor-used-object 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…