我们如何在Java中显式调用垃圾回收(GC)?
当不再有对对象的引用时,该对象将被终结,并且当垃圾回收开始时,这些终结的对象将被收集,这将由JVM自动完成。我们可以直接调用垃圾回收,但是不能保证GC将立即开始执行。
我们可以通过两种方式显式调用垃圾 回收
System.gc()方法
Runtime.gc()方法
在java.lang中。Runtime.freeMemory()方法返回Java虚拟机(JVM)中的可用内存量。调用gc() 方法可能会导致freeMemory返回的值增加。
示例
现场演示
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
