ConcurrentHashMap: Thread-Safety Engine
hardConcurrentHashMapConcurrencyCASLockFreePerformance
In a multi-threaded world, HashMap is a liability. ConcurrentHashMap provides a thread-safe implementation that maximizes throughput without the global locking bottleneck of Hashtable.
1. Evolution: JDK 1.7 vs. JDK 1.8+
- JDK 1.7 (Segmented Locking): Used an array of 16
Segments(each a separate lock). Concurrency was limited to the number of segments. - JDK 1.8+ (Node Locking): Switched to Bucket-Level Synchronization. It uses CAS for empty buckets and
synchronizedonly on the head node of a bucket for collisions. - Lock-Free Reads: It uses
volatileon node values and thenextpointer, allowing theget()operation to be entirely lock-free.
2. Parallel Resizing: Group Effort
Resizing a massive map is slow. ConcurrentHashMap allows multiple threads to assist in the process:
- A thread finding a
ForwardingNodeduring aputwill join the transfer effort. - The map is split into "strides" (typically 16 buckets), and each thread moves its own stride to the new table.
3. Atomic Compute: Beyond Get/Put
Standard "Check-then-Act" sequences (if not exists, put) are NOT thread-safe in a normal Map. ConcurrentHashMap provides atomic methods to handle this:
map.computeIfAbsent(key, k -> new ExpensiveObject());
map.merge(key, value, (oldVal, newVal) -> oldVal + newVal);
These ensure the entire logic (check, create, insert) is atomic for that specific key.
4. Why No Nulls?
ConcurrentHashMap prohibits null keys and values to prevent Ambiguity in concurrent environments. See the "Collections" overview for the full technical rationale.