You may already know that when an object is not referenced by other objects, it's eligiable for garbage collection. But do you know the following two statemenats are also true?
- "If an object obj1 is garbage collected, but another object obj2 contains a reference to it, then obj2 is also eligible for garbage collection"
- "If object obj2 can access object obj1 that is eligible for garbage collection, then obj2 is also eligible for garbage collection"
This is called "Island of Isolation". An "island of isolation" describes one or more objects have NO references to them from active parts of an application.
In When is an object eligible for garbage collection?, we talked about: any object, that are not accessible from root set of references, is eligible for garbage collection. If object obj1 is eligible for garbage collection meaning it is not reachable by any objects from root set of references. Then the garbage collection algorithm tries to find any objects that have ONLY refernce to object obj1 (in this case object obj2) which also become eligible for garbage collection.
If obj2 was accessible from root then the object obj1 would never be eligible for garbage collection in the first place. Therefore, it must be that the object obj2 cannot be referenced from the active part of the program, and so object obj2 is eligible for garbage collection.
Here is an example,
class Person { public Person firend; public static void main(String[] args) { Person obj1 = new Person(); Person obj2 = new Person(); obj2.firend = obj1; obj1 = null; //Line A obj2 = null; //Line B ..... } }
After Line A executes, The object obj2 still has a reference to the object obj1 and the object obj2 is still referenced by the variable obj2. Therefore, the object obj1 can not be eligable for garbage collection. After Line B exectues, there are no more references to the object obj2. There still is a reference to object obj1 inside the object obj2. Now, the object obj1 and obj2 has no reference from root set of references. Therefore, both of objects are eligible for garbage collection.
Comments
Post a Comment