@TOC
前言
相信多数读者都知道细品ConcurrentHashMap是一个并发安全的hashmap,其之所确保安全的原理可能就有读者不知,笔者之前也不曾了解,所以趁闲暇时间来学习学习。
正文
本文是基于jdk1.8进行的学习,对1.7的concurrenthashmap源码不做讨论。
get方法
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
// spread相当于hashmap中的hash方法
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;
}
概览一遍,和hashmap中的get方法没有什么差异,如果有读者对hashmap的底层不了解的话,可以自行查询资料或者查看笔者写的hashmap源码解读系列
唯一的差异在tabAt
方法,这个方法读者应该清楚这是为了定位在table中的某个下标的方法。
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);
}
读者疑惑其中的U,ASHIFT,ABASE变量是什么含义,hashmap中并不存在这种变量的定义。
// Unsafe mechanics
private static final sun.misc.Unsafe U;
private static final long SIZECTL;
private static final long TRANSFERINDEX;
private static final long BASECOUNT;
private static final long CELLSBUSY;
private static final long CELLVALUE;
private static final long ABASE;
private static final int ASHIFT;
static {
try {
U = sun.misc.Unsafe.getUnsafe();
Class<?> k = ConcurrentHashMap.class;
SIZECTL = U.objectFieldOffset
(k.getDeclaredField("sizeCtl"));
TRANSFERINDEX = U.objectFieldOffset
(k.getDeclaredField("transferIndex"));
BASECOUNT = U.objectFieldOffset
(k.getDeclaredField("baseCount"));
CELLSBUSY = U.objectFieldOffset
(k.getDeclaredField("cellsBusy"));
Class<?> ck = CounterCell.class;
CELLVALUE = U.objectFieldOffset
(ck.getDeclaredField("value"));
Class<?> ak = Node[].class;
ABASE = U.arrayBaseOffset(ak);
int scale = U.arrayIndexScale(ak);
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
} catch (Exception e) {
throw new Error(e);
}
}
在代码中可以看到这些是调用unsafe类需要,在静态代码块中对这些字段(偏移量)调用native方法获取。
而其中getObjectVolatile
有个Volatile字段,读者知道Volatile字段修饰的变量是线程可见的,所以可以大胆猜测获取的这个node节点在native方法中也是volatile的,这样就确保了读的安全。
put方法
和hasmap一样,put方法中也是调用putVal方法
/** Implementation for put and putIfAbsent */
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) {
// cas操作put,成功就终止循环
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;
// synchronize代码块上锁,有hash冲突
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;
}
}
}
// put 一个元素后检查size。判断是否要进行扩容
addCount(1L, binCount);
return null;
}
与hashmap的put方法理念一直,多了关于并发安全的操作
- 自旋,直到put成功
- 判断table有没有初始化,没有即初始化
- 有没有hash冲突,没有说明这个索引下没有节点,直接cas插入
- 否则先检查是否再扩容,是的话帮助扩容
- 也不是扩容的情况下,hash冲突下,上锁
- 判断是链表还是树,两种情况下判断是插入还是覆盖value
- 插入成功后判断是否需要转换成树
- put成功后检查size是否需要扩容
接下来,分别解析一下put方法中调用的方法
initTable
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
// 说明有线程正在进行初始化
if ((sc = sizeCtl) < 0)
// 将线程挂起
Thread.yield(); // lost initialization race; just spin
// 那就说明值为0默认值,就cas操作成-1,-值代表初始化
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
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 {
// 初始化成功后,将size赋值给sizeCtl
sizeCtl = sc;
}
break;
}
}
return tab;
}
这段代码不难理解,估计就是对这sizeCtl感到疑惑,sizeCtl这是一个标志符。
/**
* Table initialization and resizing control. When negative, the
* table is being initialized or resized: -1 for initialization,
* else -(1 + the number of active resizing threads). Otherwise,
* when table is null, holds the initial table size to use upon
* creation, or 0 for default. After initialization, holds the
* next element count value upon which to resize the table.
*/
private transient volatile int sizeCtl;
从注释可了解,sizeCtl值对应的几种状况
- 为0 是默值
- 为-1表名map正在初始化
- 为-(1+n)n的值为扩容的线程数,意味正在扩容
- 初始化成功后,值为size长度
明白了sizeCtl字段含义的时候,再回看代码就很明了。
helpTransfer
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
// f是扩容节点
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
// 根据length计算一个标识符
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;
// 不满足上述情况,即cas加一赋值,意味着扩容线程+1
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
// 扩容
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}
hashmap中节点只会为Node,普通节点或者TreeNode树节点,concurrentHashMap中添加了一个ForwardingNode节点,表示此时正处在扩容中。
接下来看下while循环条件while (nextTab == nextTable && table == tab &&(sc = sizeCtl) < 0)
。
nextTab == nextTable
说明其他线程还未修改nextTable即扩容后新的table,同理table == tab
其他线程并没有修改tab,至于sizeCtl)< 0
上文中提到了关于sizeCtl的值,小于0 说明正在扩或者初始化中。
看下if中的条件判断
(sc >>> RESIZE_STAMP_SHIFT) != rs
sc即sizeCtl的值无符号右移16位和之前计算的标志符进行比较,不相等说明标志符rs被改变了。sizeCtl高16位存储的是通过length计算的标志符,低16位存储的是并发扩容线程数。
sc == rs + 1
意味着扩容结束了,不再有线程参与扩容。之所以判断sc= rs+1的原因是默认第一个线程设置 sc == rs 左移 16 位 + 2,当第一个线程结束扩容了,就会将 sc 减一。这个时候,sc 就等于 rs + 1。在后续的addCount方法中详细解释
如果 sizeCtl == 标识符 + 1 ,说明库容结束了,没有必要再扩容了。
sc == rs + MAX_RESIZERS
判断扩容线程是否达到最大值。
transferIndex <= 0
即扩容结束,是否在进行调整。
总结一下:
- 判断tab以及nexttab不为null,且当前节点是扩容节点
- 根据tab的长度计算标志符
- 判断是否存在其他线程修改tab和nexttale以及sc的值还是小于0
- 判断是否修改了标志符,是否还处在扩容,扩容线程是否达到最大值,是否已经扩容结束在进行下标调整
- 都不满足,扩容线程+1,cas赋值给sc,调用扩容方法进行扩容。
addCount
private final void addCount(long x, int check) {
// 修改baseCount
CounterCell[] as; long b, s;
// counterCells为null或者basecount cas 修改失败后
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
// 借助CounterCell,相当于计数器数组
// 判断counteCells不为null
if (as == null || (m = as.length - 1) < 0 ||
// ThreadLocalRandom.getProbe()用来取随机数,如果没取到,说明没有CountCell可用
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
// 有coutCell,cas 递增value失败了
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
// 如果也失败了调用fullAddCount直到成功
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
// 求和
s = sumCount();
}
// 判断是否要进行扩容
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
// 判断table及sizeCtl不为null以及table长度小于最大值
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);
}
//如果不在扩容,将 sc 更新:标识符左移 16 位 然后 + 2. 也就是变成一个负数。
// 高 16 位是标识符,低 16 位初始是 2.
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
这个方法分两部分,第一个if是用来更新basecount,第二个是用来处理扩容的。
首先来看第一部分
先了解一下baseCount和CounterCell.CounterCell 是concurrentHashMap的内部类
@sun.misc.Contended static final class CounterCell {
volatile long value;
CounterCell(long x) { value = x; }
}
内部维护着一个volatile 修饰的value,用来辅助计算baseCount。
baseCount存储是的非竞争情况下也就非并发下的hasemap键值对的数量。看下concurrentHashMap的size方法
public int size() {
long n = sumCount();
return ((n < 0L) ? 0 :
(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
(int)n);
}
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;
}
可以看到调用sumCount方法,含义是循环遍历CounterCell数组,取出里面的值加上baseCount。
明白了这两属性的含义,第一部分就好理解了。
- basecount直接cas更新,更新失败那就说明是并发的情况下
- 走进if里,借助CountCell进行辅助,counterCells是多个用数组容纳的计数器,counterCells数组中有可用计数器时,去尝试给计数器递增x
- 如果失败或者没有计数器可用,执行fullAddCount
fullAddCount的方法源码中注释解释了思想和LongAdder一致,读者有兴趣可自行了解,简单看下fullAddCount。
// x: 递增数量
// wasUncontended: 是否未竞争CAS递增过CounterCell
private final void fullAddCount(long x, boolean wasUncontended) {
int h;
// 取随机值等于0 的话
if ((h = ThreadLocalRandom.getProbe()) == 0) {
ThreadLocalRandom.localInit(); // force initialization
h = ThreadLocalRandom.getProbe();
wasUncontended = true;
}
boolean collide = false; // True if last slot nonempty
for (;;) {
CounterCell[] as; CounterCell a; int n; long v;
if ((as = counterCells) != null && (n = as.length) > 0) {
// counterCell为null
if ((a = as[(n - 1) & h]) == null) {
// 为0,新建
if (cellsBusy == 0) { // Try to attach new Cell
CounterCell r = new CounterCell(x); // Optimistic create
// 尝试更新cellsBusy值为1
if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean created = false;
// 二次检查
try { // Recheck under lock
CounterCell[] rs; int m, j;
if ((rs = counterCells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
// 不管修改cellsBusy值为1是否成功,最后都改为0
cellsBusy = 0;
}
// 新建成功就跳出,否则继续
if (created)
break;
// 说明这个下标已有其他线程创建好了CountCell
continue; // Slot is now non-empty
}
}
collide = false;
}
// 在上文中提到的if循环内,已经调用过countCell竞争过一次,失败了所以调用fullAddCount方法。
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
// 尝试一下赋值
else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
break;
// 判断是否有线程修改了as
else if (counterCells != as || n >= NCPU)
collide = false; // At max size or stale
else if (!collide)
collide = true;
// 继续修改cellsBusy值为I
else if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
try {
if (counterCells == as) {// Expand table unless stale
CounterCell[] rs = new CounterCell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
counterCells = rs;
}
} finally {
cellsBusy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h = ThreadLocalRandom.advanceProbe(h);
}
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
if (init)
break;
}
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break; // Fall back on using base
}
}
可以看到多次对cellsBusy值进行CAS修改,并发状况下多个线程只有一个可以修改成功,将0改成一,在方法最后会改回0.
接下来看第二部分扩容的判断和处理
putval调用方法传值的check=0,所以是符合条件的,其他逻辑和上文提到的一样,就不赘述。
总结
本文介绍了concurrentHashMap与hashmap的不同,在put以及get方法进行对比,也对concurrentHashMap中put方法的差异点进行了研读。