简体   繁体   English

JAVA:了解有多少对象符合 GC 条件

[英]JAVA : To know how many objects eligible for GC

There is a question in SCJP third chapter ... see the following code ... SCJP第三章有个问题……看下面的代码……

class Beta{

}

class Alpha extends  Beta{
    static Beta b1;
    Beta b2;
}

class Tester{
    public static void main(String a[]){
        Beta b1 = new Beta();
        Beta b2 = new Beta();

        Alpha a1 = new Alpha();
        Alpha a2 = new Alpha();


        a1.b1 = b1;
        a1.b2 = b1;
        a2.b2 = b2;

        a1 = null;
        b1 = null;
        b2 = null;

        //DO STUFF
        //HOW MANY OBJECTS ARE ELIGIBE FOR GC AT THIS LINE..

    }
}

Q : How are many objects are eligible for GC @ line //DO STUFF问:有多少对象符合 GC @ line //DO STUFF

Options :选项 :

Option-1> 0
Option-2> 1
Option-3> 2
Option-4> 3
Option-5> 4
Option-6> 5

Book says : The correct ansert is 2 : Only one object is eligible for GC.书上说:正确的答案是 2:只有一个对象符合 GC 的条件。

Still not able to understand this answer.仍然无法理解这个答案。 How only one object can be eligible for GC?如何只有一个对象有资格进行 GC?

Any Idea ??任何的想法 ?? Thanx,Gunjan.谢谢,Gunjan。

Probably because a2.b1 will still contain a reference to b1 because it is static.可能是因为a2.b1仍然会包含对b1的引用,因为它是静态的。 It also has a1.b2 referencing b2 .它还有a1.b2引用b2 So b1, b2 and a2 are very much alive.所以 b1、b2 和 a2 非常活跃。 Only a1 is eligible for garbage collection.只有a1有资格进行垃圾收集。

here ...a1.b1 or a2.b1 is static.这里 ...a1.b1 或 a2.b1 是静态的。 so it can not be GCed.所以它不能被GCed。 But a1 is eligible for GC because its not used.但是 a1 有资格进行 GC,因为它没有被使用。 And a2.b1 is pointing to b1.而 a2.b1 指向 b1。 So b1 can not be GCed.所以 b1 不能被 GCed。 We are nulling b2,so it can also be added into GC pipeline.我们正在清零 b2,因此它也可以添加到 GC 管道中。 So only two objects a1 and b2 are eligible for GC.所以只有两个对象 a1 和 b2 有资格进行 GC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM