Thursday, 17 March 2016

How we can make objects eligible for Garbage Collection when it is no longer needed ?


1. Set all available object references to null (once the purpose of creating the object is served)
String str = "Set the object ref to null";
// String object referenced by variable str is not eligible for GC yet
str = null;
// String object referenced by variable str becomes eligible for GC


2. Make the reference variable to refer to another object
Decouple the reference variable from the object and set it refer to another object, so the object which it was referring to before reassigning is eligible for Garbage Collection.
String str1 = "Garbage collected after use";
String str2 = "Another String";
System.out.println(str1);
// String object referred by str1 is not eligible for GC yet
str1 = str2;
/* Now the str1 variable referes to the String object "Another String" and the object "Garbage collected after use" is not referred by any variable and hence is eligible for GC */


3. Creating Islands of Isolation
If you have two instance reference variables which are referring to the instances of the same class, and these two reference variables refer to each other and the objects referred by these reference variables do not have any other valid reference then these two objects are said to form an Island of Isolation and are eligible for Garbage Collection.
GCTest3 gc1 = new GCTest3();
GCTest3 gc2 = new GCTest3();
gc1.g = gc2;   // gc1 refers to gc2
gc2.g = gc1;   // gc2 refers to gc1
gc1 = null;
gc2 = null;
// gc1 and gc2 refer to each other and have no other valid //references
// gc1 and gc2 form Island of Isolation
// gc1 and gc2 are eligible for Garbage collection here

No comments:

Post a Comment

Note: only a member of this blog may post a comment.