views:

53

answers:

3
class Stage
{

  Actor act1 = new Actor(); 
  Actor act2 = new Actor();
  Actor act3 = new Actor();

}

Stage stg = new Stage();

how will garbage collection behave in java this scenario?

stg = null;

will the three objects created act1,act2 and act3 also get garbage collected?

A: 

When the reference count for each object is 0, the GC will collect them all.

Davide Vosti
+1  A: 

Yes.

When the garbage collector runs, it will see references to the old object are gone, and clean it up. The next time it runs, it will see that now nothing refers to the other three objects, and clean them up too.

Conceptually, anyway; I'm sure most garbage collectors will be a little smarter than that in practice and get them in one pass. The exact mechanism will vary.

Chris Arguin
so that means i dont need to specifically set the inner objects to null. they will automatically handeled.Thanks
krisp
As per C#. Setting an object to null will prolong the time taken for it to clear.
Ganesh R.
A: 

They will be garbage collection if there is no more reference to it. Do not forget to remove attached EventListener from outside because they also count as a reference (as long as you are not using weak-reference).

Hippo