我怎么知道在java中的任何给定时间创建了多少个类实例? [英] How do I know how many instances of class are created at any given time in java?

查看:86
本文介绍了我怎么知道在java中的任何给定时间创建了多少个类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么知道java中任何给定时间创建了多少个类实例?
我有A类,我想知道在任何给定时间创建了多少个实例?
请让我知道解决方案

How do I know how many instances of class are created at any given time in java? I have class A and I want to know how many instances are created at any given time? Please let me know the solution

推荐答案

使用静态变量

public class A {

    private static int instances = 0;

    public A() {
        instances++;
    }
}

如果并发是您关心的问题:

public class A {

    private static final Object LOCK = new Object();
    private static int instances = 0;

    public A() {
        synchronized(LOCK) {
            instances++;
        }
    }
}

要解决你的问题在你的问题下面的评论中说:如果你想知道有多少目前存在(即,还没有垃圾收集)您可以尝试以下内容:

To address what you've said in the comments below your question: if you want to know how many currently exist (i.e., have not been garbage collected) you could try something like the following:

public class A {

    private static final Object LOCK = new Object();
    private static int instances = 0;

    public A() {
        synchronized(LOCK) {
            instances++;
        }
    }

    protected void finalize() throws Throwable {
        synchronized(LOCK) {
            instances--;
        }
    }
}

finalize()方法将在对象被垃圾回收之前调用。但垃圾收集是臭名昭着的不可靠

The finalize() method will be called right before the object is garbage collected. However garbage collection is notoriously unreliable.

另外,作为附注,您可以使用 AtomicInteger 类而不是 int synchronized 块,如@rolfl所述。如果他发布一个,那么所有对这个想法的赞成都应该回答他的答案。

Also, as a side note, you could use the AtomicInteger class rather than an int and the synchronized blocks, as @rolfl says below. All upvotes for that idea should go to his answer, should he post one.

这篇关于我怎么知道在java中的任何给定时间创建了多少个类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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