views:

156

answers:

3

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.

+1  A: 

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
and with synchronization expected
Gopi
@Gopi, I left that out for simplicity. mdma shows one way to do it.
Matthew Flaschen
+1  A: 

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
Or you could make the class a singleton, then you could just "return singletonObject == null ? 0 : 1;"
bowenl2
Mr. Badguy could challenge this by means of reflection.
DerMike
+5  A: 

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
@mdma this code is pretty close,but what happens for serialized and deserialized class.
Suresh S
@mdma ok thanks
Suresh S
@mdma a small thought , is it possible to know count for instances if other class creates
Suresh S
All instantiations of the class are tracked, no matter who creates the class.
mdma