You cannot do this at runtime with an arbitrary object, and in fact it is not entirely possible to do it deterministically. However, there are two options that may be appropriate depending on your needs:
- Take a heap heap after you set the link to
null , and then load it into a heap analyzer tool like jhat or a profiler that supports this. These tools should let you go from the roots of the GC and thus check if your object is accessible or not. - Wrap the object in a PhantomReference with the specified
ReferenceQueue . When the link is in the queue, you know that the object was garbage collected. (Unfortunately, if the link is not provided, this may be due to the fact that the object is still accessible, or it may be due to the fact that the GC has not yet verified the object. As with all issues related to the GC, garbage collection does not is a deterministic process!)
In general, however, I agree that the best option is to recognize problems with memory leaks and develop your application to avoid them. If you have a memory leak, it should be fairly obvious, and you can focus your efforts on finding the problem (again, dumping and analyzing the heap for objects that are not reachable).
The above steps are relatively time-consuming and should not be what you do after each change to just reassure yourself, but rather are tools that you will use to research a specific problem.
Andrzej doyle
source share