System.gc()什么时候做什么 [英] When does System.gc() do anything

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

问题描述

我知道垃圾收集在Java中是自动的。但是我明白,如果你在代码中写入 System.gc(),那么Java VM可能会或可能不会在运行时决定在那一刻做一个垃圾收集。这是如何精确地工作的?当VM看到 System.gc()时决定做甚么(或不做)GC的基础/参数?是否可能有这样的例子,在这种情况下 是将它放入代码中的好主意?

I know that garbage collection is automated in Java. But I understood that if you write System.gc() in your code the Java VM may or may not decide at runtime to do a garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the VM decide to do (or not do) a GC when it sees a System.gc()? Are there maybe examples in which case it is 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天全站免登陆