1.写在前面
上一篇文章我们从ConcurrentHashMap的日常使用开始,讲解了ConcurrentHashMap的源码,这篇文章我计划再深入研究一下ConcurrentHashMap的源码。我先抛出几个问题看看大家有没有思考过:
- ConcurrentHashMap 与 HashMap 有什么区别?
- ConcurrentHashMap 的内部结构是怎样的?
- ConcurrentHashMap 是如何实现线程安全的?
- 为什么 ConcurrentHashMap 不允许 null 键和值?
- 在 Java 8 及之后ConcurrentHashMap如何进行扩容?
- ConcurrentHashMap 的 computeIfAbsent 方法是如何实现的?
- ConcurrentHashMap 的 size() 方法是线程安全的吗?
2. ConcurrentHashMap 与 HashMap 有什么区别?
- 线程安全性:HashMap 不是线程安全的,而 ConcurrentHashMap 是线程安全的
- 性能:在多线程环境中,ConcurrentHashMap 的性能优于 HashMap + Collections.synchronizedMap() 或 HashTable。
- 锁机制:在 Java 8 之前,ConcurrentHashMap 使用分段锁(Segment);在 Java 8 及之后,使用 CAS 操作和细粒度锁。
- Null 值:HashMap 允许存储 null 键和 null 值,而 ConcurrentHashMap 不允许
3. ConcurrentHashMap 是如何实现线程安全的?
ConcurrentHashMap 通过多种机制实现线程安全,包括分段锁(在 Java 8 之前)、CAS 操作和细粒度锁(在 Java 8 及之后)。下面我们通过源代码来详细说明这些机制。
3.1 Java 8 之前的实现(分段锁)
在 Java 8 之前,ConcurrentHashMap 使用了分段锁机制。整个哈希表被分成多个 Segment,每个 Segment 类似于一个小的哈希表,并且有自己的锁。只有在访问同一个 Segment 时,线程才需要竞争锁。
// Segment 类是 ConcurrentHashMap 的一个内部类
static final class Segment<K,V> extends ReentrantLock implements Serializable {
// Segment 内部是一个 HashEntry 数组
transient volatile HashEntry<K,V>[] table;
// 获取值的方法
V get(Object key, int hash) {
if (count != 0) { // read-volatile
HashEntry<K,V> e = getFirst(hash);
while (e != null) {
if (e.hash == hash && key.equals(e.key)) {
V v = e.value;
if (v != null) {
return v;
}
return readValueUnderLock(e); // recheck
}
e = e.next;
}
}
return null;
}
// 插入值的方法
V put(K key, int hash, V value, boolean onlyIfAbsent) {
lock();
try {
int c = count;
if (c++ > threshold) // ensure capacity
rehash();
HashEntry<K,V>[] tab = table;
int index = (tab.length - 1) & hash;
HashEntry<K,V> first = tab[index];
HashEntry<K,V> e = first;
while (e != null && (e.hash != hash || !key.equals(e.key)))
e = e.next;
V oldValue;
if (e != null) {
oldValue = e.value;
if (!onlyIfAbsent)
e.value = value;
} else {
oldValue = null;
++modCount;
tab[index] = new HashEntry<K,V>(key, hash, first, value);
count = c; // write-volatile
}
return oldValue;
} finally {
unlock();
}
}
}
3.2 Java 8 及之后的实现(CAS 和细粒度锁)
在 Java 8 及之后,ConcurrentHashMap 使用了 CAS 操作和细粒度锁来实现线程安全,并且引入了红黑树来优化哈希冲突严重的场景。
3.2.1 核心数据结构
// Node 类是 ConcurrentHashMap 的基本单元
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;
Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.val = val;
this.next = next;
}
}
3.2.2 获取值的方法
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
3.2.3 插入值的方法
public V put(K key, V value) {
return putVal(key, value, false);
}
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key || (ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key, value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
3.3 关键机制
- CAS 操作:利用 Unsafe 类的 compareAndSwap 方法,尝试无锁地更新某些字段,失败时再使用锁机制。
- 细粒度锁:在链表或树的头节点上加锁,确保在并发修改时,只有涉及到的部分会被锁住,减少锁竞争。
- 红黑树:当链表长度超过一定阈值(默认是 8)时,链表会转换为红黑树,以提高查找和插入的性能。
- 分段锁:在 Java 8 之前,使用分段锁机制,每个 Segment 都有自己的锁,减少锁竞争。
4. 为什么 ConcurrentHashMap 不允许 null 键和值?
4.1 避免歧义
在使用 Map 接口时,如果 get(key) 方法返回 null,有两种可能性:
- 该键不存在于映射中。
- 该键存在,但其对应的值是 null。
在非并发环境中,这种歧义可以通过 containsKey(key) 方法来消除。但在并发环境中,情况变得更加复杂,因为在调用 containsKey(key) 和 get(key) 之间,键值对可能已经被其他线程修改或删除。
4.2 避免潜在的错误
在并发环境中,允许 null 键和值可能会导致一些未定义的行为和潜在的错误。例如:
- 如果 put(key, null) 允许,则在多线程环境中,可能会有多个线程尝试插入或修改相同的键,这会导致不一致的状态。
- 如果 remove(key) 允许 null 键,则可能会有多个线程尝试删除相同的键,这也会导致不一致的状态。
- 允许 null 键和值会使得代码的逻辑更加复杂,增加了潜在的错误和调试的难度。
4.3 简化内部实现
不允许 null 键和值可以简化 ConcurrentHashMap 的内部实现,使得代码更容易维护和优化。例如:
- 在实现 computeIfAbsent、merge 等方法时,不需要额外处理 null 值的情况。
- 在实现哈希表的扩容和迁移时,不需要考虑 null 值的特殊处理。
4.4 与其他并发集合保持一致
Java 中的其他并发集合类,如 ConcurrentSkipListMap 和 ConcurrentSkipListSet,同样不允许 null 键和值。保持一致的行为有助于减少开发者的困惑和误用。
5. 在 Java 8 及之后ConcurrentHashMap如何进行扩容?
5.1 扩容触发条件
当 ConcurrentHashMap 的某个桶(bucket)中的链表或树的节点数量超过一定阈值(例如,链表长度超过 8 且总节点数超过 64),或者当总节点数超过当前容量的负载因子(load factor)时,会触发扩容操作。
5.2 扩容过程
扩容过程主要包括以下几个步骤:
5.2.1 初始化新的数组
扩容时,首先会创建一个新的数组,新的数组长度是旧数组长度的两倍。
Node<K,V>[] newTable = (Node<K,V>[])new Node[newCap];
5.2.2 标记旧数组正在进行扩容
在扩容过程中,旧数组的某些桶会被标记为 ForwardingNode,表示这些桶已经被迁移。
static final class ForwardingNode<K,V> extends Node<K,V> {
final Node<K,V>[] nextTable;
ForwardingNode(Node<K,V>[] tab) {
super(MOVED, null, null, null);
this.nextTable = tab;
}
}
5.2.3 并发迁移
迁移过程是并发进行的,多个线程可以同时参与迁移操作。每个线程会尝试获取自己负责的桶范围,然后将这些桶中的节点迁移到新的数组中。
final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { // initiating
try {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
transferIndex = n;
}
int nextn = nextTab.length;
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
else if (U.compareAndSwapInt(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
if (fh >= 0) {
int runBit = fh & n;
Node<K,V> lastRun = f;
for (Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
if (runBit == 0) {
ln = lastRun;
hn = null;
}
else {
hn = lastRun;
ln = null;
}
for (Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
else if (f instanceof TreeBin) {
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> lo = null, loTail = null;
TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}
5.2.4 更新引用
当所有桶都已经迁移完毕后,旧数组的引用会被更新为新的数组,完成扩容操作。
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
5.3 关键机制
- 分段迁移:扩容时,多个线程可以同时参与迁移操作,每个线程负责一个或多个桶的迁移,减少了单个线程的负担,提高了扩容效率。
- ForwardingNode:在迁移过程中,旧数组的某些桶会被标记为 ForwardingNode,表示这些桶已经被迁移。其他线程访问这些桶时,会被重定向到新的数组,避免了重复迁移。
- CAS 操作:使用 CAS 操作来确保多个线程在迁移过程中不会发生冲突,保证了并发安全。
6. ConcurrentHashMap 的 computeIfAbsent 方法是如何实现的?
ConcurrentHashMap 的 computeIfAbsent 方法是一个非常有用的操作,它允许在键不存在时计算其值并将其插入到映射中,同时保证线程安全。下面是 computeIfAbsent 方法的实现细节。
6.1 方法签名
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
6.2 方法实现
以下是 computeIfAbsent 方法的完整代码:
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
if (key == null || mappingFunction == null) throw new NullPointerException();
int h = spread(key.hashCode());
V val = null;
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
if (casTabAt(tab, i, null, r)) {
binCount = 1;
Node<K,V> node = null;
try {
if ((val = mappingFunction.apply(key)) != null)
node = new Node<K,V>(h, key, val, null);
} finally {
setTabAt(tab, i, node);
}
}
}
if (binCount != 0)
break;
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
boolean added = false;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek; V ev;
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek)))) {
val = e.val;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
if ((val = mappingFunction.apply(key)) != null) {
added = true;
pred.next = new Node<K,V>(h, key, val, null);
}
break;
}
}
}
else if (f instanceof TreeBin) {
binCount = 2;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((p = t.putTreeVal(h, key, val)) != null)
val = p.val;
else if ((val = mappingFunction.apply(key)) != null) {
added = true;
t.putTreeVal(h, key, val);
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (!added)
break;
}
}
}
if (val != null)
addCount(1L, binCount);
return val;
}
6.3 主要步骤解析
6.3.1 空值检查
if (key == null || mappingFunction == null) throw new NullPointerException();
6.3.2 计算哈希值
int h = spread(key.hashCode());
6.3.3 循环处理
使用一个无限循环来处理并发情况,直到成功插入或找到值
6.3.4 初始化表格
if (tab == null || (n = tab.length) == 0)
tab = initTable();
如果表格未初始化或长度为 0,则进行初始化。
6.3.5 尝试插入新节点
else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
Node<K,V> r = new ReservationNode<K,V>();
synchronized (r) {
if (casTabAt(tab, i, null, r)) {
binCount = 1;
Node<K,V> node = null;
try {
if ((val = mappingFunction.apply(key)) != null)
node = new Node<K,V>(h, key, val, null);
} finally {
setTabAt(tab, i, node);
}
}
}
if (binCount != 0)
break;
}
如果对应桶为空,则尝试插入一个新的 ReservationNode,并计算值插入新节点。
6.3.6 处理迁移中的表格
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
如果该桶正在迁移,则帮助完成迁移。
6.3.7 处理非空桶
else {
boolean added = false;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek; V ev;
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek)))) {
val = e.val;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
if ((val = mappingFunction.apply(key)) != null) {
added = true;
pred.next = new Node<K,V>(h, key, val, null);
}
break;
}
}
}
else if (f instanceof TreeBin) {
binCount = 2;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((p = t.putTreeVal(h, key, val)) != null)
val = p.val;
else if ((val = mappingFunction.apply(key)) != null) {
added = true;
t.putTreeVal(h, key, val);
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (!added)
break;
}
}
- 如果桶不为空,首先检查是否正在迁移。
- 如果不是迁移中的桶,则对桶进行加锁。
- 如果是链表结构,则遍历链表查找键,如果找到则返回对应值;如果未找到则插入新节点。
- 如果是树结构,则使用树的插入方法进行处理。
6.3.8 更新计数
if (val != null)
addCount(1L, binCount);
7. ConcurrentHashMap 的 size() 方法是线程安全的吗?
ConcurrentHashMap 的 size() 方法在 Java 8 及之后的实现中是线程安全的,但它并不是一个严格意义上的瞬时精确值。由于 ConcurrentHashMap 允许并发修改,size() 方法返回的值可能是一个近似值,而不是一个瞬时精确的值。
7.1 size() 方法的实现
ConcurrentHashMap 的 size() 方法通过遍历所有的计数器槽(counter cells)来计算总的元素数量。以下是 size() 方法的实现代码:
public int size() {
long n = sumCount();
return ((n < 0L) ? 0 : (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)n);
}
7.2 sumCount() 方法
sumCount() 方法用于计算所有计数器槽的总和:
final long sumCount() {
CounterCell[] as = counterCells; CounterCell a;
long sum = baseCount;
if (as != null) {
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum;
}
7.3 线程安全性
- 线程安全性:size() 方法是线程安全的,因为它在计算期间不会导致数据竞争或抛出异常。它读取的所有数据结构(如 baseCount 和 counterCells)都是通过原子操作更新的,确保了读取时的线程安全性。
- 近似值:由于 ConcurrentHashMap 允许并发修改,size() 方法返回的值可能不是瞬时精确的值。例如,在计算过程中,其他线程可能正在插入或删除元素,这会导致 size() 方法返回一个近似值。
7.4 适用场景
- 统计信息:如果你需要一个大致的元素数量用于统计或监控,size() 方法是非常适合的。
- 精确计数:如果你需要一个瞬时精确的元素数量,ConcurrentHashMap 可能不是最佳选择。你可能需要使用其他数据结构或额外的同步机制来确保精确计数。