views:

83

answers:

2

I have a composite object (tree) with parent-child relationships.The tree can be upto n levels (say for e.g 10-12 levels)

Now suppose i have to remove an object at level 6 in the hierarchy.If i point its reference to null (while leaving the child object untouched) in Java then what happens to the child objects under it (do they become available for garbage collection).

A: 

Only if you set the object itself to null, or it goes out of scope.

Gandalf
That's wrong. You can't set "object itself to null", you can only set its reference; and it's the reference that can go out of scope. Neither of those events makes object eligible for GC; there can be other references to it.
ChssPly76
Thanks for the semantics lesson - last time I checked Object o = null worked.
Gandalf
Really? `Object o1 = new Object(); Object o2 = o1; o1 = null;`. Will that work? Do you still think it's just semantics?
ChssPly76
Yes actually I do, since you immediately knew exactly what the statement meant.
Gandalf
+2  A: 

The child objects will get picked up by garbage collection if the reference the parent had was the only live reference to the child object in the entire application.

NickDK
That's not entirely true. First of all, they'll become **eligible** for garbage collection - there's no telling **when** and **if** they'll actually be garbage collected. Secondly, you can very well have other references to the child object and still have it eligible for GC - the key is said references should be **unreachable**.
ChssPly76
True about the eligible part, not that it matters much from a developers pov since it is as far as you can ever make garbage collection happen yourself. Also true about the unreachable part but thats why I called it a "live" reference ;-).
NickDK
Fair enough. "Live" could be misconstrued as "not null", that's why I commented.
ChssPly76