programmatic memory tracking in java
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 bein开发者_如何学Cg 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.
- 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)
- Print out the object counts of all classes, and
Runtime.getRuntime().totalMemory()
periodically.
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).
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.
精彩评论