Garbage Collection in Java

Updated 6 July 2023

Save

Garbage collection in Java is the automatic process for memory management.
It is the way to remove/destroy unused objects.

In C language allocation and deallocation of memory is the manual process. But in java, deallocating memory process is handled automatically by the garbage collector.

Basically, Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. 

Working of Garbage Collector

To determine which objects are no longer in use, the JVM intermittently use Mark and Sweep algorithm.

Basically, it consists of two steps.

Step 1: Marking

In this step, the Garbage collector identifies the used and unused objects and mark the used object.

Garbage collection in Java

Step 1: Sweep
In this step, all unused objects will be deleted. All of the heap memory which was used by unused objects is free now and available for further use.

Advantages of Garbage Collection

Automatic deallocation makes java memory efficient.
Programmers don’t have to worry about memory as It is automatically done by the garbage collector.

How to make an object eligible for Garbage Collection

There are several ways to make an object eligible for garbage collection.

  1. Nullifying the reference variable:
    For example:

2. Assigning a reference to another:

For example :

3. Anonymous object:

Example:

finalize() method :

 Before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities.
Once finalize() method completes, Garbage Collector destroys that object.

This method is present in the Object class.

System.gc() method:

Once an object is eligible for garbage collection, it may not destroy immediately by GC.
It will be garbage collected once GC will be run and we can’t predict when GC will be run.

Although we don’t know when will GC run, we can request JVM to run GC by using System.gc() method.

Hope this post will give an idea about Garbage Collection in java

Thank you !!

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home