Garbage Collector


Garbage Collector

When JVM starts up, a heap area is created, which is called a runtime data area. This is the place where all the objects are stored. It is required to manage this area efficiently by clearing the objects that are no longer in use since this area is limited. The procedure of removing unused objects from heap memory is called Garbage collection. It is a part of memory management in Java. The garbage collection is automatic in java. Garbage Collection is the process of taking back the unused memory automatically at the runtime that is how the unused objects are getting destroyed.

Java has these automatic functions unlike C and C++ where we use free() and delete() functions respectively to free up the unused spaces during the runtime.

We can request JVM to run garbage collector in the following 2 ways:

  • Using System.gc() method
  • Using Runtime.getRuntime().gc() method

Java performs garbage collection:

  • When the object is no longer reachable
  • When one reference is copied to another reference

Some good ways to handle garbage collection are as follows:

  • Use Tools for Analysis
  • Select the Right Collector
  • Use JVM Flags for Tuning
  • Avoid manual triggers

What are the advantages of Garbage Collection?

Due to Garbage Collector, java is more memory efficient which removes unreferenced objects from the heap memory.
JVM has a dedicated Garbage Collector for the automatic collection of the unused heap memory so that we do not have to make extra efforts.

What are Unreferenced Objects?

  • Objects which are not initialized.

    int n; // this n will never be used in the program and not initialized.
  • The reference of the object is null.

    ClassName obj = new ClassName();
    Obj = null; // obj is assign as null
  • The reference is assigned to another.

    ClassName obj1 = new ClassName();
    ClassName obj2 = new ClassName();
    obj1 = obj2; //obj referenced is assigned to another.
  • If the object gets assign by anonymous objects.New NewClassConstructor();

Example:

Com.knowledge2life public class Main{ public void finalize(){System.out.println("Knowledge2life 1");} public static void main(String args[]){ Main s1=new Main(); Main s2=new Main(); s1=null; s2=null; System.gc(); } }

OUTPUT:

Knowledge2life 1
Knowledge2life 1