简体   繁体   中英

Number of objects eligible for garbage collection

I am not sure if I have understood the behaviour of garbage collector completely, therefore I am posing this question based on a previous question .

In this program:

class A {
    Boolean b;
    A easyMethod(A a){
       return new A();
    }
    public static void main(String [] args){
        A a1 = new A();
        A a2 = new A();
        A a3 = new A();
        a3 = a1.easyMethod(a2);
        a1 = null;
        // Some other code 
    }
} 

how many objects would be eligible for garbage collection? I think that although a3 never becomes null, the first object ( new A() ) assigned to it should also be garbage-collected, as no references still point to it. Am I right? I think hence that the correct answer would be again 2 objects. What is true actually?

I think that although a3 never becomes null, the first object ( new A() ) assigned to it should also be garbage-collected, as no references still point to it. Am I right? I think hence that the correct answer would be again 2 objects.

Yes, this is exactly right. a3 originally points to one instance of A , but after that variable is reassigned to point to a different instance, there is no longer any way to reach the original instance, so said original instance becomes eligible for garbage collection.

Yes, you are right.

a1 = <instance 1>
a2 = <instance 2>
a3 = <instance 3>
a3 = <instance 4> //as a returned value
a1 = null

So instance 1 and instance 3 are no longer referenced and thus may be collected.

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