核心原理
为什么需要 ConcurrentHashMap
HashMap:非线程安全Hashtable:整张表synchronized,并发度低,不推荐ConcurrentHashMap:细粒度并发控制,现代并发 Map 首选
JDK 1.7:Segment 分段锁
Segment 数组 + HashEntry 链表;每个 Segment 一把 ReentrantLock,只锁一段数据,提高并发度。
JDK 1.8:对齐 HashMap + 桶级锁
去掉 Segment;结构为数组 + 链表/红黑树。
- 空桶:CAS 插入
- 非空:synchronized 锁桶头(或
TreeBin) - 不允许
null键和null值(避免二义性)
Map<String, Integer> concurrent = new ConcurrentHashMap<>();concurrent.put("Tom", 90);// concurrent.put(null, 1); // NPE与 HashMap 对比
| HashMap | ConcurrentHashMap | |
|---|---|---|
| 线程安全 | 否 | 是 |
| null | 允许 null 键/值 | 不允许 |
| JDK 8 并发 | — | CAS + synchronized 锁桶 |
常见陷阱
在 ConcurrentHashMap 中使用 null 键或 null 值会 NullPointerException。
面试速记
HashMap vs ConcurrentHashMap:线程安全、null 策略;1.8 CHM 用 CAS + 锁桶头,比 Hashtable 粒度更细。