Reputation: 9262
How many objects are eligible for garbage collection when the main method of the Tester class reaches its end? My impression is that the answer is two, particularly a1, b1. However I have found somewhere as corect answer, that only a1 object is eligible. I think that since we have not asigned b1 as member variable in a2 an b1 is assigned to null before main ends, it should be collected by garbage collector. What is true?
class B {
}
class A {
static B b1;
B b2;
}
public class Tester {
public static void main(String[] args) {
B b1 = new B();
B b2 = new B();
A a1 = new A();
A a2 = new A();
a1.b1 = b1;
a1.b2 = b1;
a2.b2 = b2;
a1 = null;
b1 = null;
b2 = null;
}
}
Upvotes: 1
Views: 219
Reputation: 31206
well the only reference that you haven't nullified is a2
. your answer will be whatever objects that you can't trace to from a2
so you have a2
, and b2
is referenced by a2.b2
a1
and (in the scope of your main
method) can't, and are therefore garbage collected.
actaually, affe is right, b1
is static, and is therefore reachable.
Upvotes: 0
Reputation: 4650
a2
- since it was not nullifiedb2
(the original object assigned to b2
) - since it is held by a2b1
(the original object assigned to b1
) - since it's held in a static
variableUpvotes: 0
Reputation: 47994
The object initially assigned to the method scope variable b1
is not eligible for collection because the reference to it in Class A
is static. It does not expire with that particular instance of a1. It is a sneaky bit of wonky java syntax that a1.b1
and A.b1
are the same reference, but it is what it is. That reference remains live until the class A is un-loaded/the JVM exists, regardless of what happens to any instance of A such as a1.
The code assigns the pointer b1
in the method to null, but it does not assign A.b1
to null.
Upvotes: 2