Garbage collection
Eligibility for garbage collection
An object is eligible for garbage collection when no live thread can access it.
An object can become eligible for garbage collection in different ways:
- If the reference variable that refers to the object is set to null, the object becomes eligible for garbage collection, provided that no other reference is referring to it.
- If the reference variable that refers to the object is made to refer to some other object, the object becomes eligible for garbage collection, provided that no other reference is referring to it.
- Objects created locally in a method are eligible for garbage collection when the method returns, unless they are exported out of the method (that is, returned or thrown as an exception).
- Objects that refer to each other can still be eligible for garbage collection if no live thread can access either of them.
Consider the following example:
public class TestGC
{
public static void main(String [] args)
{
Object o1 = new Integer(3); // Line 1
Object o2 = new String("Tutorial"); // Line 2
o1 = o2; // Line 3
o2 = null; // Line 4
// Rest of the code here
}
}
In this example, the Integer object initially referred to by the reference o1 becomes eligible for garbage collection after line 3. This is because o1 now refers to the String object. Even though o2 is now made to refer to null, the String object is not eligible for garbage collection because o1 refers to it.
1 comment: