How can I find the number of live objects on the heap in Java program?
For debugging, you can use a profiler (like YourKit, a commercial java profiler). You'll find both open source and commercial variants of java profilers.
For integration with your code, you might look at using "Aspect Oriented Programming" technique. AOP frameworks (e.g. AspectWerkz) let you change the class files at class load time. This will let you modify constructors to register objects to your "all-my-runtime-objects-framework".
public class ObjectCount
{
static int i;
ObjectCount()
{
System.out.println(++i);
}
public static void main(String args[])
{
ObjectCount oc = new ObjectCount();
ObjectCount od = new ObjectCount();
ObjectCount oe = new ObjectCount();
ObjectCount of = new ObjectCount();
ObjectCount og = new ObjectCount();
}
}
class Test1
{
static int count=0;
public Test1()
{
count++;
System.out.println("Total Objects"+" "+count);
}
}
public class CountTotalNumberOfObjects
{
public static void main(String[] args)
{
Test1 t = new Test1();
Test1 t1 = new Test1();
Test1 t3 = new Test1();
Test1 t11 = new Test1();
Test1 t111 = new Test1();
Test1 t13 = new Test1();
}
}
If all your objects are created using some kind of Factory
class you can find number of objects in the heap. Even then you have to have something in the finalize()
method. Of course, this cannot be done for all objects, e.g. the jdk library classes cannot be modified. But if you want to find number of instances of a particular class you have created you can potentially find that.