简体   繁体   中英

JAVA : To know how many objects eligible for GC

There is a question in SCJP third chapter ... see the following code ...

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

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.

Still not able to understand this answer. How only one object can be eligible for GC?

Any Idea ?? Thanx,Gunjan.

Probably because a2.b1 will still contain a reference to b1 because it is static. It also has a1.b2 referencing b2 . So b1, b2 and a2 are very much alive. Only a1 is eligible for garbage collection.

here ...a1.b1 or a2.b1 is static. so it can not be GCed. But a1 is eligible for GC because its not used. And a2.b1 is pointing to b1. So b1 can not be GCed. We are nulling b2,so it can also be added into GC pipeline. So only two objects a1 and b2 are eligible for GC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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