If Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then are they eligible for GC?
Asked
Active
Viewed 101 times
1
-
http://stackoverflow.com/questions/1910194/garbage-collection-in-java-and-circular-references – NPE Aug 20 '13 at 12:49
2 Answers
3
Yes. Garbage collection of objects in Java can occur if the objects are not reachable. It isn't affected by circular references.
One definition of reachability is provided by the package documentation for java.lang.ref:
Going from strongest to weakest, the different levels of reachability reflect the life cycle of an object. They are operationally defined as follows:
- An object is strongly reachable if it can be reached by some thread without traversing any reference objects. A newly-created object is strongly reachable by the thread that created it. An object is softly reachable if it is not strongly reachable but can be reached by traversing a soft reference.
- An object is weakly reachable if it is neither strongly nor softly reachable but can be reached by traversing a weak reference. When the weak references to a weakly-reachable object are cleared, the object becomes eligible for finalization.
- An object is phantom reachable if it is neither strongly, softly, nor weakly reachable, it has been finalized, and some phantom reference refers to it.
- Finally, an object is unreachable, and therefore eligible for reclamation, when it is not reachable in any of the above ways.

Andy Thomas
- 84,978
- 11
- 107
- 151
0
Java's GC considers objects "garbage" if they aren't reachable through a chain starting at a garbage collection root, so these objects will be collected. Even though objects may point to each other to form a cycle, they're still garbage if they're cut off from the root.

Ashish Chaurasia
- 1,747
- 17
- 23