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