HashMap Architecture: Bucket Treeification & ConcurrentHashMap
1Concept
HashMap uses an array of Node buckets (`Node<K,V>[] table`). Hash code is spread via bit-shift (`h ^ (h >>> 16)`). If bucket collisions exceed `TREEIFY_THRESHOLD = 8` and table size >= 64, the linked list is treeified into a Red-Black Tree (O(log N) worst case instead of O(N)). `ConcurrentHashMap` avoids full table locks, using bucket-level CAS and synchronized bin heads.
2Architecture Diagram
HashMap Bucket Table (Capacity 16 by default): Bucket [0] ---> null Bucket [1] ---> [Node K1,V1] -> [Node K2,V2] (Linked List collision) Bucket [2] ---> [ Red-Black Tree Root ] (Treeified if entries > 8!)
3Code Example
Core Java
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
public class MapArchitectureDemo {
public static void main(String[] args) {
// High-throughput thread-safe ConcurrentHashMap
ConcurrentHashMap<String, Integer> inventory = new ConcurrentHashMap<>();
inventory.put("SKU-1001", 50);
inventory.put("SKU-1002", 120);
// Atomic update without locking
inventory.compute("SKU-1001", (key, val) -> (val == null) ? 1 : val - 5);
System.out.println("Updated Inventory for SKU-1001: " + inventory.get("SKU-1001"));
// computeIfAbsent pattern
inventory.computeIfAbsent("SKU-1003", k -> 200);
System.out.println("Total Inventory Count: " + inventory.size());
}
}4Expected Output
Updated Inventory for SKU-1001: 45 Total Inventory Count: 3
5Key Takeaways
- ✓Default load factor is 0.75; resizing doubles table capacity when entries exceed `capacity * 0.75`.
- ✓HashMap allows one null key; ConcurrentHashMap does NOT permit null keys or values.
- ✓Java 8 treeification protects HashMaps against Hash-DoS attacks.