Java之ConcurrentHashMap线程安全原理

引言

对于Java程序员来说,HashMap是他们用到最多的映射(键值对)数据结构,但是HashMap是线程不安全的,在多线程的环境下,建议使用线程安全的ConcurrentHashMap。

锁机制

在JDK1.7及其之前,ConcurrentHashMap采用的是分段锁,也就是先将ConcurrentHashMap分成一定数量的段Segment,构成一个Segment数组,数组中的元素才是HashMap的键值对Node结点。可以理解为维护了一个Segment数组,数组中的元素是HashMap。

如此,在加锁时只需要对每个Segment段进行加锁即可,无需对整个ConcurrentHashMap加锁,提高了并发效率。

但是,对Segment段加锁,会导致统一段内的其它Node结点也无法被其它线程访问。

在JDK1.8及其之后,取消了分段机制,保留原有HashMap的数据结构,单独只对某一个Node结点进行加锁,不会影响其它结点,大大提高了锁粒度,提高了并发效率。

在JDK1.8及其之后,使用synchronized关键字以及CAS自旋锁保证多线程安全性。

当我们使用put方法新增键值对时:

1
2
3
public V put(K key, V value) {
return putVal(key, value, false);
}

会调用putVal方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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;
}

我们可以看到,当通过 (f = tabAt(tab, i = (n - 1) & hash)) == null 判断数组索引位置上没有数据时,就会通过casTabAt方法将Node结点直接加进去:

1
2
3
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}

tabAt方法会调用Unsafe类内的getObjectVolatile方法,该方法通过直接从内存中取值,确保数据是其它线程修改后上传的最新值。

1
2
3
4
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}

casTabAt方法会调用Unsafe类内的compareAndSwapObject方法,该方法通过CAS的方式保证将数据安全的修改。

可以看到,如果数组索引位上已经有结点数据的情况下,会使用synchronized锁住该结点,如果结点后面是链表或者红黑树,也可以保证只有当前线程可以访问(因为锁住了根结点,其它线程拿不到根结点,就无法向后遍历)。

扩容

在JDK1.7及其之前,Segment数组无法进行扩容,如果某个Segment内的Node数组达到了阈值,就单独对该Node数组进行扩容。这样,扩容的次数越多,每个Segment内的数组就越长,锁的灵活性就越差。

在JDK1.8及其之后,与原HashMap扩容机制基本一致,不过加入了多线程协助扩容机制:

可以看到,如果结点的hash值为MOVED也就是-1,就认为当前数组正在扩容,就会调用helpTransfer方法协助扩容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT;
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
if (sc == rs + MAX_RESIZERS || sc == rs + 1 ||
transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}

总数

多线程环境下,如何保证size方法获取到的结点总数量是正确的?

1
2
3
4
5
6
7
public int size() {
long n = sumCount();
return ((n < 0L) ? 0 :
(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
(int)n);
}

size方法调用了sumCount方法:

1
2
3
4
5
6
7
8
9
10
11
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;
}

可以看到,除了基础的总数baseCount外,ConcurrentHashMap还维护了一个CounterCell数组,通过将baseCount与CounterCell数组中的每个数相加得到最终总数。

在putVal方法的最后调用了addCount方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
s = sumCount();
}
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT;
if (sc < 0) {
if (sc == rs + MAX_RESIZERS || sc == rs + 1 ||
(nt = nextTable) == null || transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
else if (U.compareAndSwapInt(this, SIZECTL, sc, rs + 2))
transfer(tab, null);
s = sumCount();
}
}
}

addCount会先通过CAS尝试直接增加baseCount:

如果失败,则随机在CounterCell数组内增加:

增加完总数后,还要判断一下是否需要扩容:

CAS

CAS全称CompareAndSwap,也就是自旋锁。

其本质上并不是锁,只是通过循环比较来不断尝试:

CAS会拿到一个要修改的旧值A,想将其改为新值B,然后访问内存中的当前值C,

判断如果内存值C与自己的旧值A不相等,则认为当前有其它线程在访问该数据,自己就先放弃修改,

然后循环再次比较C与A,如果一直不相等就一直循环直至相等,

此时如果内存值C与自己的旧值A相等,那么认为当前没有其它线程访问该数据,将该数据该为新值B,结束CAS。

CAS会直接从内存中读取数据,并且可以保证读写操作的原子性。

需要注意的是,CAS并不能保证数据的可见性,它无法保证从内存中读取的数据C是最新的值,也无法保证修改后的值B可以被其他线程同步。我们应该结合可以保证数据可见性的关键字volatile使用:


Java之ConcurrentHashMap线程安全原理
https://www.wananhome.site/2024/12/01/Java之ConcurrentHashMap线程安全原理/
作者
WanAn
发布于
2024年12月1日
许可协议