Java – check whether the garbage collector can get objects

Is there any way to check whether the garbage collector can get objects?

Somewhere in my code, I have a reference to an object:

MyObject mo = myObject;

Then, through eclipse debugger, I get the memory location of the object Then I set the reference to null:

mo = null;

Is there any way to check whether the previously referenced object is suitable for garbage collection, or whether it is referenced elsewhere?

Thank you.

stefan

Solution

You cannot perform this operation with any object at runtime. In fact, it is not entirely possible to perform this operation deterministically However, depending on your needs, there are two options that may be appropriate:

>Set the reference to null, dump the heap, and then load it into a heap analyzer tool (such as jhat) or an analyzer that supports this analyzer These tools should let you traverse the GC root path to check whether your objects are still accessible. > Wrap the object in phantom reference using the given ReferenceQueue When the reference is queued, you know that the object has been garbage collected (unfortunately, if the reference is not added, it may be because the object is still accessible, or it may be because the GC has not checked the object. Like all GC related problems, garbage collection is not a deterministic process!)

Overall, I agree that the best option is to understand memory leaks and design applications to avoid them If there is a memory leak, it should be obvious enough, and then you can focus on finding the problem (again by dumping and analyzing the incorrect objects in the heap)

The above steps are relatively time-consuming and should not be done to reassure yourself after each change, but a tool you use to investigate specific problems

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>