You need to enable JavaScript to run this app. 如何通过监控已用对象理解GC Root?附Java Monitor Used测试示例
优惠活动
大模型
产品
解决方案
定价
更多

如何通过监控已用对象理解GC Root?附Java Monitor Used测试示例

同步监视器(Monitor Used)作为GC Root的测试实现

测试目标

验证被用作synchronized同步锁的对象(即Monitor Used类型),是否属于GC Root范畴、能阻止关联对象被垃圾回收,配套测试代码、运行结果如下。

测试代码

1. 主测试类 GCRootMonitorUsed.java

package cn.jast.jvm.gcroot;

/**
 * Monitor Used - 用作同步监视器的对象
 * 测试场景:验证被synchronized持有的对象可作为GC Root
 * Created by jast90 on 2021/1/9
 */
public class GCRootMonitorUsed {
    // 每个BigClass实例占用约80M堆内存,方便观察回收效果
    BigClass bigClass = new BigClass();
    BigClass lock = new BigClass();

    public static void main(String[] args) {
        PrintMemoryUtil.printMemory();
        GCRootMonitorUsed gcRootMonitorUsed = new GCRootMonitorUsed();
        System.out.println("创建大对象实例后");
        PrintMemoryUtil.printMemory();

        // 第一次GC:此时lock还没被作为同步锁持有
        System.gc();
        System.out.println("第一次GC执行后");
        PrintMemoryUtil.printMemory();

        synchronized (gcRootMonitorUsed.lock){
            // 外部引用置空,观察锁对象关联的实例是否会被回收
            gcRootMonitorUsed = null;
            System.gc();
            System.out.println("进入同步代码块、外部引用置空后执行第二次GC");
            PrintMemoryUtil.printMemory();

            System.gc();
            System.out.println("第三次主动GC执行后");
            PrintMemoryUtil.printMemory();
        }
    }

    /**
     * 注意:BigClass需单独定义为独立的类文件,不要作为GCRootMonitorUsed的内部类
     * class BigClass{
     *     private int _10MB = 10 * 1024 * 1024;
     *     private byte[] memory = new byte[8 * _10MB];
     * }
     */
}

2. 内存打印工具类 PrintMemoryUtil.java

package cn.jast.jvm.gcroot;

/**
 * 堆内存打印工具
 * Created by jast90 on 2021/1/9
 */
public class PrintMemoryUtil {

    public static void printMemory(){
        System.out.println("当前空闲堆内存:" + Runtime.getRuntime().freeMemory()/1024/1024 + "M");
        System.out.println("当前JVM占用总堆内存:" + Runtime.getRuntime().totalMemory()/1024/1024 + "M");
    }
}

测试运行结果

当前空闲堆内存:120M
当前JVM占用总堆内存:123M
创建大对象实例后
当前空闲堆内存:40M
当前JVM占用总堆内存:203M
第一次GC执行后
当前空闲堆内存:42M
当前JVM占用总堆内存:203M
进入同步代码块、外部引用置空后执行第二次GC
当前空闲堆内存:42M
当前JVM占用总堆内存:203M
第三次主动GC执行后
当前空闲堆内存:42M
当前JVM占用总堆内存:203M

结果说明

  • 第一次主动GC时,lock对象尚未被作为同步监视器持有,因此仅回收了少量无引用关联的内存,可用内存从40M回升到42M。
  • 进入lock对象对应的synchronized代码块后,该对象被JVM标记为持有同步锁的监视器对象,本身属于GC Root类型。哪怕外部的gcRootMonitorUsed引用被置为null,与该锁对象关联的所有实例(包括同属GCRootMonitorUsed类实例下的bigClass大对象)都不会被GC回收,因此后续多次主动GC都无法释放这部分内存,可用内存始终稳定在42M。
  • 相关概念说明:被用作同步监视器的对象(Monitor Used)是JVM定义的标准GC Root类型之一,只要锁被持有,关联对象就始终处于可达状态。

内容的提问来源于stack exchange,提问作者user3940641

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 10:54:05