显式调用System.gc()? [英] Calling System.gc( ) explicitly?

查看:197
本文介绍了显式调用System.gc()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说我们不能强制Java中的 垃圾回收 进程。

毕竟,它是一个守护线程。

但是有时候,为什么我们明确调用 System.gc(); 函数?

值得称呼它吗?任何Pro的和Con的?

如果在许多情况下没有用,为什么这个方法不被Java弃用?



PS:在我看来,最好的办法是考虑 System.gc()。 方法作为垃圾收集应该运行的虚拟机的提示。也就是说,就像人们认为他们正在执行的优化的很大一部分一样,通常最好是让系统自行处理事情。系统正在不断发展等等等等。仍然有些情况下开发人员可能真的知道得更好,而且它的用例可能非常类似于为什么一些代码仍然是用汇编语言编写的(大多数情况下,编译器更好,但在少数情况下(或少数开发人员),人们实际上可以编写更高效的代码)。

过去曾经见过的一个例子用来证明它的存在是因为如果分配了大量对象,并且您作为开发人员知道他们的即时状态不再被使用。在这种情况下,与GC相比,您可能拥有更多关于内存使用情况的信息(或者至少在它意识到之前),并且由于回收的内存量很大,建议它运行是有意义的。 p>

It is said that we cannot force the garbage collection process in java.
It's after all, a daemon thread.

But still sometimes, why we call the System.gc( ); function explicitly ?
Is it worth calling it ? Any Pro's and Con's ?
If not useful in many situations, why this method is not deprecated from Java ?

PS : Explanation with an example will be useful

解决方案

The best way, in my opinion, to think of the System.gc() method is as a "hint" to the VM that garbage collection should run. That said, much like a large percentage of "optimizations" people think they are performing, it's usually best to just let the system take care of things on its own. Systems are evolving etc, etc, etc. There are still some instances where the developer may actually know better and the use case for it is probably very similar to why some code is still written in assembly (most of the time, the compiler is better, but in a few instances -- or with a few developers -- humans can actually write more efficient code).

One example I've seen used in the past to justify its existence is in the event that a large number of objects were allocated and you as the developer know the instant they are no longer going to be used. In that case, you may have more information about the memory utilization than the GC does (or at least, before it realizes it) and, since the amount of memory reclaimed will be significant, it makes sense to suggest that it runs.

这篇关于显式调用System.gc()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆