Check if the object can be retrieved by the garbage collector

Is there a way to check if an object can be retrieved by the garbage collector?

Somewhere in my code, I have an object reference:

MyObject mo = myObject; 

Then, through the Eclipse Debugger, I get the object memory cell. Subsequently, I set the reference zero:

 mo = null; 

Is there a way to check if the previously mentioned object is suitable for garbage collection or somewhere else a link to it?

Many thanks,

Stephen

+6
java garbage-collection
source share
2 answers

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.

+13
source share

Not. The only thing to do is to be careful and keep in mind that a memory leak can exist in Java when writing your application.

The only thing you can do is use the tools to try and find out where the memory leaks come from when you notice such a problem. I would highly recommend Memory Analyzer for this purpose.

+1
source share

All Articles