Quick revision
The short answer
The method has two races even though every single call on ConcurrentHashMap is thread-safe: containsKey followed by put is check-then-act, so two threads can both see the key missing, and get followed by put is read-modify-write, so two threads can read the same count and one increment is lost. The fix is to make the whole update one atomic map operation, counts.merge(k, 1, Integer::sum), or for very hot keys to store a LongAdder per key with counts.computeIfAbsent(k, x -> new LongAdder()).increment().
What to remember
In this answer, we saw that the original hit() method has two separate races: check-then-act when a key appears for the first time, and read-modify-write on every increment. Each ConcurrentHashMap call was atomic, but the sequence of calls was not, so updates were lost. We rewrote it with merge(k, 1, Integer::sum), which performs the whole update atomically per key, and with a LongAdder per key for very hot counters, where contention on a single bin would otherwise become the bottleneck.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The method has two races even though every single call on ConcurrentHashMap is thread-safe: containsKey followed by put is check-then-act, so two threads can both see the key missing, and get followed by put is read-modify-write, so two threads can read the same count and one increment is lost. The fix is to make the whole update one atomic map operation, counts.merge(k, 1, Integer::sum), or for very hot keys to store a LongAdder per key with counts.computeIfAbsent(k, x -> new LongAdder()).increment().
Why this question is asked
Counting things per key is one of the most common jobs a shared map does in a service: hits per endpoint, errors per customer, messages per topic. It is also where many engineers first learn that a thread-safe collection does not make the code around it thread-safe. Interviewers like this snippet because it looks correct, it passes every single-threaded test, and it quietly loses counts in production. In this answer, we will recap what ConcurrentHashMap actually guarantees, reproduce both races step by step, see why each method being atomic does not help, and then rewrite the method with merge and with LongAdder, explaining when each one is the better choice.
1A Quick Recap of What ConcurrentHashMap Promises
ConcurrentHashMap is a hash map that many threads can use at the same time without corrupting it. Its promise is about individual operations: each call to get, put, containsKey or remove behaves as if it happened at one instant, and the map's internal structure always stays valid. Reads do not take a lock at all, and writes lock only the small part of the table, the bin, that the key falls into.
What the map cannot promise is anything about a sequence of calls we make ourselves. Between our containsKey and our put, another thread can run any number of operations. The map has no idea that we meant those two calls to belong together. So the question to ask about any code that uses a concurrent collection is not whether each call is safe, but whether the decision we make from one call is still true when we make the next one.
2Race 1: Check-Then-Act on the First Hit
The first line of hit() checks whether the key exists and inserts 0 if it does not. That is a check followed by an action that depends on the check. Suppose the key "home" has never been seen and two threads call hit("home") at the same moment.
Both threads saw the key missing, because both checks ran before either insert. Thread B then reset the counter to zero after thread A had already counted. This race only happens on the first hit for each key, so it loses few counts, but it shows the pattern clearly: the answer to containsKey was already out of date when put ran.
3Race 2: Read-Modify-Write on Every Hit
The second race is worse because it happens on every call, not only the first. The expression counts.put(k, counts.get(k) + 1) is three steps: read the current value, add one in a local variable, write the result back. Nothing stops another thread from doing the same three steps in between.
6 messages in order. Play them, or step through them one at a time.
Both threads read 41 before either writes, so the second put overwrites the first and one hit disappears.
This is the classic lost update. Each get and each put was perfectly atomic, yet the final value is wrong. Under real load, with eight threads hitting a popular key, a test that sends one million hits can easily end with a count tens of thousands short, and the shortfall changes from run to run.
So the core lesson is that each method is atomic, but the sequence is not. To fix it we need the map itself to perform the read, the change and the write as one operation while it holds the lock on that key's bin.
4The Fix: merge Does the Whole Update Atomically
ConcurrentHashMap has methods that take a function and run it inside the map, under the bin lock, so no other thread can change that key in the middle. The best fit for counting is merge(key, value, function). If the key is absent, merge stores the given value. If it is present, it calls the function with the old value and the given value and stores the result. Both cases happen as one atomic step per key.
Notice that merge removes both races at once. There is no separate check, because merge handles the absent case itself, and there is no separate read, because the old value is handed to the function while the lock is held. The function should stay tiny, like Integer::sum, because other writers to the same bin wait while it runs.
An equivalent alternative is counts.compute(k, (key, v) -> v == null ? 1 : v + 1). It is correct too, but merge says the intent more directly and avoids the null check.
5For Very Hot Keys: One LongAdder per Key
merge is exact and fast for most workloads. But there is a catch when a handful of keys receive almost all the traffic. Every merge on the same key needs the same bin lock, so with 32 threads hammering "home", the threads queue up behind each other. Each update also allocates a new Integer once the value passes 127, the end of the small-integer cache.
For that case we store a LongAdder as the value. A LongAdder is a counter from java.util.concurrent.atomic that spreads increments across several internal cells, one per contending thread roughly, and adds them up only when we read it. The map is then only touched once per key, to create the adder.
| Approach | Correct? | Cost under heavy contention |
|---|---|---|
containsKey + put + get | No: two races | Loses counts silently |
merge(k, 1, Integer::sum) | Yes, atomic per key | Bin lock per hit, boxing above 127 |
computeIfAbsent + LongAdder | Yes, reads are approximate | Map touched once per key, increments spread |
computeIfAbsent creates exactly one LongAdder per key even if many threads arrive together, and after that every hit is a lock-free increment on the adder, not a write to the map. The trade-off is that sum() is not a snapshot: if increments are happening while we read, we may see some of them and not others. For metrics that is exactly what we want. If we needed to read and reset atomically, for example to ship a count every minute and start again, we would use sumThenReset() and accept the same fuzziness, or swap whole maps.
6Follow-up questions
Is AtomicInteger as a value as good as LongAdder?
It is correct and simpler: computeIfAbsent(k, x -> new AtomicInteger()).incrementAndGet(). Under light contention it is fine. Under heavy contention on one key, all threads spin on the same compare-and-set, so LongAdder scales better. AtomicInteger is the better choice when we need the exact new value back from each increment.
How would you prove the original code is broken?
Write a test that starts, say, 8 threads with a CountDownLatch so they begin together, has each call hit("k") 100,000 times, joins them and asserts the count equals 800,000. The original code fails most runs; the merge version passes every run. Tools like jcstress can show the race even more reliably.
7Conclusion
In this answer, we saw that the original hit() method has two separate races: check-then-act when a key appears for the first time, and read-modify-write on every increment. Each ConcurrentHashMap call was atomic, but the sequence of calls was not, so updates were lost. We rewrote it with merge(k, 1, Integer::sum), which performs the whole update atomically per key, and with a LongAdder per key for very hot counters, where contention on a single bin would otherwise become the bottleneck.
Open with
There are two races here. The first line is check-then-act: two threads can both call containsKey, both see the key missing, and both put zero, so one of them can reset a count the other already incremented.
Then, if they want more
The second line is read-modify-write: two threads can both get 41, both put 42, and one hit is lost. That one happens on every call, so under load the counts drift low. The important point is that every single call on ConcurrentHashMap is atomic, but a sequence of calls is not, because other threads can run between them.
The fix is to let the map do the whole update in one atomic operation. I would write counts.merge(k, 1, Integer::sum): if the key is absent it stores one, otherwise it adds one to the old value, and it does that while holding the lock on that key's bin.
If a few keys are extremely hot, I would store a LongAdder per key instead and call computeIfAbsent(k, x -> new LongAdder()).increment(), so the map is touched once per key and the increments are spread across cells instead of fighting over one bin lock. Reads with sum are then approximate while writes are happening, which is normally fine for metrics.
To prove it, I would run a multi-threaded test that checks the final count matches the number of hits.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Find the race conditions and rewrite:": https://scrivio-interview-library.netlify.app/java/concurrent-collections/a5186658bb/