Unlocking Java’s ConcurrentHashMap: Deep Dive into JDK 7 & 8 Implementations
This article explains how Java's ConcurrentHashMap provides thread‑safe, high‑performance map operations by comparing the segmented‑lock design of JDK 7 with the fine‑grained locking and CAS approach of JDK 8, and includes a practical multithreaded code example.
ConcurrentHashMap is a thread‑safe hash table implementation in Java, designed for high‑concurrency environments.
When multiple threads need to operate on a map, ConcurrentHashMap outperforms Hashtable or synchronizedMap because it uses lock‑splitting and CAS techniques to achieve higher concurrency.
ConcurrentHashMap Principles
Understanding why ConcurrentHashMap performs better requires a look at its underlying implementation in different JDK versions.
Implementation in JDK 7
JDK 7 uses a segmented lock mechanism: the map consists of an array of Segment objects, each acting as an independent hash table with its own lock.
This allows multiple threads to access different segments simultaneously, though uneven data distribution can cause bottlenecks.
Implementation in JDK 8
JDK 8 removes the segmented lock, adopting finer‑grained locks and CAS operations similar to HashMap. The structure is an array of Node objects that may form linked lists or red‑black trees.
Put operations first attempt a CAS insertion; on failure, they fall back to synchronized handling of the conflicting bucket, reducing lock contention.
ConcurrentHashMap in Practice
The following example demonstrates multiple threads updating the same key concurrently while the map maintains correct counts.
public class ConcurrentAccessExample {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
ExecutorService executor = Executors.newFixedThreadPool(3);
// Three threads concurrently update "apple" count
for (int i = 0; i < 3; i++) {
executor.submit(() -> {
for (int j = 0; j < 1000; j++) {
map.merge("apple", 1, Integer::sum);
}
});
}
executor.shutdown();
while (!executor.isTerminated()) {
// wait for tasks to finish
}
System.out.println("Final Apple count: " + map.get("apple"));
}
}This example shows that ConcurrentHashMap’s internal thread‑safety mechanisms allow correct updates even under high concurrency.
Mastering ConcurrentHashMap’s design and usage is essential for writing efficient concurrent Java code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
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.
