~/ learn/ comp-348/ cards/ Not locking: confinement, immutability, safe collections, deadlock
1 of 5

A per-host tally with no lock at all

A per-host tally with no lock at all

Answer

private final ConcurrentMap<String, Long> bytesByHost = new ConcurrentHashMap<>(); void record(String host, long bytes) { bytesByHost.merge(host, bytes, Long::sum); // one atomic read-modify-write }

merge() inserts the value when the key is absent and otherwise applies the remapping function — all inside one atomic operation, so the get-then-put race cannot occur. This is the tally you will build in L3.6.

JDK javadoc java.util.concurrent.ConcurrentHashMap

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e75e5f2c-a0d0-4845-8a8a-9c0edd9bab83/flashcard utf-8 LF