Video in progress
If a few "hot" keys in a ConcurrentHashMap are slowing down the whole service, how do you detect it and fix it?
All writes to one key queue up for a single bucket lock: the CPU is busy, but throughput doesn't grow. In a profile you see synchronized monitor waits. The fix: split the counter with LongAdder, shard the key, or accumulate writes through a local buffer.
📖 Answer
The scenario: for every event, counts.merge(eventType, 1L, Long::sum). There are 20 types, but 80% of events fall into a single PAGE_VIEW type. With 64 threads, throughput is barely different from 8 threads.
Detection:
- async-profiler
-e lockor JFR'sjdk.JavaMonitorEnterevents: waiting insideConcurrentHashMap.putVal/compute; - in a thread dump, many threads are
BLOCKEDon the same monitor; - CPU is high, but p99 latency is growing.
Ways to fix it, simplest first:
- Make the value itself concurrent, so the Map is written only once:
ConcurrentHashMap<String, LongAdder> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent(type, k -> new LongAdder()).increment();
Now there are no writes to the Map, and inside the LongAdder threads write to different cells. On Java 9+, computeIfAbsent returns without taking a lock when the key is at the head of the bucket, which is the case most of the time.
-
Split the key artificially:
type + "#" + (threadId % 16), and combine on read. You need this for complex values. -
A thread-local buffer and a periodic flush: the highest throughput, but data shows up slightly late and can be lost on a crash.
-
Hand the work to a single writer thread and send to it through a queue: no locks at all, but you have to watch that the queue itself doesn't become the bottleneck.
Which one depends on the accuracy and latency requirements. For metrics I almost always take option 1; for exact values like a balance or a limit, you need transactional storage here, not an in-memory map.
Sign up to mark studied questions and save your progress.