进阶学习(4.4) JVM GC Root 判定, 垃圾的判定

要学JVM 垃圾回收机制, 必须先知道什么是GCRoots,根节点, 常见有

  • 类静态字段
  • 常量
  • 静态代码块
  • 第一栈变量, 网上没有案例说明, 都是复制粘贴的也没说清楚什么是Root
  • 虚拟机栈

 

1, 先产生一个垃圾对象

这里解释第一栈变量, 理解为就是main 方法中, 中的变量,

public static void main(String[] args) {
        // Root Var
        User userA = new User();
        userA.setName("GC Root A");
        User userB = new User();
        userB.setName("GC Root B");

        {
            User userC = new User();
            userC.setName("GC Root C");
        }

        f1();

        while (true) {
            userA.hashCode();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void f1() {
        User NodeA = new User();
        NodeA.setName("Node A");
    }
}
  1.   A B C 都被判定成GC Root
  2.  而 Node A 因为没有与 根变量 关联所以被判断成了垃圾
  3.  通过JVVM 工具我们可以看到三个变量都活下来了, 而Node A 不属于第一栈帧, 没有找到GC Root, 被标记为垃圾GG了

进阶学习(4.4) JVM GC Root 判定, 垃圾的判定_第1张图片

 

2, 产生一个非垃圾对象

  1. 找到原因就可以把 Node A 变成非垃圾对象了, 只需要能在 root 节点中能找到 Node A 就OK 了
  2. 一定要记住的是, 是通过 root 能找到 Node A, 而不是Node A 找到 root, 否则他还是一个垃圾
  3. 我们修改后, User.save 方法是 User 里面有一个map 对象, 也就是root 节点存储了 Node A, 所以 Node A 现在可以被root 节点标记了, 它就不是一个垃圾了
public static void main(String[] args) {
        // Root Var
        User userA = new User();
        userA.setName("GC Root A");
        User userB = new User();
        userB.setName("GC Root B");

        {
            User userC = new User();
            userC.setName("GC Root C");
        }

        f1(userB);

        while (true) {
            userA.hashCode();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void f1(User root) {
        User NodeA = new User();
        NodeA.setName(root.getName() + ", Child Node A");
        root.save(NodeA);
    }

进阶学习(4.4) JVM GC Root 判定, 垃圾的判定_第2张图片

可以看到 Node A 活下来了

你可能感兴趣的:(JVM,学习资料,JAVA,jvm)