~/ 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/21636b02-ff2c-4559-abcc-0045025ab2c7/flashcard utf-8 LF