This was taken from Mugal: "If an object obj1 can access an object obj2 that is eligible for garbage collection, then obj1 is also eligible for garbage collection". The explanation states: "An object is only eligible for garbage collection if the only references to the object are from other objects that are also eligible for garbage collection", which doesn't really explain much. Any thoughts? thanks to all
The concept here is one of "circular references." Take a look at the following code:
As you can see from this code, the class CircRef contains a reference to an object of type CircRef. In the main method, I create two objects of type CircRef and have them reference eaach other. Now, the question is, after the try block completes (and the CircRef objects are out of scope), are they eligible for garbage collection? In order to answer that, you might want to count the number of references to an object. If that count is 0, the object is eligible for garbage collection. However, both objects reference each other so, even after the try block completes and the variables one and two are out of scope, the reference count for each object is 1, not 0. However, you don't want to look at just total references, you want to look at total references from an active part of the application. Since there are no references to either object from an active part of the application, both are available for garbage collection. Now, to get back to your initial question, let's look at the object originally referenced by the variable "two". This object is referenced only by an object that is available for garbage collection so, it too, is available for garbage collection. However, if we modify the code slightly...
In this case, when the try block completes, the variable "one" is not out of scope. Therefore, the object it references is not eligible for garbage collection as it is still referenced from an active part of the application. Since the object referenced by "one" also references the object originally referenced by "two", that object is not eligible for garbage collection, either. I hope this makes sense. I feel like I got awfully carried away on a pretty simple question. If you have more questions, please let me know. Corey