Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

how many instances for a class exists at runtime in java

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...