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