JAVA

Garbage Collection

  • One of the really powerful features of Java Virtual Machine is memory management strategy.
  • The Java Virtual Machine allocates objects on a heap dynamically as requested by new operator.
  • Other language put burden on the programmer to free these objects when they’re no longer needed with an operator such as delete or a library function such as free.
  • The Java programming language does not provide this functionality for the programmer, because The Java run-time environment automatically reclaims the memory for the objects that are no longer associated with a reference variable.
  • This memory reclamation process is called Garbage Collection.
  Consider the following method:
Example:
void aMethod()
{
Dog dog = new Dog();//do something with the instance dog
} 
  • Dog is a local variable within aMethod, allocated automatically upon method invocation.
  • The new operator creates an instance of Dog; its memory address is stored in dog; and, its reference count is incremented to 1.
  • When this method finishes/returns the reference variable dog goes out of scope and the reference count is decremented to 0. At this point, the Dog instance is subject to reclamation by the garbage collector.

gc() Method

gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that JVM will perform the garbage collection. It only request the JVM for garbage collection. This method is present in System and Runtime class.

Example for gc() method:
 
 public class Test
{    
    public static void main(String[] args)
    {
        Test t = new Test();
        t=null;
        System.gc();
    }
    public void finalize()
    {
        System.out.println("Garbage Collected Successfully ");
    }
}
Output: Garbage Collected Successfully



Subscribe us on Youtube

Share This Page on


Ask Question