一位面试官问我
How can you implement a class Foo, where you will be able to count instances of that class. There are more threads which are creating instance of that class Foo.
我用下面的代码回复了
public class Foo {
private static int count = 0;
public Foo() {
incrementCount();
}
public void incrementCount() {
synchronize (Foo.class) {
count++;
}
}
}
她再次问我
If a thread ends, counter should be decrement, how can you do that?
我没有回答这个问题。
我知道 finalize()
方法,但它取决于 Garbage collector
何时调用此方法,即使我们覆盖 finalize()
.
我还没有解决办法,你能解释一下吗?
最佳答案
您可以包装 Thread 的 Runnable
在另一个里面 Runnable
这会减少计数器:
Thread createThread(final Runnable r) {
return new Thread(new Runnable() {
@Override public void run() {
try {
r.run();
} finally {
Foo.decrementCounter();
}
}
});
}
问题是如果 Runnable r
创建 Foo 的多个实例。您必须以某种方式跟踪线程创建的实例数。你可以使用 ThreadLocal<Integer>
来做到这一点, 然后调用 decrementCounter()
, 在 finally
block ,适当的次数。有关完整的工作示例,请参见下文。
如果可以避免,则不应依赖 GC 的行为,因为它是不可预测的!如果您坚持要处理垃圾收集器,那么您应该使用引用队列——要正确使用它,您应该研究对象可达性的概念:http://docs.oracle.com/javase/7/docs/api/index.html?java/lang/ref/package-summary.html
作为最后的说明,如果我正在采访您,我会尽量让您意识到您提出的代码并不能完全满足要求:您必须创建类 final
,或方法 incrementCount()
final
或 private
.或者,更简单的方法是,您可以在实例初始化 block 中增加计数:无需考虑在子类中重写的方法或新添加的构造函数不会增加计数。
一个完整的例子:
public class Foo {
private static final AtomicInteger liveInstances = new AtomicInteger(0);
private static final ThreadLocal<Integer> threadLocalLiveInstances = new ThreadLocal<Integer>() {
@Override protected Integer initialValue() { return 0; }
}
// instance initializer (so you won't have problems with multiple constructors or virtual methods called from them):
{
liveInstances.incrementAndGet();
threadLocalLiveInstances.set(threadLocalLiveInstances.get() + 1);
}
public static int getTotalLiveInstances() {
return liveInstances.get();
}
public static int getThreadLocalLiveInstances() {
return threadLocalLiveInstances.get();
}
public static void decrementInstanceCount() {
threadLocalLiveInstances.set(threadLocalLiveInstances.get() - 1);
liveInstaces.decrementAndGet();
}
// ... rest of the code of the class ...
}
class FooCountingThreadFactory implements ThreadFactory {
public Thread newThread(final Runnable r) {
return new Thread(new Runnable() {
@Override public void run() {
try {
r.run();
} finally {
while (Foo.getThreadLocalLiveInstances() > 0) {
Foo.decrementInstanceCount();
}
}
}
});
}
}
这样,您可以将此 ThreadFactory 提供给线程池,例如,或者您可以在要构建线程时自己使用它:(new FooCountingThreadFactory()).newThread(job);
无论如何,这种方法仍然存在问题:如果线程创建了 Foo
的实例并将它们存储在全局范围内(读取:static
字段),然后这些实例在线程死亡后仍然存在,并且计数器将全部递减为 0。
关于java - 如何在Java中实现对象计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8641992/