How is Garbage Collection managed ?

The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low.  One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by JVM.

The Garbage Collection process can not be forced, though there are few ways by which it can be requested but there is no guarantee that these requests will be taken care of by JVM.

Ways to request for Garbage Collection

There are two ways in which we can request the jvm to execute the Garbage Collection.

  • The methods to perform the garbage collections are present in the Runtime class provided by java. The Runtime class is a Singleton class for each JVM. The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked using this instance of Runtime to request the garbage collection.
public static void main(String[] args) {
	Runtime.getRuntime().gc();
}

The gc() method runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to   make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects. The gc() method is writtent in native code ( C / C++ ) in Runtime class.

public native void gc();
  • Another way to call the System class System.gc() method which will request the jvm to perform GC.

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself