How to make object eligible for garbage collection

Dear Friends,

In this tutorial I would try to explain what is garbage collection in Java and How to make objects eligible for Garbage collection.

In the language like C, a programmer need to manually do the memory management himself/herself by allocating memory programmatically and then de-allocating memory programmatically, but Java provides automatic memory management facility, wherein a programmer need not take care of allocating/de-allocating memory, but there is utility which is part of JVM which do it for programmer automatically and we call is as Mr. Garbage Collector. Don't go on its name, it's a big guy actually, which does pretty decent job for programmer :)




What is Garbage collection ?

To answer this question in simple way ,lets take literal meaning of  "Garbage". So basically any waste material which we want to throw away, we call it as Garbage, as we know that it is unnecessarily taking some space in our house and is of no use to us.

In Java, all the objects reside in the heap and if we want to use/refer these objects in our program ,we should have some reference to refer to these objects. If we don't have any reference to these objects then there is no way these objects can be accessed.

So the objects which do not have any reference left to access them are of no use and are like just waste material and can be thrown away. Here comes Mr. Garbage Collector, which is a part of JVM. This guy is like a municipality guy who comes and collect Garbage but it follows some standard mechanisms to do this, which we call algorithms. So what this Garbage collector will do it will check for all such eligible objects which can not be accessed and remove them from memory(heap) ,so that , that unnecessarily occupied space by these objects can be freed and can be re-sued by some new objects.

Various ways  to make object eligible for garbage collection

Now as we have understood what is garbage collection ,lets try to understand what are the various ways an object can be made eligible for Garbage collection. Note the term "eligible". we are not saying that by following the below ways, objects are actually getting garbage collected ,but we are making them only eligible for Garbage collection, such that when ever next time garbage collector will run, it will remove these objects from memory.

As an example,if we have some waste stuff at home,we will throw it to some box outside placed by municipality,such that this waste or garbage is eligible to be collected by municipality(Garbage Collector).So by putting the waste stuff in a box,we are just making it eligible for garbage collector to collect,such that whenever next time municipality guys(Garbage collector) will come,they will remove the garbage.

1) By nullifying a reference to object

Here is how we create an object normally using new operator.
Employee emp = new Employee();




When above line of code is executed, memory is allocated in heap for this object and "emp"     reference can be used to access this object.

Now ,if we assign this emp a null, then the object this emp was referring to ,could not be accessed any more and hence is eligible for garbage collection.
emp = null;




2) By reassigning reference variable to some other object

Lets create object using new operator :
Employee emp1 = new Employee();



Now say we create another object 
Employee emp2 = new Employee();



At this moment first object is being referred by emp1 reference variable and second object is being   referred to by emp2 reference variable,so which means none of these two objects are eligible for       garbage collection.

Now lets do this :
emp1 = emp2
So what happened here. Yes ,you guessed it right....

emp1 has also started referring to object which emp2 was referring. Basically we are assigning reference to second object, to reference variable of first object, such that reference variable of first object has also started pointing to second object.



So now, as emp1 and emp2 both are referring to second object, who is referring to first object. Yes, you are right again,....Answer is no-one.so that means first object which is not being referred by any reference variable is eligible for garbage collection.

3) By creating Objects inside methods/blocks

Lets try to understand with few examples as below :

Example 1 :
package com.blogspot.javasolutionsguide;

Class TestGC {
    public static void main(String args[]) {
        testMethod();  // Line1
    }

    public static void testMethod() {
        Employee emp1=new Employee();
    }
}
After Line 1 ,that is when control returns back after testMethod has got executed,emp1 variable is not referring to any object, as local variables gets created on entering method and gets destroyed once method is exited.so after testMethod has exited ,object referred by emp1 is eligible for garbage collection.

Example 2:
package com.blogspot.javasolutionsguide;                                                                                                                          Class TestGC{
public static void main(String args[]){ Employee emp = testMethod(); // Line 1 System.out.println("Name is :"+emp.getName()); //Line 2 } public static Employee testMethod(){ Employee emp1 = new Employee(); //Line 3 emp1.setName("JavaSolutionsGuide"); //Line 4 return emp1 ; // Line 5 } }
Output : JavaSolutionsGuide
Here in Line 1 ,we are calling testMethod() ,which creates object Employee (at Line 3) ,which is being referred by emp1 reference variable. In Line 4 ,we are setting instance variable "name" of Employee object to value "JavaSolutionsGuide".At Line 5,we are returning reference to Employee object ,back to testMethod. Now as the control returns back to Line 1 ,reference emp1 is assigned to emp. we can think of it as emp = emp1,such that Employee object is being referred now by emp reference variable rather than emp1.Hence object Employee is not eligible for garbage collection here.

Now lets see a variation of above program :
package com.blogspot.javsolutionsguide

Class TestGC{
  public static void main(String args[]){
     testMethod();              // Line 1
  }

public static Employee testMethod(){
      Employee emp1 = new Employee();      //Line 3
      emp1.setName("JavaSolutionsGuide"); //Line 4
      return emp1  ;   // Line 5
   }
}
As you would have already noticed, here in Line1 ,after testMethod is returned, we are not assigning returned reference to any variable, so Employee object created in testMethod is eligible here for garbage collection.

Example 3 :
package com.blogspot.javasolutionsguide

Class TestGC{
          static Employee emp;      //Line 1
   public static void main(String args[]){
      testMethod();              // Line 2
      System.out.println("Name is :"+emp.getName());  //Line 3
   }

   public static void testMethod(){
        emp = new Employee();  // Line 4
        emp.setName("GB");     // Line 5
   }
}

Here in Line 1 ,we are declaring a static reference variable of type Employee. At line 2,we are calling testMethod().At Line 4, we are creating an object of type Employee and assigning its reference to emp static reference variable. At Line 5,we are setting name to "GB" in the instance variable of Employee object created at Line 4.Now control will return back to Line 2.

Is Employee object eligible here for garbage collection ?

Employee object is not eligible here for garbage collection, but why?
Have not we just discussed that ,if  reference to object is not caught in the calling method, then object should be eligible for garbage collection, so why not here.

Answer to this is that emp variable declared in Line 1 here is static variable and static variables have class level scope that means they are accessible anywhere from within the class and will live till class is unloaded. As this emp variable is still holding the reference to Employee object ,so Employee object is not eligible for garbage collection.

4) Island of isolation 

Example :
package com.blogspot.javasolutionsguide

class TestGC{
          TestGC tgc ;    //Line 1
   public static void main(String args[]){
             TestGC tgc1 = new TestGC();   //Line 2
             TestGC tgc2 = new TestGC();   //Line 3
             TestGC tgc3 = new TestGC();   //Line 4
             tgc1.tgc = tgc2;      //Line 5
             tgc2.tgc =tgc3;       //Line 6
             tgc3.tgc =tgc1;       //Line 7

            tgc1 = null;    //Line 8
            tgc2 = null;    //Line 9
            tgc3 = null;    //Line 10
   }
}

Here after Line 4,we have three objects created in heap and they are referred by reference variables tgc1,tgc2 and tgc3.



After Lines 5,6,7


After Line 8

Although tgc1 = null ,still first object can be referred by tgc3.tgc ,so none of three objects are eligible for garbage collection at this time.


After Line 9

Here both tgc1 and tgc2 are assigned null, but still first object can be accessed by tgc3.tgc and second object by tgc3.tgc.tgc ,hence none of the three objects are eligible for garbage collection.


After Line 10

As all three tgc1,tgc2 and tgc3 are set to null ,it means we are left with no external reference to access any of these three objects. So although there are internal references through which these objects can access each other, but they are totally isolated from outside world, hence the name Island of isolation. So here all three objects are eligible for garbage collection.




Any suggestions, feedback, questions on the post are welcome.