Start a Project

Garbage Collection in Java

Garbage Collection in Java is an automatic memory management process that removes or reclaims unused objects.

In contrast, C language requires manual allocation and deallocation of memory. Java, however, handles memory deallocation automatically through the garbage collector.

Essentially, automatic garbage collection involves examining the heap memory to identify which objects are still in use and which are not, and then deleting the unused objects to free up memory.

Working of Garbage Collector

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

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.

Step 1: Sweep
In this step, all unused objects are identified and deleted. The heap memory previously occupied by these unused objects is then freed and made available for future use.

Advantages of 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:

System.gc() Method:

Conclusion:

Garbage collection in Java is a crucial feature for automatic memory management, helping to efficiently manage and reclaim memory by removing unused objects. By using the finalize() method and invoking System.gc(), you can influence garbage collection, although the exact timing of garbage collection remains unpredictable. Understanding how garbage collection works can improve your application’s performance and memory usage.

Thank you for reading!

Exit mobile version