tags:

views:

66

answers:

3

Given a class (ex: foo.bar.MyClass), how can I get a count of the number of instances of that class existing within the JVM?

Thanks

EDIT: I'm looking for the code that will retrieve this count.

EDIT: More specifically, an implementation of the method Integer getInstanceCount(Class c)

+2  A: 

If you want to know this for debugging / optimizing reasons: Look for a memory profiler.

winSharp93
A: 

You can use a static attribute to measure instances of classes within a virtual machine:

static int noOfInstances = 0;

Increment each new instance in the constructor with:

noOfInstances++;

Or use the instance initializer:

{ noOfInstances++; }

Decrement when the object is finalized.

void finalize() {
    noOfInstances--;
}
Pool
Nice, but I suspect the OP is more interested in being able to count the number of *any* class, not those which he is able to modify. But nice nonetheless.
delfuego
Thanks, yes, I've just seen the edit. I don't believe that to be possible without using a profiler (or some sort of modified VM). @Chad, could you elaborate whether you are only after a solution at a source level?
Pool
That implementation is not thread safe. The increment/decrement is not atomic and the variable isn't volatile, so changes may not be apparent to all threads.
McDowell
Yes, it's true user must add synch blocks or use atomic concurrent to get a thread safe solution.
Pool
+4  A: 

There are three or even four possible answers depending on the exact context. Here they are:

  1. If you can change the source code of the class, then you can add a static counter (see @The Feast's answer)

  2. If you're having memory problems then you should use a memory profiler (see @winSharp93) such as: http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html,

  3. If you don't have access to the source code you can register an instrumentation agent with the JVM which will inject that static field into the classes that interest you (not trivial, but possible). A tutorial on instrumentation is available here: http://today.java.net/pub/a/today/2008/04/24/add-logging-at-class-load-time-with-instrumentation.html

  4. If you were looking for some Java API that exposes this information, then - sadly - the answer is that no such facility is supported.

Itay