System.gc() 什么时候做某事? [英] When does System.gc() do something?

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

问题描述

我知道垃圾收集在 Java 中是自动化的.但我明白,如果您在代码中调用 System.gc() ,JVM 可能会或可能不会决定在此时执行垃圾收集.这是如何精确工作的?JVM 在看到 System.gc() 时究竟根据什么基础/参数决定执行(或不执行)GC?

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() 什么时候做某事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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