2

Today in my interview , i was asked to write a code to determine how many instances for a class exits at runtime in java.

I told them , that we can use reflection . kindly let me know if you have efficient way of doing this.

Dead Programmer
  • 12,427
  • 23
  • 80
  • 112

3 Answers3

5

I don't think reflection will help you. There is the JVMTI (and the older and now defunct JVMPI) which can be used to analyse the heap and determine the number of current instances of a class.

A coded alternative is to add a counter to the class you want to track instances of:

class Myclass {

   static private final AtomicInteger count = new AtomicInteger();

   {
      count.getAndIncrement();
   }

   static public int instanceCount() { 
      return count.get();
   }

   // edit: account for serializable
   private void readObject(ObjectInputStream ois) 
       throws ClassNotFoundException, IOException {
      counter.getAndIncrement();
      ois.defaultReadObject();          
   }
}

This will track the number of instances ever created, and is thread-safe. To find out when instances are garbage collected, you can use a PhantomReference and a ReferenceQueue to track collected instances and decrement the counter.

class Myclass {

   static private final AtomicInteger count = new AtomicInteger();
   static private final ReferenceQueue<MyClass> queue = new ReferenceQueue<MyClass>();

   {
      count.getAndIncrement();
      new PhantomReference<MyObject>(this, queue);
   }

   static public int instanceCount() { 
      return count.get();
   }

   static {
      Thread t = new Thread() {
         public void run() {
            for (;;) {
               queue.remove();
               count.decrementAndGet();
            }
         }
      };
      t.setDaemon(true);
      t.start();
   }

}

EDIT:

If the class is serializeable, implement the readObject method and increment the counter. I've added this to the first code example.

mdma
  • 56,943
  • 12
  • 94
  • 128
  • this code is pretty close,but what happens for serialized and deserialized class. – Dead Programmer Aug 13 '10 at 16:33
  • a small thought , is it possible to know count for instances if other class creates – Dead Programmer Aug 13 '10 at 16:50
  • All instantiations of the class are tracked, no matter who creates the class. – mdma Aug 13 '10 at 16:54
  • This still cannot track all instantiations because an object may be created with [`Unsafe.allocateInstance`](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/misc/Unsafe.java#Unsafe.allocateInstance%28java.lang.Class%29) – Marko Topolnik Apr 10 '14 at 20:12
  • 1
    The Unsafe class is not part of the official JDK api. I could have a custom VM that does object pooling on value objects rather than allocating new instances. If we start talking mechanisms outside the JDK that mess with instantiation then of course we cannot track all instances. – mdma Apr 10 '14 at 22:27
1

I don't think you can do it for an arbitrary class with reflection. Probably he just expected you to add a static counter field:

public class Foo
{
  private static int counter = 0;
  public Foo()
  {
    counter++;
  }   
}
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
1

If you restrict instance generation by providing an accessor method and a provate constructor (like in a Singleton pattern) then you can keep count on how many times you create a new instance.

Noel M
  • 15,812
  • 8
  • 39
  • 47