Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 635
Jacky Avatar asked Jun 02 '12 09:06

Jacky


People also ask

How can you make sure an object is garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object? The new operator dynamically allocates memory for an object and returns a reference to it.

Can two objects reference each other?

Of course you can have objects reference each other. You could simply pass the this pointer in both objects to each other, which is perfectly valid.

Which is not valid reference in terms of garbage collection?

Any object with at least one strong reference is not eligible for garbage collection. In our analogy, prefects hold strong references to their plates. In technical terms, we say the object is strongly reachable.

Can multiple object variables contain references to the same object?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.


2 Answers

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)

like image 52
alain.janinm Avatar answered Oct 19 '22 08:10

alain.janinm


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.

like image 4
Juvanis Avatar answered Oct 19 '22 09:10

Juvanis