1

Possible Duplicate:
Garbage Collection in Java and Circular References

Java runs it's garbage collector whenever there is not enough space in the memory . It does so by deleting the unreferenced objects. So what if an object has a pointer that points to itself ,or any cyclic pointing structure that always has a pointer to it ? Will the garbage collector fail or will it recognize any such insidious attempts made by us in order to make it fail ?

Community
  • 1
  • 1
Nikunj Banka
  • 11,117
  • 16
  • 74
  • 112
  • searching for an answer using the above question does not take you to the question that you just mentioned , or does it ? Anyway thanks for the link . – Nikunj Banka Jan 12 '13 at 03:05
  • What will happen is that this question will be closed, and then searches that hit this question will have a link to the earlier question. (Your question has not been downvoted, so you don't lose any rep points ...) – Stephen C Jan 12 '13 at 03:50

3 Answers3

2

The Java garbage collector will not reclaim any memory of objects that are pointed to by static or local variables, or by any objects linked (recursively) from those objects. Thus if you have large linked trees of objects, the garbage collector will not reclaim that space if there is a variable pointing to any root of a tree or loop.

The memory for objects linked in a loop will be reclaimed as long as there is no static or local variable pointing to an object in the loop. Thus if you want garbage collection to work efficiently, be sure to null out variables when the objects are no longer needed.

The garbage collector does detect, and does not care, if objects are linked in cyclic ways. The only thing that matters with whether the object can be reached from a variable.

AgilePro
  • 5,588
  • 4
  • 33
  • 56
2

"A references object B and B references A" is called an island of isolation. GC is smart enough to detect such things. If there is no reference to any object in an island the whole island is eligible for garbage collection

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

Whether the objects will be collected depends on the Garbage collecting algorithm

  • reference-counting GC, will not collect cyclic references
  • but, modern GC algorithms usually decide eligibility of an object for collection by traversing the heap starting from the root set.

Garbage collector will collect objects that are not accessible from the root set of references (current local variables, static references, operand stacks of stack frames). This means that even objects that are referenced by some other objects can still be collected.

Therefore, your cyclic-pointer structure will get collected even though each object is referenced iff there is no other reference path going transitively from the root set to the objects forming the cycle.

See also What triggers the Java Garbage Collector.

Community
  • 1
  • 1
Aleš
  • 8,896
  • 8
  • 62
  • 107