~/ learn/ comp-308/ cards/ Concurrent collections & higher-level tools
1 of 6

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.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/4921f4ce-0cf6-45be-82ed-9433d4ccdf22/flashcard utf-8 LF