我想实现一个共享对象,用于计算执行操作的统计数据。对象状态将由Map<String,AtomicInteger>表示(键是操作的名称,值是执行操作的次数)。我是否正确地选择了一个HashMap<String,AtomicInteger>实现,并且在它上不使用同步来从它获取值,因为AtomicInteger在它下面有一个易失性的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();
}
}发布于 2014-01-19 21:59:38
如果您希望线程在计数器初始化方面是安全的,您应该使用一个ConcurrentHashMap,并且总是以这样的方式实例化并增加计数器:
themap.putIfAbsent("the name", new AtomicInteger(0));
themap.get("the name").incrementAndGet();您还可以确保在开始之前初始化所有使用的计数器,并只使用您喜欢的任何集合。普通的AtomicInteger[]-array是最快的,考虑到您知道在哪里查找,HashTable可能比HashMap略快一些。
如果事先知道有哪些计数器,还可以定义所有计数器名称的java enum,并使用EnumMap<YourCountersEnum, AtomicInteger>。这可能会使查找性能接近于AtomicInteger[]-array查找。
https://stackoverflow.com/questions/21222832
复制相似问题