Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell when a Java object's memory is released?

Tags:

java

memory

I have a Swing browser application with a bug that as I add/remove to/from the GUI the memory isn't released for those objects and I'm trying to track down what is holding onto them. Problem is I don't know how to tell when something has actually be fully released from memory.

Is there a way to tell if an object has been released from memory? I'm used to Objective-C where there are several ways to tell.

Thanks

like image 801
Shizam Avatar asked Aug 11 '10 17:08

Shizam


2 Answers

You can't really do it in Java. All the answers mentioning finalizers are really not what you're after.

The best you can do is enqueue a PhantomReference in a ReferenceQueue and poll until you get the reference.

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

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

Have you ever used Phantom reference in any project?

Very interesting read here:

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

Basically, I'm using a PhantomReference in a project where a very special kind of cache needs to be computed once, when the software is installed. To efficiently compute this (disk-based) cache, a gigantic amount of memory is needed (the more the better). I'm using a PhantomReference to track "nearly exactly" when that gigantic amount of memory is released.

like image 178
NoozNooz42 Avatar answered Sep 18 '22 22:09

NoozNooz42


There are multiple ways of detecting memory leaks. Here the three I'm currently thinking of:

  1. Attaching a Profiler to your application (Netbeans or Eclipse TPTP should be useful here)
  2. Making a heap dump and analyze (with Eclipse Memory Analyzer) what instances of a class are held in memory by which other instances.
  3. Attaching VisualVM to track Garbage Collection status.
like image 36
Johannes Wachter Avatar answered Sep 18 '22 22:09

Johannes Wachter