Garbage Collection

This is a very interesting and important to understand the role of garbage collection in Java.

When the JVM starts up, it creates a heap memory area, which is also called a dynamic and runtime data area. All the objects and instances will be stored in the heap area.

Garbage collection works well for managing heap memory effectively. The garbage collector collects all the unreferenced data, destroys it and frees the memory.

System.gc()

We can request the garbage collector to run using the System.gc() method.

finalize()

Every time an object is garbage collected, the finalize() method is called.

It will totally depend on the garbage collector when to run. below is the example for the same:

Syntax:

OUTPUT:

Below are the options to make any object eligible for garbage collection:

  1. Assign object to null value:

2. Anonymous objects are always ready for garbage collection.

3. An object will be ready for garbage collection if it is no longer in use.

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0