Search code examples
javagarbage-collectionjvm

how to understand GC Root by Monitor Used Object?


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


Solution

  • From your own reference:

    enter image description here

    Assuming that reference is correct, I would interpret it as:

    synchronized(obj) {
      // obj used as monitor
    }
    // obj free to collect