Garbage collection

Java language provides different ways to perform the task of memory management. In Java, objects are declared and assigned references. Once lifeof an object is completed it is dereferenced and destroyed to free up memory space. The task is performed by a garbage collector that resides inside the JVM (Java Virtual Machine). When dereferenced objects are shifted from the young generation to the old generation, the garbage collector is executed.

The JVM can perform garbage collection operation during the execution program. But we don’t know when it’s going to be executed. Hence, we can make JVM run a garbage collector at least once throughout the execution of the program by using System.gc() method.

How to mark an object for garbage collection?

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

  1. By making a reference null
  2. Assigning an old reference to new reference
  3. With the use of anonymous object

All these methods are explained in the previous article about Java garbage collector.

Ways to implementgc() method

  1. Using System.gc() Method

System.gc() is a method available in java.lang package. It can be invoked by using simple syntax.

Syntax:

DemoGC.java

Output:

In the above code, a class DemoGCis declared. An object d of the class DemoGC is marked for garbage collection by marking d as null. After that System.gc() method is called.

The output contains the object id that is destroyed by the gc() method.

  • Using Runtime.getRuntime.gc() method

The Runtime class permits the application to make an interface with the JVM. And it executesgc() method to perform garbage collection.

GcExample.java

Output:

In the above code, a class DemoGCis declared. Two objects d1 and d2 are declared. An object d1of the class DemoGC is marked for garbage collection by assigning the old reference to new reference. After that System.gc() method is called.

The output shows the object id that is destroyed by the gc() method.

Advantages of gc() method

  1. When an application or server is started many objects are getting invoked. After that those object needs to be finalized. At this time we can call System.gc() method to clear up the memory space.
  2. System.gc() method can be used while debugging the program. To check whether memory leak is not happening in the system.

Disadvantages of gc() method

  1. The gc() method may execute for unlimited time. Itimpacts the further execution of the program. Ultimately affecting the performance of program.

Example of using gc() method

The below code counts the number of staff working in the hotel (excluding new staff).The concept of a garbage collector is used for this program.
Hotel.java

Output:

In this way, this article helps to learn more about System.gc() method used for garbage collection in Java.

Pin It on Pinterest

Share This