What are the different ways to make an object eligible for Garbage Collection when it is no longer needed?
1.Set all available object references to null if the purpose of creating object completed.
e.g.
String obj1 = "Hello World"; //1
obj1 = null; //2
Memory allocated by obj1 at line1 is eligible for Garbage Collections
after line 2.
2. Make the reference variable to refer to another object
e.g.
String obj1 = "Hello World"; // 1
String obj2 = "Hi How are you"; // 2
obj2=obj1; // 3
Now after line 3, the reference variable obj2 will refer to the String object "Hello World" and the object "Hi How are you" is not referred by any variable and hence eligible for Garbage Collection.
3. Creating Islands of Isolation -
e.g.
class Example{
Example example;
public static void main(String args[]){
Example obj1 = new Example();
Example obj2 = new Example();
obj1.example = obj2;
obj2.example = obj1;
obj1 = null; // 1
obj2 = null; // 2
}
}
Will object allocated by obj1 eligible for Garbage collection after line1?
No, Only after line2 both objects are eligible for Garbage collection.
e.g.
String obj1 = "Hello World"; //1
obj1 = null; //2
Memory allocated by obj1 at line1 is eligible for Garbage Collections
after line 2.
2. Make the reference variable to refer to another object
e.g.
String obj1 = "Hello World"; // 1
String obj2 = "Hi How are you"; // 2
obj2=obj1; // 3
Now after line 3, the reference variable obj2 will refer to the String object "Hello World" and the object "Hi How are you" is not referred by any variable and hence eligible for Garbage Collection.
3. Creating Islands of Isolation -
e.g.
class Example{
Example example;
public static void main(String args[]){
Example obj1 = new Example();
Example obj2 = new Example();
obj1.example = obj2;
obj2.example = obj1;
obj1 = null; // 1
obj2 = null; // 2
}
}
Will object allocated by obj1 eligible for Garbage collection after line1?
No, Only after line2 both objects are eligible for Garbage collection.
Comments
Post a Comment