arjacsoh
arjacsoh

Reputation: 9232

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?

Upvotes: 0

Views: 218

Answers (2)

Tim Bender
Tim Bender

Reputation: 20442

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.

Upvotes: 2

ruakh
ruakh

Reputation: 183311

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.

Upvotes: 2

Related Questions