Type an atomic merge-counter on a ConcurrentHashMap
Type an atomic merge-counter on a ConcurrentHashMap
Answer
ConcurrentHashMap<String, Integer> counts = new ConcurrentHashMap<>(); counts.merge("a", 1, Integer::sum);
merge runs atomically: it inserts 1 if absent, otherwise applies Integer::sum to combine the old and new values. No external lock and no check-then-act race.