java中运行时存在多少个类实例 [英] how many instances for a class exists at runtime in java

查看:102
本文介绍了java中运行时存在多少个类实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在我的采访中,我被要求编写一个代码来确定一个类在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.

推荐答案

我认为反思不会对你有所帮助。有 JVMTI (以及旧的和现已解散的JVMPI),它可以用于分析堆并确定类的当前实例数。

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();          
   }
}

这将跟踪有史以来创建的实例数,以及是线程安全的。要找出垃圾收集实例的时间,您可以使用 PhantomReference ReferenceQueue 来跟踪收集的实例并减少counter。

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();
   }

}

编辑:

如果类是可序列化的,请实现 readObject 方法并递增计数器。我已将此添加到第一个代码示例中。

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

这篇关于java中运行时存在多少个类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆