Course contentsShow
← Java
Lesson 1163 of 2,87026. Map ImplementationsFree lesson

Null Keys and Values: Not Allowed in ConcurrentHashMap

Understand why ConcurrentHashMap prohibits null keys and values, unlike HashMap, to avoid ambiguity in concurrent contexts.

Null Keys and Values: Not Allowed in ConcurrentHashMap

What you'll learn: Why ConcurrentHashMap prohibits null keys and values, unlike HashMap, to avoid ambiguity in concurrent contexts.

The Core Difference

Unlike HashMap, which permits one null key and multiple null values, ConcurrentHashMap strictly forbids both null keys and null values. Attempting to insert either will throw a NullPointerException immediately.

Why This Restriction Exists

In single-threaded environments (like HashMap), if get(key) returns null, you can safely check containsKey(key) to determine whether the key doesn't exist or its value is actually null.

In concurrent environments, this two-step check creates ambiguity:

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

// Thread 1 checks:
if (map.get("user") == null) {
    // Is the key absent, or is the value null?
    // Before you can call containsKey()...
    
    // Thread 2 might have just added or removed "user"!
    // Your second check is now unreliable
}

Between the get() and containsKey() calls, another thread could modify the map, making your logic unreliable.

The Design Decision

By prohibiting nulls entirely, ConcurrentHashMap ensures that a null return from get() unambiguously means the key is absent. No follow-up check needed, no race condition possible.

This design choice prioritizes clarity and correctness in concurrent code over the flexibility that nulls might provide.

Practical Impact

Always use non-null sentinel values or Optional when working with ConcurrentHashMap if you need to represent "no value" semantics beyond simple absence from the map.

Key Takeaway: ConcurrentHashMap forbids null keys and values to eliminate ambiguity in concurrent scenarios—a null return from get() always means the key is absent, period.