java - 垃圾收集器意外输出

标签 java garbage-collection runtime output println

我不明白这里发生了什么

public class UnderstandGC {
public class Inner1
{
    String name=new Inner2().name;
    public void finalize()
    {
        System.out.println("Inner1 -> I am Dead");
    }
}
public class Inner2
{
    public String name="Inner2";
    public void finalize()
    {
        System.out.println("Inner2 -> I am Dead");
    }
}
public void finalize()
{
    System.out.println("Main -> I am Dead");
}
    public static void main(String[] args) {
        UnderstandGC ugc=new UnderstandGC();
Inner1 inner1=ugc.new Inner1();
//System.out.println("hello");      //1

Runtime.getRuntime().gc();         


    }
}

预期输出: Inner2 -> I am Dead 在 Inner1 中实例化为字段引用的 Inner2 的 bcoz 对象没有来自主线程运行时堆栈的本地引用。

观察到的输出:

有趣的观察是,如果我在代码中包含注释 //1 ,它就可以正常工作。无法理解发生了什么。

最佳答案

gc() method javadoc

Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse.

无法保证在任何一种情况下都会运行 GC。

关于java - 垃圾收集器意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23859803/

相关文章:

java - 如何将字符串矩阵格式化为 x 行和 y 列

java - 如何为Azure Function TimerTrigger实现单元测试

java - 如何重用或确保一次只存在一个 JasperViewer?

java - 为什么使用 Docker 时会出现 OOM?

c# - 自处理事件是否会阻止实例被垃圾收集?

java - 在eclipse运行时错误中运行android项目时出错

c# - 需要解决方法 : notify a user that exe is missing dependencies from within the application?

java - 如何使用 XPath 设置空值?

java - 使用自动装箱的内存泄漏

c++ - 如何从动态加载库中执行未知函数?