Pages

Saturday, February 9, 2013

Garbage Collector in Java - How it works!

Dynamic allocation of objects is possible in java using the new keyword. Once an object is created it is allocated with memory and this memory is alive until there are references being used by the object in the program. 
When there are no more references being used by the object it is assumed that the object is no longer needed and its memory is to be reclaimed. Unlike other programming languages, there is no need to destroy the objects using code but it is handled completely by Java and the process is called Garbage Collection. As we know, programs which do not deallocate memory can eventually crass due to the lack of availability of resources in general which is called memory leakage. 




Elimination of the need to deallocate memory in Java programs is completely handled by Garbage Collection explicitly during the lifetime of the program. Garbage Collection plays a vital role projects which uses large amount of memory or where frequently new objects are created but are required for a short span of time.

Notes : 

  1. We know memory for the objects is created in the HEAP Area of the JVM. 
  2. To make objects eligible for garbage collection, their reference variables should be assigned to null.
  3. All primitive data types cannot be assigned to null. 
Example program to see how garbage collection is called and how it works : http://pastie.org/6104628


0 comments:

Post a Comment