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
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.
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.
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.
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.
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 :
See this documentation (§ A.3.4 Unreachable and §A.4.2 Example GC with WeakReference)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With