ConcurrentHashMap源码阅读03
前言
为了更快速方便地理解ConcurrentHashMap的设计原理,这篇文章我们主要从以下几个视角来探讨ConcurrentHashMap的内部实现:内部结构、初始化、put操作的不同情况、扩容流程、线程安全及红黑树的转化等。
1、数据结构
2、默认初始化
3、put操作的不同情况
4、扩容流程
5、线程安全的原理
6、红黑树转化
正文
一、数据结构
与HashMap相同,ConcurrentHashMap中用于存储的存储单元也是Node<K,V>,由Node<K,V>这样的链表结构数组形成了ConcurrentHashMap的存储数据结构。
每个键值对代表一个Node<K,V>,属性由key、value、hash、next组成,每个节点都指向下一个节点。每个键值对按hash值运算出自己的落点在哪个索引位置。
二、默认初始化
/**
* Initializes table, using the size recorded in sizeCtl.
* 初始化表,使用记录在sizeCtl大小。
*/
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
//判断是否需要初始化
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)
//如果判断成立,说明有其他线程正在执行,则将当前线程由RUNNING转为READY状态,等待OS调度。
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
//确保当前线程进行线程安全的操作,当没有其他线程干扰时,将SIZECTL变为-1
try {
if ((tab = table) == null || tab.length == 0) {
//当链表数组为空时,对其进行初始化,默认容量是16
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
三、put操作的不同情况
在上一篇文章ConcurrentHashMap源码阅读02中,我们列出了put操作的几种情况:
(1)链表数组为空时进行初始化
此种情况在上面已说明。
(2)hash运算落点未被占用
此时ConcurrentHashMap正常进行put操作,将value组装成Node<K,V>并放入对应的落点位置上。
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
}
其中,tabAt方法与casTabAt方法均为原子操作,确保线程安全。
(3)hash运算落点被占用,但原节点hash值为-1
此时ConcurrentHashMap判断可能正在扩容,需要进行特殊处理,即调用helpTransfer方法:
/**
* Helps transfer if a resize is in progress.
*/
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
//判断节点为扩容时产生的特殊节点ForwardingNode且拥有一个链表节点数组时成立
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
//将当前链表节点数组中的节点放入ForwardingNode的链表节点数组中
int rs = resizeStamp(tab.length);
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}
(4)hash运算落点被占用,原节点hash值正常
将形成链表节点,利用同步关键字synchronized 来保证同步。
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;
}
若是同一个key,则将旧值替换为新值;若不是同一个key,但hash计算落点相同,则组装成Node<K,V>放入链表末端。
若当前节点是树节点,则按红黑树的规则放入树节点。
若节点数大于8,则将当前链表节点数组转化为红黑树结构。
四、扩容流程
这里我们结合测试案例进行分析:
测试案例如下(与HashMap测试案例类似):
@Test
public void test(){
Map<String,Object> map = new ConcurrentHashMap<String, Object>();
// map.put("s",1);
map.put("a",1);
map.put("b",2);
map.put("c",3);
map.put("hd",4);
map.put("hdi",4);
map.put("hdaq",4);
map.put("hderm",4);
map.put("hdermh",4);
map.put("hdermeN",4);
map.put("hdermera",4);
map.put("hdermeqco",4);
map.put("I",4);
map.put("l",4);
map.put("J",4);
map.put("K",4);
map.put("M",4);
Integer i = (Integer) map.get("a");
System.out.println(i);
}
我们重点分析执行到put(“I",4)之前的变化,当put(“hdermeqco”,4)操作完成后,ConcurrentHashMap形成了一条长度为8的链表,索引位置为12,如图示:
当执行到put(“I”,4)时,此时Map中键值对个数达到12,触发扩容,这里我们将扩容流程与HashMap做下对比:
相同的是,无论是ConcurrentHashMap还是HashMap,它们都对原链表数组做了长度倍增,是原链表数组长度的2倍,并且都对原有键值对节点重新进行了hash运算得出新的索引位置并将其放入。
不同的是,对单个链表的处理,在原有一分为二的基础上,ConcurrentHashMap采用了倒插法对链表上节点进行排序,如图所示:
从源码角度来看,主要分为几个步骤:
1、扩容入口:
扩容的入口代码在putVal方法中:
addCount(1L, binCount);
看看这个方法:
/**
* Adds to count, and if table is too small and not already
* resizing, initiates transfer. If already resizing, helps
* perform transfer if work is available. Rechecks occupancy
* after a transfer to see if another resize is already needed
* because resizings are lagging additions.
*
* @param x the count to add
* @param check if <0, don't check resize, if <= 1 only check if uncontended
*/
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);
if (sc < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (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 << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
2、上述方法主要看下后半部分,while判断当前节点数量到达扩容阈值sizeCtl时,会开始进行扩容准备,在扩容前将sizeCtl置为负值,进入transfer方法。
3、扩容的核心方法:
/**
* Moves and/or copies the nodes in each bin to new table. See
* above for explanation.
*/
private 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;
}
}
}
}
}
}
首先,生成了一个长度为原链表数组长度的2倍的新链表数组作为nextTable,并生成了ForwardingNode节点(hash值为-1的特殊节点)。
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
nextTab = nt;
nextTable = nextTab;
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
接着,从原链表数组的尾部开始往头部遍历,若当前位置上无节点,则放入ForwardingNode节点;若当前位置上有节点的,进入利用synchronized加锁的方法,将原节点重新计算位置后,要么放入原位置,要么放入(i+n)的位置。【i:代表原位置,n代表原链表数组的长度,即扩容长度】。当然其中也包含了对链表与红黑树的处理。
上述动作完成后,原链表数组上所有位置均已放置ForwardingNode节点,所有节点已转移到新的链表数组上。
最后,ConcurrentHashMap还要进行一次recheck,仍然是从尾部到头部遍历一次,检查原链表数组上所有节点是否都已转移并置为ForwardingNode节点,保证线程安全。检查完毕后,将nextTable置为null,table置为新链表数组,sizeCtl置为新链表长度的四分之三。
扩容结束。
五、线程安全的原理
(1)UnSafe类的使用
从ConcurrentHashMap的源码中我们可以看到,有大量使用sun.misc.Unsafe的地方,如:
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);
}
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);
}
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
上面的U即sun.misc.Unsafe的实例。这里,需要稍微介绍下sun.misc.Unsafe这个类,这个类为利用Java进行开发时不能直接操作内存的情况,开辟了一条可以直接操作内存的通道,并且Unsafe中提供了int,long和Object的CAS操作:
public final native boolean compareAndSwapObject(Object var1, long var2, Object var4, Object var5);
public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);
public final native boolean compareAndSwapLong(Object var1, long var2, long var4, long var6);
CAS:Compare and Swap,即比较再交换。CAS操作具有原子性,适用于多线程并发的场景。详细原理可以参考这篇文章:CAS原理
通过总结,在对链表数组落点位置进行判空或取值或赋值时,均采用了Unsafe的API操作来保证线程安全。
在put操作中就用到了Unsafe的API,在进行链表数组初始化时,通过CAS操作来保证只要有一个线程开始执行初始化操作后,其他线程都只能处于ready状态,不再参与初始化,等待调度。
在判断hash落点上是否存在节点时,利用了Unsafe的Volatile操作,直接从主内存中获取到当前落点上的节点并进行判空,避免在多线程场景下,出现缓存一致性问题。
接下来,同样采用了CAS操作来保证只有一个线程能为当前落点赋值,新增节点。
在扩容过程中,如何保证ConcurrentHashMap的线程安全?
当ConcurrentHashMap进入扩容流程后,若有其他线程同时操作链表数组,则会分几种情况处理:
1、当前操作节点还未置为ForwardingNode节点,此时按正常情况处理,该怎么来怎么来;
2、当前操作节点已被置为ForwardingNode节点,说明当前节点已被搬运至新链表数组中。此时进入helpTransfer方法,若此时刚刚好扩容完成,则直接返回nextTab,继续操作;
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
int rs = resizeStamp(tab.length);
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
3、接着上述情况,若此时扩容仍在进行,则此线程一样开始执行transfer方法,同原本执行扩容任务的线程一起完成扩容任务。
(2)分段锁的使用(JDK1.7)
在JDK1.8中,Segment已不被使用,分段锁技术已被粒度更小的自旋锁替代,并获得了更好的性能。
/**
* Stripped-down version of helper class used in previous version,
* declared for the sake of serialization compatibility
*/
static class Segment<K,V> extends ReentrantLock implements Serializable {
private static final long serialVersionUID = 2249069246763182397L;
final float loadFactor;
Segment(float lf) { this.loadFactor = lf; }
}
(3)自旋锁的应用
在addCount方法中,有这样一段代码:
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();
}
当对baseCount的CAS操作失败时,说明此时有多个线程同时竞争资源,这时进入fullAddCount方法,这个方法里面利用CounterCell数组进行计数,将未竞争到资源的线程以线程为粒度,生成一个CounterCell 数组,并利用无限循环和CAS模拟出一个自旋锁来保证线程安全。锁的状态只有两种:0和1。这段代码逻辑中包含了CounterCell 数组的初始化与扩容,初始化容量为2,扩容倍数始终为2倍,最大不超过CPU核心数。
六、红黑树的转化
关于红黑树的转化,这一块与HashMap中大致相同,当链表节点数达到8时,进行树结构转化,当树节点数量达到6时,进行链表转化,其他不做解读。
在进行树结构转化时,若链表数组节点数量未达到64时,会调用tryPresize方法:
if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
tryPresize(n << 1);
这个方法里面会调用扩容方法:
/**
* Tries to presize table to accommodate the given number of elements.
*
* @param size number of elements (doesn't need to be perfectly accurate)
*/
private final void tryPresize(int size) {
int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(size + (size >>> 1) + 1);
int sc;
while ((sc = sizeCtl) >= 0) {
Node<K,V>[] tab = table; int n;
if (tab == null || (n = tab.length) == 0) {
n = (sc > c) ? sc : c;
if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if (table == tab) {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
}
}
else if (c <= sc || n >= MAXIMUM_CAPACITY)
break;
else if (tab == table) {
int rs = resizeStamp(n);
if (sc < 0) {
Node<K,V>[] nt;
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (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 << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
}
}
}
当有其他线程正在扩容时或者还没有线程扩容时,都会进行扩容操作。
参考
[1]Map 大家族的那点事儿 ( 7 ) :ConcurrentHashMap ( 下 ) :http://www.sohu.com/a/254192521_355142
[2]Java中的Unsafe:https://www.jianshu.com/p/db8dce09232d