How can we call garbage collection (GC) explicitly in Java?

JavaObject Oriented ProgrammingProgramming

When there are no more references to an object, the object is finalized and when the Garbage Collection starts these finalized objects get collected this will done automatically by the JVM. We can call garbage collection directly but it doesn't guarantee that the GC will start executing immediately.

We can call the Garbage Collection explicitly in two ways

  • System.gc() method
  • Runtime.gc() method

The java.lang.Runtime.freeMemory() method returns the amount of free memory in the Java Virtual Machine (JVM). Calling the gc() method may result in increasing the value returned by the freeMemory.

Example

Live Demo

public class GarbageCollectionTest {
   public static void main(String args[]) {
      System.out.println(Runtime.getRuntime().freeMemory());
      for (int i=0; i<= 100000; i++) {
         Double d = new Double(300);
      }
      System.out.println(Runtime.getRuntime().freeMemory());
      System.gc();
      System.out.println(Runtime.getRuntime().freeMemory());
   }
}

Output

15648632
13273472
15970072
raja
Published on 04-Jul-2019 23:05:31
Advertisements