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.
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.
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++;
}
}
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.
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.