这个对象不应该被垃圾收集吗? [英] Shouldn't this object be garbage collected ?

查看:61
本文介绍了这个对象不应该被垃圾收集吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中学到如果一个对象没有对它的任何引用,它将被自动垃圾收集,但为什么下面的对象工作正常并且没有任何引用它,不应该是垃圾集?

i learned in Java that if an object doesn't have any reference to it, it will be garbage collected automatically, but why the object below works fine and doesn't have any reference to it, shouldn't it be garbage collected?

public class Main {

    public static void main(String[] args) {
	new A().show();
    }
}


class A{
    void show(){
        System.out.println("Java");
    }
}





我的尝试:



没有什么可以尝试的!



What I have tried:

there was nothing i could try!

推荐答案

为什么当你的应用程序退出时会调用垃圾收集器?只需将所有内存作为一个整体释放而不必担心处理每个单独的对象 - 应用程序即将死亡,所以只需将所有已分配的内存释放回系统,这是一个更容易的负载。



并且要记住垃圾收集器不会立即启动任何超出范围的东西 - 它会等到它实际需要或系统处于空闲状态才开始检查是否有任何可释放的东西。在您的示例中,系统永远不会闲置,直到应用程序退出,到那个阶段,GC开始工作为时已晚!
Why would a garbage collector be called in when your app exits? It's a load easier to just release all memory as a lump without worrying about disposing of each individual object - the app is dying, so just release all allocated memory back to the system instead.

And do remember that the garbage collector doesn't fire up immediately anything goes out of scope - it will wait until it's actually needed or the system is idle before it starts checking to see if anything is releasable. In your example the system is never idle until the app exits, and by that stage, it's too late for the GC to start work!


这篇关于这个对象不应该被垃圾收集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆