首頁  >  文章  >  Java  >  在Java中,我們如何明確地呼叫垃圾回收(GC)?

在Java中,我們如何明確地呼叫垃圾回收(GC)?

王林
王林轉載
2023-09-05 18:29:12879瀏覽

在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

以上是在Java中,我們如何明確地呼叫垃圾回收(GC)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除