Understanding ConcurrentHashMap: Implementation Differences between JDK 1.7 and JDK 1.8
This article explains why ConcurrentHashMap provides thread‑safe and high‑performance map operations, compares it with HashMap and Hashtable, and details the architectural changes from JDK 1.7’s segment‑lock design to JDK 1.8’s array‑list‑red‑black‑tree and CAS‑based implementation.
ConcurrentHashMap is a thread‑safe and efficient container; the article explores why it can guarantee both safety and performance.
It compares ConcurrentHashMap with HashMap (non‑thread‑safe, can cause infinite loops during resize) and Hashtable (uses a single synchronized lock, leading to low concurrency).
When HashMap expands, concurrent resize may create a circular linked list, causing dead loops and 100% CPU usage.
Hashtable protects data with a global lock, which serializes all access and degrades throughput.
ConcurrentHashMap employs lock‑striping (segment locks) so that different segments are locked independently, allowing multiple threads to operate on different segments simultaneously.
JDK 1.7 implementation : uses an array of Segment objects, each segment containing an Entry array and a ReentrantLock . The default number of segments is 16, allowing up to 16 concurrent write operations on different segments.
The segment‑lock design reduces lock contention but adds extra hashing overhead compared with a plain HashMap .
JDK 1.8 implementation : abandons segments and introduces a unified Node array. Each node stores key , value , hash , and a next reference, with volatile fields for visibility. The structure combines an array, linked list, and red‑black tree; when a bucket’s list exceeds a threshold, it is transformed into a tree to achieve O(log N) lookup.
JDK 1.8 relies heavily on CAS (compare‑and‑swap) operations, which are optimistic locks that retry in a spin loop until the expected value matches, providing lock‑free updates for most cases.
Overall, the segment‑lock approach of JDK 1.7 improves concurrency over Hashtable , while JDK 1.8’s CAS‑based, tree‑augmented design further boosts performance and scalability.
In summary, understanding the differences between HashMap , Hashtable , and ConcurrentHashMap across JDK 1.7 and JDK 1.8 is essential for Java interview preparation.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.