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:
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.
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()); } }
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!