Skip to main content
Java Intermediate Scenario-Based Topic: Collections & Concurrency

What is the difference between HashMap and ConcurrentHashMap?

Quick Summary: HashMap is non-thread-safe, permits one null key and null values, and fails fast during concurrent structural modification; ConcurrentHashMap is thread-safe using volatile reads, CAS operations, and fine-grained per-bucket synchronization without permitting null keys or values.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

HashMap provides O(1) average lookup for single-threaded code and allows one null key plus multiple null values. Under concurrent writes, unsynchronized updates can lose entries or corrupt buckets.

ConcurrentHashMap achieves thread-safe high concurrency by performing lock-free volatile reads for get() and synchronizing only the head node of an individual hash bucket (plus CAS insertion when a bin is empty), rather than locking the entire map.

Detailed Technical Explanation

Why does ConcurrentHashMap forbid null keys and values? Because in concurrent code, returning null from get(key) would create ambiguity between "the key does not exist" and "the key was explicitly mapped to null", breaking atomic read semantics since another thread could mutate the key between containsKey() and get().

In Java 8+, both HashMap and ConcurrentHashMap convert long hash-collision chains (≥ 8 nodes when capacity ≥ 64) into balanced Red-Black Trees (TreeBin), bounding worst-case lookup to O(log n).

Practical Walkthrough

Use atomic computeIfAbsent or merge on ConcurrentHashMap instead of check-then-act patterns.

Code Example — JAVA
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

public class HitCounterRegistry {
    private final ConcurrentHashMap<String, LongAdder> counters = new ConcurrentHashMap<>();

    public long recordHit(String endpoint) {
        LongAdder adder = counters.computeIfAbsent(endpoint, k -> new LongAdder());
        adder.increment();
        return adder.sum();
    }
}
Expected Output / Verification
Thread-safe endpoint counts updated concurrently without global lock contention.

Real-World Production Use Case

In-memory rate limiters, API metric counters, and feature-flag caches inside high-QPS Java backend services where thousands of worker threads read simultaneously while a background scheduler refreshes entries.

Common Interview Mistakes to Avoid

  • Writing non-atomic check-then-act code like if (!map.containsKey(k)) map.put(k, v) on a ConcurrentHashMap — use computeIfAbsent instead.
  • Trying to insert null keys or null values into ConcurrentHashMap, which immediately throws NullPointerException.
  • Calling Collections.synchronizedMap() under heavy contention where a coarse mutex blocks concurrent readers.
Topics: #java #hashmap #concurrenthashmap #concurrency
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.