Tuesday, 8 July 2014

Garbage Collector in Java

Garbage Collector is a part of JVM (Java Virtual Machine). Garbage collector(GC) only deal with heap memory.GC is a program which runs on the JVM which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management.


Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp.

Garbage Collector done it's job without any request and  notification.It continuously reviewing the heap memory that any objects have not been referenced to variable(stack) then it automatically clean the memory from these object or simple words are It frees memory allocated to objects that are not being used by the program any more.
In Java the GC runs automatically, but you can also call it explicitly with System.gc() and try to force a major garbage collection but in a programming language like C, allocating and deallocating memory is a manual process so Java take this headache from programmer and put it into JVM.





  public class GarbageCollector{
   public static void main(String[] args) {
        Object obj1=new Object(); //Create a new object on Heap
        obj1=new Object();//Create another object and hold reference to last one variable
        System.gc();
  }
}//ENd of Class

Now in the above code the first time obj1 hold referenced first created object and then
 it again hold another object reference; but where is the last object referenced that is
 unreachable; now it's time of Garbage collector and it automatically deallocate the 
object memory from  the heap and make available free for the future and save program
from starvation problem. 
We can garbage collector in Java by using this statement
   System.gc();

Note: If anyone don't know about the word "HEAP" or "Stack" then first 
I recommend to you read this topic
http://theprogrammingsintroduction.blogspot.com/2014/07/what-is-stack-and-heap-in-java.html

No comments:

Post a Comment