简体   繁体   English

如何查看Java中垃圾收集的对象?

[英]How to see what objects have been garbage collected in Java?

Please, is there any way how to get history of objects (their variable or at least class names) that have been garbage collected in Java? 请问,有没有办法获取在Java中垃圾收集的对象(它们的变量或至少是类名)的历史记录?

Just adding these params (to Oracle JVM) 只需添加这些参数(到Oracle JVM)

-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps

doesn't provide anything else memory in bytes. 没有以字节为单位提供任何其他内存。 It's very limited help to me. 这对我来说是非常有限的帮助。 Thanks for all responses. 感谢所有回复。

Note: Workaround with add finilize() method is not unfortunatelly an option for me (I don't have an access to it). 注意:添加finilize()方法的解决方法对我来说并不是一个不幸的选择(我无法访问它)。

You can use the finalize method from Object . 您可以使用Objectfinalize方法。 This method is called when the object is about to be GCed. 当对象即将被GCed时调用此方法。 From here, you can log the information you need. 从这里,您可以记录您需要的信息。

Disclaimer: My company develops the tool that I recommend in this answer. 免责声明:我的公司开发了我在这个答案中推荐的工具。

In JProfiler you can go to the "Recorded objects" view in the memory section and switch the liveness mode to garbage collected objects (View->Change Liveness Mode->Garbage Collected Objects). JProfiler中,您可以转到内存部分中的“已记录对象”视图,并将活动模式切换为垃圾回收对象(查看 - >更改活动模式 - >垃圾收集对象)。 You will then see a statistics of objects that have been GCed. 然后,您将看到已经GCed的对象的统计信息。

在此输入图像描述

Weak references or phantom references seem to be useful to log when the object actually gets removed. 当对象实际被删除时, 弱引用幻像引用似乎对记录有用。 In this article the technology is explained. 本文中 ,解释了该技术。

Are you searching for a memory leak? 你在寻找内存泄漏吗?

If you implement finalize() method (available in every Object ) it will get called just before the object is being garbage collected - and you can run any code inside it. 如果你实现了finalize()方法(在每个Object中都可用),它将在对象被垃圾收集之前被调用 - 你可以在其中运行任何代码。

If you are looking for a systematic solution (or you don't have access to classes you want to monitor), I am not aware of any JVM option that allows that. 如果您正在寻找一个系统的解决方案(或者您无法访问要监视的类),我不知道有任何JVM选项允许这样做。 However you can log classes being loaded and unloaded (GCed), but this is not what you are asking. 但是,您可以记录正在加载和卸载的类(GCed),但这不是您要求的。

There is a nice built-in tool in JDK for observing jvm in runtime. JDK中有一个很好的内置工具,用于在运行时观察jvm。 It is jvisualvm. 这是jvisualvm。 There is aa good reference with screenshots: http://visualvm.java.net/description.html 屏幕截图有一个很好的参考: http//visualvm.java.net/description.html

Here is one of them : 这是其中之一: 在此输入图像描述

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM