How do I know when Java object memory is released?

I have a Swing browser application with an error, since I add / remove to / from the GUI, memory is not allocated for these objects, and I'm trying to track what is held for them. The problem is that I don’t know how to say when something is really completely freed from memory.

Is there any way to know if an object has been released from memory? I'm used to Objective-C, where there are several ways to say it.

thanks

+6
java memory
source share
4 answers

You cannot do this in Java. All the answers that mention finalizers are not really what you need.

The best you can do is insert a PhantomReference into the ReferenceQueue and poll until you get the link.

final ReferenceQueue rq = new ReferenceQueue(); final PhantomReference phantom = new PhantomReference( referenceToObjectYouWantToTrack, rq ); 

You want to read Peter Kofler's answer here (he explains what PhantomReference is):

Have you ever used the Phantom link in any project?

It is very interesting to read here:

http://www.kdgregory.com/index.php?page=java.refobj

Basically, I use PhantomReference in a project where I need to calculate a very special type of cache when the software is installed. To efficiently compute this (disk-based) cache, a huge amount of memory is required (the better, the better). I use PhantomReference to track "almost exactly" when this gigantic amount of memory is freed.

+6
source share

Edit:

As NoozNooz42 noted, PhantomReference can do everything the finalizer can do without the presence of problem finalizers. Therefore, I recommend using PhantomReferences to extend finalize() . I keep my original post in tactics, since I think Java programmers should at least know that finalize() exists.

Original post:

Each Java class has a finalize() method, which runs when no other objects contain a reference to this class. You can extend this method as follows:

 protected void finalize() throws Throwable { try { // Do whatever you want } finally { super.finalize(); } } 

That way, you can find out if anything has a link to the objects in question. Just make sure you always call super.finalize() if you use this approach.

Finalization Link:

http://java.sun.com/developer/technicalArticles/javase/finalization/

+3
source share

There are several ways to detect memory leaks. Here are three that I'm thinking of right now:

  • Attaching a Profiler to your application ( Netbeans or Eclipse TPTP should be useful here)
  • Heap dumping and analysis (with Eclipse Memory Analyzer ) which class instances are stored in memory, with which other instances.
  • Attaching VisualVM to track garbage collection status.
+3
source share

Try YourKit . This is a Java profiler that can show you your memory usage and what is happening. IIRC, a free trial, can integrate with Eclipse and has all the features of a paid version (it just has a time limit).

+1
source share

All Articles