检查垃圾收集器是否可以获取对象
有没有办法检查垃圾收集器是否可以获取对象?
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;
然后,通过 Eclipse 调试器,我获得了对象的内存位置.之后,我将引用设置为空:
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?
非常感谢,
斯蒂芬
推荐答案
您不能在运行时对任意对象执行此操作,事实上,确定性地执行此操作并非完全可能.但是,根据您的需要,有两个选项可能适合:
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:
- 在将引用设置为
null
后进行堆转储,然后将其加载到堆分析器工具中,例如 jhat 或支持此功能的分析器.这些工具应该可以让您从 GC 根开始遍历路径,从而检查您的对象是否仍然可以访问. - 将对象包装在 PhantomReference 具有给定的
ReferenceQueue
.当引用入队时,您就知道该对象已被垃圾回收.(不幸的是,如果引用未排队,可能是因为对象仍然可以访问,或者可能是因为 GC 还没有检查对象.与所有与 GC 相关的问题一样,垃圾收集不是一个确定性的过程!)
- 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. - 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.
相关文章