Java System.gc() – Examples
We know that Garbage Collection in Java happens implicitly by JVM. But, we can also request JVM to explicitly perform Garbage collection.
In this tutorial, we will learn about the Java System.gc() function, and learn how to use this function to perform Garbage Collection explicitly by the Garbage Collector, the help of examples.
gc()
System.gc() runs the garbage collector to recycle unused objects and make this memory available for reuse.
Syntax
The syntax of gc() function is
gc()
Returns
The function returns void.
Example 1 – gc()
In this example, we will initialize an ArrayList Object with some values. Then we shall assign a null reference to this ArrayList Object. So, if we run Garbage Collection now, the values we assigned to the ArrayList Object before assigning null are eligible for Garbage Collection.
Java Program
import java.util.ArrayList;
public class Example {
public static void main(String args[]) {
ArrayList<Integer> arrayList = new ArrayList<>();
arrayList.add(4187);
arrayList.add(5263);
// assign null to arrayList
arrayList = null;
// requesting JVM for running Garbage Collector
System.gc();
}
}
Example 2 – gc()
When Garbage Collection is run, before destroying eligible objects for garbage collection, JVM runs finalize() method on these objects.
In this example, we will create an anonymous object. This anonymous object is created in the memory but never used after initialization. So, this anonymous object is eligible for garbage collection. When we call gc() method, finalize() method for this object will be run.
Java Program
public class Example {
public static void main(String[] args) {
new Example();
System.gc();
}
@Override
protected void finalize() {
System.out.println("Garbage collector called.");
}
}
Output
Garbage collector called.
Conclusion
In this Java Tutorial, we have learnt the syntax of Java System.gc() function, and also learnt how to use this function with the help of examples.