HOWTO · Java

Java 中用于垃圾回收的 System.gc()

本教程演示了如何在 Java 中使用 System.gc() 进行垃圾收集。

System.gc() 是 Java 中提供的用于垃圾收集的 API,它执行自动内存管理。

当我们运行 Java 程序时,可能会有一些不再需要的对象或数据,System.gc() 收集这些数据并删除它们以释放内存。

本教程将演示如何在 Java 中使用 System.gc()

在 Java 中演示使用 System.gc()

System.gc() 可以由系统、开发人员或用于应用程序的外部工具调用。

例子:

package delftstack;
public class System_Gc {
  public static void main(String... args) {
    for (int x = 1; x < 15; x++) {
      Demo_Class New_Demo_Class = new Demo_Class(x);
      System.out.printf("Demo Class Generated, Demo= %s%n", New_Demo_Class.get_Demo());
      System.gc();
    }
  }

  public static class Demo_Class {
    private final int Demo;

    public Demo_Class(int Demo) {
      this.Demo = Demo;
    }

    public int get_Demo() {
      return Demo;
    }

    // the garbage collector will call this method each time before removing the object from memory.
    @Override
    protected void finalize() throws Throwable {
      System.out.printf("-- %s is getting collected in the garbage --%n", Demo);
    }
  }
}

上面的代码给出了 System.gc() 的示例用法,其中一个方法被调用了 14 次,系统收集了 13 次垃圾。

输出:

Demo Class Generated, Demo= 1
Demo Class Generated, Demo= 2
Demo Class Generated, Demo= 3
-- 1 is getting collected in the garbage --
Demo Class Generated, Demo= 4
-- 2 is getting collected in the garbage --
Demo Class Generated, Demo= 5
-- 3 is getting collected in the garbage --
Demo Class Generated, Demo= 6
-- 4 is getting collected in the garbage --
Demo Class Generated, Demo= 7
-- 5 is getting collected in the garbage --
Demo Class Generated, Demo= 8
-- 6 is getting collected in the garbage --
Demo Class Generated, Demo= 9
-- 7 is getting collected in the garbage --
Demo Class Generated, Demo= 10
-- 8 is getting collected in the garbage --
-- 9 is getting collected in the garbage --
Demo Class Generated, Demo= 11
Demo Class Generated, Demo= 12
-- 10 is getting collected in the garbage --
-- 11 is getting collected in the garbage --
Demo Class Generated, Demo= 13
-- 12 is getting collected in the garbage --
Demo Class Generated, Demo= 14
-- 13 is getting collected in the garbage --

System.gc() 不是主要由开发人员使用,因为他们认为它没有用,但它是处理缓存的好工具。