Jacky
Jacky

Reputation: 8935

Will GC collect object a and b if they only have reference to each other?

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

Upvotes: 6

Views: 204

Answers (2)

alain.janinm
alain.janinm

Reputation: 20065

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)

Upvotes: 6

Juvanis
Juvanis

Reputation: 25950

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.

Upvotes: 4

Related Questions