简体   繁体   中英

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). 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.

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:

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 .

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> . This would probably give look-up performance close to an AtomicInteger[] -array lookup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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