Atomically incrementing counters stored in ConcurrentHashMap

前端 未结 6 1463
猫巷女王i
猫巷女王i 2020-12-05 04:02

I would like to collect some metrics from various places in a web app. To keep it simple, all these will be counters and therefore the only modifier operation is to incremen

6条回答
  •  长情又很酷
    2020-12-05 04:51

    Other than going with AtomicLong, you can do the usual cas-loop thing:

    private final ConcurrentMap counts =
        new ConcurrentHashMap();
    
    public void increment(Key key) {
        if (counts.putIfAbsent(key, 1)) == null) {
            return;
        }
    
        Long old;
        do {
           old = counts.get(key);
        } while (!counts.replace(key, old, old+1)); // Assumes no removal.
    }
    

    (I've not written a do-while loop for ages.)

    For small values the Long will probably be "cached". For longer values, it may require allocation. But the allocations are actually extremely fast (and you can cache further) - depends upon what you expect, in the worst case.

提交回复
热议问题