Home  >  Article  >  Java  >  In Java, how do we explicitly call garbage collection (GC)?

In Java, how do we explicitly call garbage collection (GC)?

王林
王林forward
2023-09-05 18:29:12877browse

In Java, how do we explicitly call garbage collection (GC)?

When there are no references to an object, the object will be finalized, and when Garbage collection begins, these finalized objects will be automatically Collection, this will be done by JVM. We can call garbage collection directly, but there is no guarantee that GC will start execution immediately.

We can explicitly call garbage collection in two ways:

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

java.lang.Runtime.freeMemory() method returns the free memory in Java Virtual Machine (JVM) quantity. Calling the gc() method may cause the freeMemory return value to increase.

Example

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

The above is the detailed content of In Java, how do we explicitly call garbage collection (GC)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete