【发布时间】:2014-01-19 21:21:42
【问题描述】:
我想实现一个共享对象来计算操作执行的统计信息。
对象状态将由Map<String,AtomicInteger> 表示(key 是操作的名称,value 是操作执行的次数)。我是否正确,我可以选择一个 HashMap<String,AtomicInteger> 实现并且不使用同步来从中获取值,因为 AtomicInteger 在它下面有一个 volatile value 字段。
增加和增加执行统计的代码示例:
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public final class Stats {
private final Map<String, AtomicInteger> statistics = new HashMap<String, AtomicInteger>();
public int increment(String operationName) {
if (!statistics.containsKey(operationName)) {
synchronized (statistics) {
if (!statistics.containsKey(operationName))
statistics.put(operationName, new AtomicInteger(0));
}
}
return statistics.get(operationName).getAndIncrement();
}
public int getOpStats(String operationName) {
if (!statistics.containsKey(operationName)) {
return 0;
}
return statistics.get(operationName).get();
}
}
【问题讨论】:
-
不清楚你想问什么。请尝试提出一个具体的问题。
-
这个不用自己实现,从key->int的线程安全映射已经存在于Guava的ConcurrentHashMultiset
标签: java multithreading synchronization