Java GC 和内存使用情况跟踪
我知道 GC 会释放不再引用的对象的内存,但是有没有一种有效的方法来检查我是否确实引用了不再使用的对象?
有关如何避免留下对不再使用的对象的引用的提示将非常有价值。
在这种情况下使用 Windows 任务管理器有帮助吗?如果是这样,关于如何使用它批评我的程序的提示也会有所帮助。
谢谢。
I know that the GC releases memory of objects that have no longer references to, but is there an effcient way to check if i do have references to no longer used objects?
tips on how to avoid leaving references to no longer used objects would be greatly aprriciated.
Is using the Windows Task Manager any help in this situation? if so, tips on how to criticize my program using it would help too.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查很简单。您仍在使用您引用的所有对象。
“内存泄漏”的一个常见问题是将对象添加到集合中,然后在不再需要它们时忘记清理它们。解决这个问题的一种方法是使用 WeakReferences 或使用它们的集合,例如 WeakHashMap。当其他地方不再有引用时,这些内容就会被清除。
恕我直言,Windows 任务管理器在这里更容易造成混乱而不是提供帮助。 ;)
使用 VIsualVM 或像 YourKit 这样的商业内存分析器是检查内存消耗的最佳方法。
The check is simple. You are still using all objects you have references to.
A common problem with "memory leaks" is adding objects to collections and forgetting to clean them up when they are no longer needed. A way around this problem is to use WeakReferences or a collection which uses these e.g. WeakHashMap. These are cleaned up when there is no longer a reference elsewhere.
IMHO, Windows Task manager is more likely to confuse than help here. ;)
Using VIsualVM or a commercial memory profiler like YourKit is the best way to examine your memory consumption.
“不再使用”的对象被垃圾收集。 “用”,就是有很强的参照性。问题在于您不打算使用但仍然被错误地强引用的对象。
只有 VisualVM 或 JProfiler 等 Java 分析器可以帮助您找到这些对象。
提供了一个屏幕截图,显示如何使用 JProfiler 查找内存泄漏此处。
免责声明:我的公司开发 JProfiler。
"No longer used" objects are garbage collected. "Using" means holding a strong reference. The problem is with objects you do not intend to use, but that are still strongly referenced by mistake.
Only Java profilers like VisualVM or JProfiler can help you to find these objects.
A screen cast that shows how to find a memory leak with JProfiler is available here.
Disclaimer: My company develops JProfiler.
您可能会找到这篇文章什么是 Java 中的“内存泄漏”? 有用(我不知道这里宣传的工具)。
我不知道如何找到引用但未使用的对象 - 但有时,可以被垃圾收集的对象也会对你的程序产生影响 - 如果你创建大量对象并经常引发GC。
要跟踪 GC 活动,您可以简单地使用 java 非标准选项
-Xloggc:
。这会将 GC 活动记录到给定文件中。您将得到第一印象:您的应用程序在垃圾收集方面有多繁忙。尽管我没有回答您的问题,但我希望这对您有用。
You may find the article What is a “Memory leak” in Java? useful (I don't know the tool that get's advertised here).
I don't know how to find referenced but not used objects - but sometimes also objects that can be garbage collected will have an impact on your program - if you create masses of them and provoke often GC.
To track the GC activity you can simple use the java non standard option
-Xloggc:<file>
. This will log the GC activity to the given file. You will get a first impression how busy your application is with garbage collecting.I hope this is a useful information for you although I did not answer your question.