Engineering With Java

Engineering With Java

Java Interview Question - The ConcurrentHashMap Trap

It was thread-safe… until the threads showed up

Suraj Mishra's avatar
Suraj Mishra
Aug 12, 2026
∙ Paid

Context

A payment platform keeps track of how many API requests each merchant has made. To make it thread-safe, the team replaced a HashMap with a ConcurrentHashMap.

A few weeks later, operations noticed something strange: The total request count is consistently lower than the number of requests recorded by the load balancer. There are no exceptions, no failed requests and CPU and memory look healthy.

The only symptom is that some increments disappear under heavy load.


🚀 Level up your Java & Spring Boot skills.

Join 8100+ developers and get weekly, no-fluff content featuring practical coding tips, real-world backend insights, and interview questions based on production scenarios.

Founding Member Offer: Lock in founding member price at $50/year (~$4/month) for life. Limited spot left.

So far we have covered 70+ real world based interview questions and will add up to 100 by end of this year.

Testimonials


The application uses a ConcurrentHashMap. Shouldn't this code be thread-safe?

ConcurrentHashMap guarantees thread safety for individual operations—not for a sequence of operations.

The following sequence is not atomic:

get(...)
modify(...)
put(...)

Multiple threads can observe the same value simultaneously.

Race condition example:

merchant A = 10. Two requests arrive at exactly the same time.

Thread A : get() → 10, Thread B: get() → 10

Both threads calculate: 10 + 1 = 11

Thread A writes → put(11). Thread B writes → put(11)

Final value → 11 vs Expected → 12

One increment silently disappears. And we don’t get any exception and warning. Just incorrect business data. This is a classic lost-update race condition.

What solution do you propose to fix this?

User's avatar

Continue reading this post for free, courtesy of Suraj Mishra.

Or purchase a paid subscription.
© 2026 Suraj Mishra · Privacy ∙ Terms ∙ Collection notice
Start your SubstackGet the app
Substack is the home for great culture