InterviewSolution
Saved Bookmarks
| 1. |
What are the possible ways of making object eligible for garbage collection (GC) in Java? |
|
Answer» FIRST Approach: Set the object references to null once the object creation purpose is served. PUBLIC class IBGarbageCollect { public static void main (String [] args){ String s1 = "Some String"; // s1 referencing String object - not yet eligible for GC s1 = null; // now s1 is eligible for GC } }Second Approach: Point the reference variable to another object. Doing this, the object which the reference variable was referencing before becomes eligible for GC. public class IBGarbageCollect { public static void main(String [] args){ String s1 = "To Garbage Collect"; String s2 = "Another Object"; System.out.println(s1); // s1 is not yet eligible for GC s1 = s2; // Point s1 to other object pointed by s2 /* Here, the string object having the content "To Garbage Collect" is not REFERRED by any reference variable. Therefore, it is eligible for GC */ }}Third Approach: Island of Isolation Approach: When 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an “Island of Isolation” and these 2 objects are eligible for GC. public class IBGarbageCollect { IBGarbageCollect ib; public static void main(String [] STR){ IBGarbageCollect ibgc1 = new IBGarbageCollect(); IBGarbageCollect ibgc2 = new IBGarbageCollect(); ibgc1.ib = ibgc2; //ibgc1 points to ibgc2 ibgc2.ib = ibgc1; //ibgc2 points to ibgc1 ibgc1 = null; ibgc2 = null; /* * We see that ibgc1 and ibgc2 objects refer * to only each other and have no VALID * references- these 2 objects for island of isolcation - eligible for GC */ }} |
|