问题描述
我知道垃圾回收在Java中是自动化的.但是我知道,如果您在代码中调用System.gc()
,那么JVM可能会或可能不会决定此时执行垃圾回收.这是如何工作的?
I know that garbage collection is automated in Java. But I understood that if you call System.gc()
in your code that the JVM may or may not decide to perform garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the JVM decide to do (or not do) a GC when it sees System.gc()
?
在这种情况下,是否有任何示例是个好主意呢?
Are there any examples in which case it's a good idea to put this in your code?
推荐答案
在实践中,通常决定进行垃圾回收.答案取决于许多因素,例如您正在运行的JVM,它处于哪种模式以及所使用的垃圾收集算法.
In practice, it usually decides to do a garbage collection. The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using.
我不会在您的代码中依赖它.如果JVM即将抛出OutOfMemoryError,则调用System.gc()不会停止它,因为垃圾收集器将尽最大努力释放它,直到达到极限为止.我唯一看到它在实践中使用过的是在IDE中,它附加到用户可以单击的按钮上,但是即使在那儿,它也不是非常有用.
I wouldn't depend on it in your code. If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme. The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.
这篇关于System.gc()什么时候做某事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!