Java 垃圾回收

2022-01-16 00:00:00 garbage-collection java

Java 自动调用垃圾收集器,那为什么我们需要手动调用垃圾收集器呢?什么时候应该使用 System.gc()

Java automatically calls garbage collector, then why we need manual calls for garbage collection? When should use System.gc()

推荐答案

Java 自动调用垃圾收集器,那为什么我们需要手动调用垃圾收集器呢?

Java automatically calls garbage collector, then why we need manual calls for garbage collection?

我们不需要它们.实际上,在大多数情况下调用 System.gc() 对应用程序性能有害.请参阅我对 为什么会这样"的回答调用系统 gc 是一种不好的做法" 以获得详细说明.

We don't need them. Indeed, in most circumstances calling System.gc() is harmful for application performance. See my answer to "Why is it a bad practice to call system gc" for a detailed explanation.

什么时候应该使用 System.gc()

When should use System.gc()

如果应用程序知道它正在进入一个无事可做的阶段,并且用户不太可能注意到垃圾收集,那么也许可以调用 System.gc()以阻止用户将来遇到 GC 暂停.

If the application knows it is going into a phase where it has nothing else to do AND the user is unlikely to notice a garbage collection, then maybe it is OK call to System.gc() in an effort to stop the user experiencing GC pauses in the future.

缺点包括:

  • 调用 System.gc() 通常会触发一次完整的 GC,这比新空间"的 GC 花费的时间要长得多.
  • 用户实际上可能关心/注意到.例如,如果您在游戏中的关卡"之间调用 System.gc(),则加载下一个关卡需要更长的时间.
  • 通过强制 GC,您会导致 JVM 使用额外的 CPU 周期等,这可能会干扰用户在其计算机上执行的其他事情.
  • Calling System.gc() typically triggers a full GC which takes significantly longer than a GC of the 'new space'.
  • The user may actually care / notice. For example, if you call System.gc() between "levels" in a game, you make loading the next level take longer.
  • By forcing the GC, you are causing the JVM to use extra CPU cycles, etc which may potentially interfere with other things that the user is doing on his machine.

(在单元测试和系统调试期间调用 System.gc() 也可能有正当理由.)

(There can also be legitimate reasons to call System.gc() in unit tests, and during system debugging.)

相关文章