简体   繁体   English

为什么我们调用 System.gc() 方法来收集未使用的垃圾 object

[英]Why we are calling System.gc() method to garbage collection of unused object

Why we are calling System.gc() method to garbage collection of unused object, if garbage collection is automatically done in Java by daemon thread in background process with regular interval?为什么我们要调用 System.gc() 方法对未使用的 object 进行垃圾回收,如果垃圾回收由后台进程中的守护线程以固定间隔自动完成 Java?

For testing purposes it can be useful to know when a GC has been performed.出于测试目的,了解何时执行 GC 可能很有用。 However this is rare and calling System.gc() when it isn't needed is such a common mistake that you can turn it off with -XX:+DisableExplicitGC.然而,这种情况很少见,在不需要时调用System.gc()是一个常见的错误,您可以使用-XX:+DisableExplicitGC.

We're not, because we're generally not smarter than the GC.我们不是,因为我们通常不比 GC 聪明。 Technically, calling it doesn't guarantee it'll run, although in many implementations it does.从技术上讲,调用它并不能保证它会运行,尽管在许多实现中确实如此。

Also, it's not necessarily done at regular imtervals, but based on an as-needed basis.此外,它不一定定期进行,而是根据需要进行。 Different implementations will start GC based on different criteria.不同的实现会根据不同的标准启动 GC。

System.gc() just gives the garbage collector a hint that this might be a good time for garbage collection, eg because a lot of objects aren't used anymore and processing has finished. System.gc() 只是给垃圾收集器一个提示,这可能是垃圾收集的好时机,例如因为很多对象不再使用并且处理已经完成。

It doesn't force the garbage collector to do anything - it just gives a hint.它不会强制垃圾收集器做任何事情——它只是给出一个提示。

Only use this once you need to optimze your application (after profiling).只有在您需要优化您的应用程序时才使用它(在分析之后)。

I don't think I have ever seen it in production code so far.到目前为止,我认为我从未在生产代码中见过它。

While it shouldn't be necessary, I had code that thrashed much, much less when I did an explicit System.gc after a very large Map was emptied, just to be refilled again, in a loop.虽然这不是必需的,但当我在一个非常大的 Map 被清空后执行显式 System.gc 时,我的代码会出现很多问题,更不用说了,只是为了再次重新填充,在一个循环中。 I think without a hint the collector tried minor gcs until it was clear that wouldn't do.我认为收集器在没有暗示的情况下尝试了次要 gcs,直到很明显行不通为止。 Yes, I put it in production.是的,我把它投入生产。 I also put in a comment, just so my colleagues would test rather than blindly remove.我也加了评论,让同事们测试一下,而不是盲目删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM