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

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

问题描述

据说java中不能强制垃圾回收进程.
毕竟,它是一个守护线程.

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

但有时,为什么我们显式调用 System.gc( ); 函数?
值得打电话吗?任何优点和缺点?
如果在许多情况下都没有用,为什么 Java 不弃用此方法?

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 : 举例说明会很有用

PS : Explanation with an example will be useful

推荐答案

在我看来,将 System.gc() 方法看作是对应该运行垃圾收集的 VM.话虽如此,就像人们认为他们正在执行的大部分优化"一样,通常最好让系统自行处理.系统在不断发展,等等.还有一些情况,开发人员实际上可能知道得更好,并且它的用例可能与为什么某些代码仍然用汇编编写非常相似(大多数时候,编译器更好,但在少数情况下——或者在少数开发人员的情况下——人类实际上可以编写更高效的代码).

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).

我在过去看到的一个用于证明其存在的示例是,如果分配了大量对象,并且作为开发人员的您知道它们将不再被使用的那一刻.在这种情况下,您可能比 GC 拥有更多关于内存利用率的信息(或至少在它意识到之前),并且由于回收的内存量很大,因此建议它运行是有意义的.

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天全站免登陆