检查是否可以通过垃圾收集器获取对象 [英] Check if object can be fetched by garbage collector

查看:99
本文介绍了检查是否可以通过垃圾收集器获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检查一个对象是否可以被垃圾回收器取回?



在我的代码的某处,我有一个对象的引用:

  MyObject mo = myObject; 

然后,通过Eclipse Debugger,获取对象的内存位置。之后,我将引用设置为null:

  mo = null; 

是否有任何方法可以检查先前引用的对象是否适合垃圾收集,或者是否有某处另一个参考呢?



非常感谢,



Stefan

你不能在运行时使用任意对象来做到这一点,事实上它不是完全可以确定地做到这一点。但是,根据您的需要,有两种选择可能是合适的:


  1. 将引用设置为<$ c后进行堆转储$ c> null ,然后将其加载到堆分析器工具中,例如 jhat 或支持此功能的分析器。这些工具应该允许您遍历GC根目录的路径,从而检查您的对象是否仍然可到达。

  2. 将对象包装在 PhantomReference 与给定 ReferenceQueue 。当引用排入队列时,您知道该对象已被垃圾收集。 (不幸的是,如果引用未排队,可能是因为对象仍然可访问,或者可能是因为GC尚未检查对象。与所有GC相关的问题一样,垃圾回收不是确定性过程! )

总体而言,我同意最好的选择是知道内存泄漏问题并设计您的应用程序以避免它们。如果你确实有内存泄漏,它应该是很明显的,然后你可以集中精力找到问题(再次通过倾销和分析堆不能正确访问的对象)。



上述步骤相对耗时,并且不应该是每次更改之后为了让自己放心而做的事情,而是您用来调查特定 的工具。问题。

is there a way to check if an object can be fetched by the garbage collector?

Somewhere in my code I've got a reference to an object:

MyObject mo = myObject;

Then, via Eclipse Debugger, I get the objects memory location. Afterwards, I set the reference null:

mo = null;

Is there any way to check if the previously referenced object is now suitable for garbage collection or if there's somewhere another reference to it?

Thanks a lot,

Stefan

解决方案

You cannot do this at runtime with an arbitrary object, and in fact it's not fully possible to do this deterministically. However, there are two options that may be suitable depending on your needs:

  1. Take a heap dump after you set the reference to null, and then load it up in a heap analyzer tool such as jhat or a profiler that supports this. These tools should let you traverse the path from the GC roots and thus check if your object is still reachable or not.
  2. Wrap the object in a PhantomReference with a given ReferenceQueue. When the reference is enqueued, you know that the object has been garbage collected. (Unfortunately, if the reference is unqueued it could be because the object is still reachable, or it could be because the GC just hasn't inspected the object yet. As with all GC-related questions, garbage collection is not a deterministic process!)

On the whole though, I agree that the best option is to be aware of memory leak issues and design your application to avoid them. If you do have a memory leak it should be obvious enough, and you can then focus your energies on finding the problem (again by dumping and analysing the heap for objects that are incorrectly reachable).

The steps above are relatively time-consuming, and shouldn't be something that you do after every change just to reassure yourself, but rather are tools you'd use to investigate a specific problem.

这篇关于检查是否可以通过垃圾收集器获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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