何时收集垃圾 [英] When to Garbage Collect

查看:43
本文介绍了何时收集垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码可以在内存中加载一个非常大的图像.因此,调用

I have a piece of code that load a very big image in memory. So it seemed like a reasonable thing to call

System.gc();

在加载图像之前.据我所知,它没有问题.

before loading the image. From what I can tell it works with no issues.

昨天我决定使用一个名为 FindBugs 的非常有用的软件来扫描您的代码并报告问题这可能会导致错误或通常不建议的策略.问题是我提到的这段代码被报告了.说明是这样的:

Yesterday i decided to use a pretty useful piece of software called FindBugs that scans your code and reports back issues that might cause bugs or generally not advised strategies. The problem is that this piece of code i mentioned gets reported. The description is this:

... 强制垃圾回收;非常可疑,除了在基准测试代码

... forces garbage collection; extremely dubious except in benchmarking code

它继续详细说明:

代码显式调用垃圾收藏.特定用途除外基准测试,这是非常可疑的.

Code explicitly invokes garbage collection. Except for specific use in benchmarking, this is very dubious.

在过去,人们在已明确调用垃圾例程中的收集器,例如关闭或finalize 方法导致了巨大的性能黑洞.垃圾收藏可能很昂贵.任何迫使数百或数以千计的垃圾收集将让机器爬行.

In the past, situations where people have explicitly invoked the garbage collector in routines such as close or finalize methods has led to huge performance black holes. Garbage collection can be expensive. Any situation that forces hundreds or thousands of garbage collections will bring the machine to a crawl.

所以我的问题是:在这种情况下以编程方式调用垃圾收集器是不是不行?我的代码只调用它一次,它所在的方法很少使用.如果不能调用它,那么在执行内存密集型操作之前需要尽可能多的内存并且需要在此之前释放尽可能多的内存的情况下应该怎么做?

推荐答案

您是否通过 System.gc() 获得了任何性能改进?我不这么认为,因为在加载图像之前您可能没有很多需要收集的对象.

Did you get any performance improvements with the System.gc()? I don't think so, since you probably dont have a lot of objects that needs to be collected before you load the image.

通常现代垃圾收集器最清楚何时运行,所以你不应该强制收集,除非你有一个非常好的理由.(例如该插件建议的基准测试应用程序)

Usually modern garbage collectors know best when to run, so you shouldnt force a collection, unless you have a really really good reason to. (for example a benchmarking application as suggested by that plugin)

顺便说一句:调用 System.gc() 建议 VM 执行完整"或大型"收集,这意味着所有线程都会很快停止.否则它可能只会进行小型"垃圾收集,不会停止所有线程.

btw: Calling System.gc() recommends the VM to perform a "full" or "large" collection, which means that all threads are stopped shortly. Otherwise it will probably only make "small" garbage collections, which don't stop all threads.

使用 -verbose:gc 运行您的程序以查看收集了多少字节.

Run your program with -verbose:gc to see how many bytes are collected.

这里还有很多关于垃圾回收的技术信息:http://java.sun.com/developer/technicalArticles/Programming/GCPortal/

There is also lots of technical information on garbage collection here: http://java.sun.com/developer/technicalArticles/Programming/GCPortal/

这篇关于何时收集垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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