track instantiations

Is there a good way to track instantiations of a particular object? For instance I would like to find out at run time how many ArrayList's are currently being used in my application. Thanks, Kyle Willkomm

A static counter in the class's constructor should do the job. If you want to actually track the object, you may have to implement some kind of object factory and object pooling mechanism. It is particularly not possible to do this for classes that are part of Java language itself since they are pre-packaged classes and you cannot modify their code. However, you can wrap those classes, for example, an ArrayList inside a custom class and implement a factory pattern if you really want to keep track of the instances. Cheers!

Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).

Kyle Willkomm
Ranch Hand

Joined: Sep 10, 2001
Posts: 44

posted Sep 25, 2001 07:34:00

0

Actually. My last thought was to create a counter class with a static counter and then add to the counter whenever I create a new, say ArrayList, I increment it and vice versa. I an aware of the ability to watch the memory of the JVM but was wondering if there were more ways to watch the actually classes in the JVM dynamically. How does something like JProbe do it?

JProbe probably is able to do that with a custom JVM... My company uses a product called JTest to do static and dynamic analysis and that's the way it does it...

The only problem with using a seperate counter class is that you actually have to remember to increment and decrement this class in your code, every time you create or destroy an object of the class you are trying to track... If you forgot to put those lines in a few times, or if another class you are using is secretly using objects of the class you are tracking there is no way to know if the numbers you arrive at are correct...

Something like this should work for classes you create yourself...

-Nate [This message has been edited by Nathan Pruett (edited September 26, 2001).]

Right. My main problem was that I needed to track sessions in my web app. This could be done by placing this counter class in the session. The counter would run its finalize when the session invalidated and it would decrement the static counter. I was just wondering if there was a way to watch the JVM or count non-custom classes. Apparently its not possible without writting your own JVM as JProbe and other tools like it do. Thanks for the time though.