Garbage Collection In Java

In java, garbage means unreferenced objects.

Garbage Collection is the automated process of reclaiming memory that is no longer in use during runtime. Essentially, it is a mechanism for disposing of objects that are not being utilized.

In C, memory is managed using the free function, while in C++, memory is managed using the delete function. On the other hand, Java handles memory management automatically, making it more convenient and efficient.

Advantage of Garbage Collection

  • It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  • It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
  • How can an object be unreferenced?

There are many ways:

  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc.
  • 1) By nulling a reference:

    Example
    
    Employee e=new Employee();
    e=null;
    

    2) By assigning a reference to another:

    Example
    
    Employee e1=new Employee();
    Employee e2=new Employee();
    e1=e2;//now the first object referred by e1 is available for garbage collection
    

    3) By anonymous object:

    Example
    
    new Employee();
    

    finalize method

The finalize method is called prior to an object being garbage collected. It is utilized for executing any necessary cleanup operations. This method is explicitly declared in the Object class as follows:

Example

protected void finalize(){}

Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

gc method

The gc function is employed for triggering the garbage collector to execute clean-up operations. This function can be located within the System and Runtime classes.

Example

public static void gc(){}

Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize method before object is garbage collected.

Simple Example of garbage collection in java

Example

public class TestGarbage1{
 public void finalize(){System.out.println("object is garbage collected");}
 public static void main(String args[]){
  TestGarbage1 s1=new TestGarbage1();
  TestGarbage1 s2=new TestGarbage1();
  s1=null;
  s2=null;
  System.gc();
 }
}
Example

object is garbage collected
       object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

Input Required

This code uses input(). Please provide values below: