views:

50

answers:

3

I am working on a large pre-existing system and can't use any of the external profiler tools that have been mentioned in other questions.

That being said, is there any programttic way for me to get java to print out what variables are still allocated and using heap space? Variable name and type would be ideal but any identifying variable information would be helpful.

A: 
  1. For each class, add a static int member (initially zero) such that it is incremented in the constructor and decremented in the destructor. This gives you an object count of each class. (You may need to synchronizing the counter inc/dec if the system is multithreaded)
  2. Print out the object counts of all classes, and Runtime.getRuntime().totalMemory() periodically.
rwong
Is he talking about using finalize? :)
willcodejavaforfood
I ended up using a slight variation of your idea. There are far too many classes to do what you suggest with each one but I instead added the counter to the class that all of the dialogs in the system inherit from. This told me that there were some dialogs being created that were not showing up on screen. After this I made a static list to hold the newly created dialogs(and removing them at the close of the dialog)
lathomas64
@willcodejavaforfood: sorry for the mis-information, I'm a C++ guy, not realizing that there was no equivalent of destructor in Java.
rwong
A: 

Have you tried VisualVM? It's pretty non-intrusive, and should be able to give you a good idea about memory usage.

Worst case, you can always kill the project and grovel over the core dump (assuming you are running on an OS that supports core dumps).

TMN
A: 

Be careful about putting any code inside finalize, as any putting code in finalize might increase the lifetime of your Object; in fact, in extreme cases it may cause an Object to never get GCed.

Shikhar