简体   繁体   English

AtomicInteger地图

[英]Map of AtomicInteger

I want to implement a shared object for calculation of statistics of executions of operations. 我想实现一个共享对象来计算操作执行的统计信息。 Objects state will be represented by Map<String,AtomicInteger> (key is the name of operation, value is the number of times the operation was executed). 对象状态将由Map<String,AtomicInteger> (键是操作名称,value是操作执行的次数)。 Am I correct that I can choose a HashMap<String,AtomicInteger> implementation and use no synchronization on it for getting values from it since AtomicInteger has a volatile value field underneath it. 我是否正确我可以选择HashMap<String,AtomicInteger>实现并且不使用同步来获取它的值,因为AtomicInteger下面有一个volatile value字段。

Sample of code that does addition and incrementation of execution stats: 执行统计数据添加和增加的代码示例:

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();
}

}

If you want to be thread safe with regards to counter initialization you should use a ConcurrentHashMap and always instanciate-and-increase the counters this way: 如果你想在计数器初始化方面是线程安全的,你应该使用ConcurrentHashMap并始终以这种方式实例化并增加计数器:

themap.putIfAbsent("the name", new AtomicInteger(0)); 
themap.get("the name").incrementAndGet();

You could also make sure you initialize all the counters used before you start, and just use whatever collection you like. 您还可以确保在开始之前初始化所有使用的计数器,并且只使用您喜欢的任何集合。 A plain AtomicInteger[] -array is by far quickest, given that you know where to look, HashTable could be slightly quicker than HashMap . 一个简单的AtomicInteger[] -array是最快的,因为你知道在哪里看, HashTable可能比HashMap稍快一些。

If you know on beforehand which counters you have, you could also define a java enum of all the counter names and use an EnumMap<YourCountersEnum, AtomicInteger> . 如果你事先知道你有哪些计数器,你也可以定义所有计数器名称的java enum ,并使用EnumMap<YourCountersEnum, AtomicInteger> This would probably give look-up performance close to an AtomicInteger[] -array lookup. 这可能会使查找性能接近AtomicInteger[]阵列查找。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM