Will GC collect object a and b if they only have r

2019-06-22 05:55发布

问题:

Will GC collect object a and b if they only have reference to each other? Can you help explain the reason or give a referece doc to explain that logic. Thanks much

回答1:

Yes they will be candidate to GC if no more strong references to it exist.

It's important to note that not just any strong reference will hold an object in memory. These must be references that chain from a garbage collection root. GC roots are a special class of variable that includes :

  • Temporary variables on the stack (of any thread)
  • Static variables (from any class)
  • Special references from JNI native code

See this documentation (§ A.3.4 Unreachable and §A.4.2 Example GC with WeakReference)



回答2:

If objects a and b referencing each other and are not interfering the other objects, they form an isolated island of objects. This kind of groups are also collected by the garbage collector. Take a look at this thread.