Java 垃圾回收

Java garbage collection(Java 垃圾回收)
本文介绍了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.)

这篇关于Java 垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)