How many ways to call garbage collector (GC) in Java?

JavaObject Oriented ProgrammingProgramming

The garbage collection in Java is carried by a daemon thread called Garbage Collector(GC). Instead of waiting until JVM to run a garbage collector we can request JVM to run the garbage collector. There is no guarantee whether the JVM will accept our request or not.

In Java, we can call the garbage collector manually in two ways

  • By using System class
  • By using Runtime class

By using System class

System class has a static method gc(), which is used to request JVM to call garbage collector.

Example

public class SystemClassTest {
   public static void main(String[] args){
      SystemClassTest test = new SystemClassTest();
      test = null;
      System.gc();
   }
   public void finalize() {
      System.out.println("Garbage collected");
   }
}

Output

Garbage collected


By using Runtime class

Runtime is a singleton class in Java and we can get a runtime object using the getRuntime() method. The gc() method is from Runtime class and it is an instance method.

Example

public class RuntimeClassTest {
   public static void main(String[] args) {
      RuntimeClassTest test = new RuntimeClassTest();
      test = null;
      Runtime.getRuntime().gc();
   }
   public void finalize() {
      System.out.println("Garbage Collected");
   }
}

Output

Garbage collected
raja
Published on 22-Aug-2019 08:49:16
Advertisements