my thought is that here a is an instance variable of object a1 so when a1=null then a1.a also null

Not really, when a1 is set to null, a is not set to null. But since a is reachable only through a1, the GC decides that "since a1 is not reachable , no other object can access a1.a. Which implies that the object created at line 1 is not reachable. so it deletes the object."

SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !

a1 will not be garbage collected because till a reference is pointing to and Onject instance in memory or pointing to null object i will not eligible for GC. only when any new instance of a class is created and not reffered or pointed by any ref var , it will be GC.

example: A a1 = null; // it will be eligible for GC but not gauranteed ti be GC immediately so it will Gc when exits the pgm. B b1 = new B(); // will not be GC coz pointing to null object. new B(); //will be GC coz it is not reffered by any ref var. [ December 29, 2008: Message edited by: Ashika Chhabda ]

The issue here is that after line 2 there are 2 objects on the heap: a1.a and a1.

If a1 is set to null, a1.a still continues to point to an object.

My understanding is that an object is eligible for garbage collection if it is "unreachable". What does "unreachable" mean here? As a programmer I can't reach a1.a after line 3 because I'll get an NPE, so from my point of view a1.a is unreachable. So you could say both a1 and a1.a are unreachable and eligible for gc (2 objects are eligible after line 3).

However according to Khalid and Mungal, "an object in the heap is said to be reachable if it is denoted by any local reference in a runtime stack". So though we as programmers can't reach it, there's still a local reference to a1.a, so unless that is explicitly set to null, it is still reachable and not eligible for gc (1 object eligible after line 3).

Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952

posted Dec 29, 2008 08:05:00

0

My understanding is that an object is eligible for garbage collection if it is "unreachable". What does "unreachable" mean here? As a programmer I can't reach a1.a after line 3 because I'll get an NPE, so from my point of view a1.a is unreachable. So you could say both a1 and a1.a are unreachable and eligible for gc (2 objects are eligible after line 3).

No no you are going on wrong track. First of all remember a1 and a1.a are not objects, they are just a reference to an object. Here a1 and a1.a both referencing to same object that was created on line 1.

A a1=new A();=====================LINE1

So question is here, if you are creating just one object on the heap, how the GC will collect two objects from the heap?