Friday, July 17, 2009

Note on Garbage collection of circular references.

Question:
=========
I have 2 objects; A and B.
A has a reference to B and B has a reference to A.
If A and B are not referenced by any other objects are they eligible for garbage collection?

Answer:
=======
Yes, they will be collected.* Most people think the GC uses reference counting to keep track of referenced objects. In that case, A and B would both have a non-zero reference count and not be collected. Sun's JVM (1.1.x, 1.2) uses a mark-and-sweep algorithm (and I think most others do as well). It starts at a base point (I can't remember off hand what the base point is, it's something like all runnable thread classes) and starts following the references from there (like walking a tree). If something s reachable from a base point it is noted as such. After walking through all references, those not marked as reachable are removed. Since neither A nor B is reachable from the root, they will be removed.
Note that 1.2 introducted concepts such as strong references, weak references, and phantom references. 1.3 has a significantly more complex GC. In all cases however, the above more or less holds true. Sun hs documentation on the new refernce types as well as the HotSpot GC.
*The GC is obviously different in each JVM, but all JVMs I know of can handle this case correctly. There may be some that don't.

Reference:
==========
http://www.coderanch.com/t/322042/Java-General-advanced/java/Garbage-collection-circular-references

No comments: