Skip to main content

Requesting Garbage Collection

As we have established, the Garbage Collector runs automatically in the background. The JVM decides when it is the optimal time to run it (usually when Eden space is getting full).

However, what if you just executed a massive block of code that generated thousands of temporary objects, and you want to clean up the heap right now?

Java provides a way for you to request that the Garbage Collector run immediately.


The Two Ways to Request GC

You can request Garbage Collection using either the System class or the Runtime class. Both methods do the exact same thing behind the scenes.

1. Using System.gc()

This is the most common and readable way to request garbage collection.

public class LabRequestGC1 {

public static void main(String[] args) {
// Create an object and immediately make it eligible for GC
Student s1 = new Student("Alice");
s1 = null;

// Requesting the JVM to run the Garbage Collector
System.gc();

System.out.println("Garbage Collection requested via System.gc()");
}
}

2. Using Runtime.getRuntime().gc()

The Runtime class allows the application to interface with the environment in which the application is running.

public class LabRequestGC2 {

public static void main(String[] args) {
// Create an anonymous object (immediately eligible for GC)
new Student("Bob");

// Requesting the JVM to run the Garbage Collector
Runtime.getRuntime().gc();

System.out.println("Garbage Collection requested via Runtime");
}
}

A Crucial Warning!

[!WARNING] Calling System.gc() is a request, not a command.

The JVM is heavily optimized to run the Garbage Collector only when it is strictly necessary. When you call System.gc(), the JVM receives your request, but it might completely ignore you if it decides the heap has plenty of space and running the GC right now would hurt application performance.

Best Practice: You should almost never call System.gc() in a production application. Trust the JVM to manage memory efficiently!