Introduction to Garbage Collection in Java - Study24x7
Social learning Network

Introduction to Garbage Collection in Java

Updated on 15 February 2020
study24x7
Java Object oriented programmi
6 min read 1 views
Updated on 15 February 2020

In C or C++, the programmer is responsible for the creation and destruction of objects but in java programmer need not worry about the creation and destruction of objects.


The garbage collector will take responsibility for this. Garbage Collector can also be called as daemon thread(low priority thread that runs in the background). Garbage collector checks and frees up the heap memory by destroying the unreachable objects.


Unreachable objects are the objects that are no longer referenced or used in the program.


In C language garbage collection is done by using the free() function and in C++ it is done by using delete() function but in java, it is done automatically.


Garbage Collection Advantage in Java

  • Garbage Collection makes java memory-efficient because of garbage collector delete the unreferenced objects from heap memory.
  • It is performed by the garbage collector automatically.

 

The possibilities when an object be unreferenced

  •  By assigning a reference to another
  •  By nulling the reference
  •  By anonymous object

 

By assigning a reference to another

 Student obj1=new Student();  

 Student obj2=new Student();  

 obj1=obj2;//now the first object referred by obj1 is available for garbage collection

 

By nulling the reference

 Student obj1=new Student();  

 obj1=null;

 

By anonymous object

  new Student();

 

finalize() method

The finalize() method is invoked each time when the object is garbage collected. Cleanup processing is done by the finalize() method. 

Syntax For finalize() method-

protected void finalize(){

}   

 

Note: The Garbage collector collects the objects which are created by a new keyword. So if you are creating an object without using a new keyword, you can use the finalize method for them.

 

gc() method

The gc() is present in System and Runtime classes. 

public static void gc(){} 

 

Example of garbage collection in java:

 

public class GCExample

{

  protected void finalize () throws Throwable

  {

    System.out.print ("GC process done");

  }

  public void static main (String args ...)

  {

    GCExample obj = new GCExample ();

    obj = null;

    GCExample a1 = new GCExample ();

    GCExample a2 = new GCExample ();

    a2 = a1;

    System.gc ();

  }

}

 

Some Important Point About Garbage Collector :

  • Garbage Collector call finalize() method, not JVM.
  • Garbage Collector is a module of JVM.



study24x7
Write a comment...