我认为反思不会对你有所帮助.有JVMTI(以及较旧且现已不存在的JVMPI),可用于分析堆并确定类的当前实例数.
编码的替代方法是向要跟踪实例的类添加计数器:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这将跟踪有史以来创建的实例数,并且是线程安全的.要找出实例何时被垃圾收集,您可以使用a PhantomReference和a ReferenceQueue来跟踪收集的实例并减少计数器.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
如果类是可序列化的,请实现该readObject方法并递增计数器.我已将此添加到第一个代码示例中.
| 归档时间: |
|
| 查看次数: |
5038 次 |
| 最近记录: |