RSS Amplifier

Engineering With Java · Aug 12, 2026

Java Interview Question - The ConcurrentHashMap Trap

0
Sign in to vote or save

Suraj Mishra · Engineering With Java

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.

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:

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?

Read the original on javabulletin.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.