本文源码研究基于jdk1.8
阅读ConcurrentHashMap源码的时候发现了很多CountCell,看不太懂,所以先来研究一下LongAdder。
LongAdder是啥?
LongAdder是用来做线程安全的i++自增操作的,我们知道AtomicLong也可以现实这个功能,那为什么需要LongAdder呢?理由很简单,为了效率。AtomicLong是对整个数进行cas,那么当多个线程并发执行increment操作时,注定只有一个线程成功,其他线程都在失败自旋,很浪费cpu资源,LongAdder你可以把它当成一个cell[cpu个数]数组,由于并行度最多就是cpu个数,那么相当于每个线程只cas操作每一个数组元素,几乎不会失败,最后调用一次sum函数统计数组和即可得到总数。
一句话概括
如果说jdk1.7的ConcurrentHashMap是分段悲观锁的话,那么LongAdder就是分段乐观锁
increment源码
public void increment() {
add(1L);
}
public void add(long x) {
Cell[] as; long b, v; int m; Cell a;
//如果cells数组不为空,那么直接进入if,就不用casBase了
//如果cells数组为空,那么casBase,如果base变量+1成功,add结束
//如果casBase变量失败,进入if
//总结:单线程情况==AtomicLong,只有当多线程竞争的情况下,casBase失败了
//他才会进入if去初始化cells数组,之后就是cas每一个cell
if ((as = cells) != null || !casBase(b = base, b + x)) {
//标志无竞争=true
boolean uncontended = true;
//如果cells数组没有初始化--->longAccumulate,uncontended=true
//如果随机找cells数组的一个cell为空--->longAccumulate,uncontended=true
//如果cas cells数组的某个cell失败了--->longAccumulate
//并且标记uncontended =false,即代表此时有竞争产生
if (as == null || (m = as.length - 1) < 0 ||
(a = as[getProbe() & m]) == null ||
!(uncontended = a.cas(v = a.value, v + x)))
//可以猜到这里要做啥,无非就是初始化数组
//如果定位到数组的某个cell为空的话就new一个Cell塞到数组里
//还有就是如果有竞争的话就给数组扩容
longAccumulate(x, null, uncontended);
}
}
final void longAccumulate(long x, LongBinaryOperator fn,
boolean wasUncontended) {
int h;
if ((h = getProbe()) == 0) {
ThreadLocalRandom.current(); // force initialization
h = getProbe();
wasUncontended = true;
}
boolean collide = false; // True if last slot nonempty
for (;;) {
Cell[] as; Cell a; int n; long v;
//cells数组已经被初始化了
if ((as = cells) != null && (n = as.length) > 0) {
//如果随机的cell为空的话
if ((a = as[(n - 1) & h]) == null) {
if (cellsBusy == 0) { // Try to attach new Cell
//new Cell
Cell r = new Cell(x); // Optimistically create
//塞cell到cells数组需要获取cellsBusy锁
if (cellsBusy == 0 && casCellsBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs; int m, j;
//塞cell到cells数组
if ((rs = cells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
cellsBusy = 0;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
}
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
//对某个cell进行cas
else if (a.cas(v = a.value, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break;
//如果cells数组>=NCPU, 那么一定不会碰撞,无竞争产生
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
else if (!collide)
collide = true;
//如果到这里还没有成功,只能说明有竞争,cells数组还不够大,扩容
else if (cellsBusy == 0 && casCellsBusy()) {
try {
//扩容成两倍
if (cells == as) { // Expand table unless stale
Cell[] rs = new Cell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
cells = rs;
}
} finally {
cellsBusy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h = advanceProbe(h);
}
//cells数组没有被初始化
//如果cas cellsBusy成功的话就去初始化数组
else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
boolean init = false;
try { // Initialize table
if (cells == as) {
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
if (init)
break;
}
//如果到这里说明有多个线程同时来初始化cells数组,但只有一个线程进入上一个else if,
//其他线程只好降级使用base变量执行cas +1操作
else if (casBase(v = base, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break; // Fall back on using base
}
}
需要cellsBusy锁: 初始化cells数组,扩容,塞Cell到cells数组
sum源码
想一个问题:sum函数没有任何加锁操作,为何不会拿到脏数据?
public long sum() {
Cell[] as = cells; Cell a;
long sum = base;
//如果cell数组不空,遍历统计cell的value值
if (as != null) {
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum;
}
上面问题回答:
1: transient volatile long base;
2:@sun.misc.Contended static final class Cell {
volatile long value;
Cell(long x) { value = x; }
}
3: transient volatile Cell[] cells;
注意前面两个volatile变量,正是因为这个关键字,可以保证不拿到脏数据。
volatile反汇编后有一个Lock前缀指令,该指令作用如下:
- 将当前cpu缓存行的数据强制刷新回主内存
- 其他cpu通过总线传播机制嗅探总线上的数据,发现自己的缓存行失效了,强制从主内存读取数据
前两个volatile是为了不读到脏数据,第三个volatile修饰的是一个数组,我猜可能是为了cell数组扩容的时候及时通知其他线程吧