LongAdder
public void add(long x) {
/*
as:表示cells引用
b:当前base值
v:表示期望值
m:cells数组长度
a:表示当前线程命中的cell单元格
*/
Cell[] as; long b, v; int m; Cell a;
/*
1:(as = cells) != null为false时,表示cells未初始化,所有线程写入base中.
2:!casBase(b = base, b + x)为false,表示CAS成功。
为true表示发生竞争,可能需要循环重试或者扩容
*/
if ((as = cells) != null || !casBase(b = base, b + x)) {
boolean uncontended = true;//用来判断是否发生竞争
/*
1:||运算符
2:as == null|| (m = as.length - 1) < 0 :表示未初始化,说明多线程写发生竞争了.
3:a = as[getProbe() & m]) == null:获取当前线程的Hash值,true时表示当前线程对于下标的cell为空,需要创建longAccumulate
false:表示cell不为空,已创建longAccumulate,只需将x值到cell中.
4:!(uncontended = a.cas(v = a.value, v + x)):
true:表示CAS失败,意味线程对于的cell有竞争.
false:CAS成功.
*/
if (as == null || (m = as.length - 1) < 0 ||
(a = as[getProbe() & m]) == null ||
!(uncontended = a.cas(v = a.value, v + x)))
/*
调用longAccumulate情况:
1:CAS失败,有竞争.
2:cells未初始化
3:cell为空,需创建longAccumulate.
*/
longAccumulate(x, null, uncontended);
}
}
Add流程图
字段
/** Number of CPUS, to place bound on table size */
/*计算机CPU数量,控制确定cells数组扩容*/
static final int NCPU = Runtime.getRuntime().availableProcessors();
/**
* Table of cells. When non-null, size is a power of 2.
* 扩容数组
*/
transient volatile Cell[] cells;
/**
* Base value, used mainly when there is no contention, but also as
* a fallback during table initialization races. Updated via CAS.
* 1.没有发生竞争会累加到base
* 2.当cells扩容时,需将写入base
*/
transient volatile long base;
/**
* Spinlock (locked via CAS) used when resizing and/or creating Cells.
* 多线程下的并发
* 需要获得锁才能进行扩容和cells初始化操作
* 1:获得锁 0:未获得锁
*/
transient volatile int cellsBusy;
longAccumulate
/*
当多个线程竞争时,必然有一个(多个)线程对base的cas累加操作失败。则调用longAccumulate
*/
final void longAccumulate(long x, LongBinaryOperator fn,
boolean wasUncontended) {
/*线程Hash值*/
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;
/*A:
表示cells已经初始化了,当前线程应该将数据写入到对应的cell中
CAS失败,当前线程对应的cell (竞争|重试|扩容)
*/
if ((as = cells) != null && (n = as.length) > 0) {
/*case1.1:当前线程对应下标位置cell为null,需要new cell*/
if ((a = as[(n - 1) & h]) == null) {
//锁未被占用
if (cellsBusy == 0) { // Try to attach new Cell
Cell r = new Cell(x); // Optimistically create
//锁未被占用,尝试获取锁casCellsBusy【cellsBusy == 0改为1】
if (cellsBusy == 0 && casCellsBusy()) {
boolean created = false;
try { // Recheck under lock
/*rs :cells引用
m:cells长度
j:命中下标
*/
Cell[] rs; int m, j;
//rs[j = (m - 1) & h] == null防止线程并发问题{覆盖数据}
if ((rs = cells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r;
created = true;
}
} finally {
//该位置已占,释放锁
cellsBusy = 0;
}
//位置已占,created = true;break退出
if (created)
break;
continue; // Slot is now non-empty
}
}
//扩容意向false
collide = false;
}
/*case1.2: wasUncontended:false[cells 初始化后并且当前竞争失败] */
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
/*case1.3:
advanceProbe(h)重置Hash值后,且cell不为空
CAS成功则break;
CAS失败说明有竞争
*/
else if (a.cas(v = a.value, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break;
/*collide = false; 意向不扩容*/
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
/*collide = true; 意向扩容*/
else if (!collide)
collide = true;
/*case1.6:扩容逻辑
cellsBusy == 0:无锁
casCellsBusy:竞争这把锁,CAS将cellsBusy == 0改为cellsBusy == 1
*/
else if (cellsBusy == 0 && casCellsBusy()) {
try {
//if (cells == as)并发问题,防止重复扩容
if (cells == as) { // Expand table unless stale
//<< 左移 2^n
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
}
//重置当前线程Hash值
h = advanceProbe(h);
}
/*B:A条件未满足(cells未初始化)
线程未加锁且获得锁成功(cellsBusy == 0)
cells == as 避免并发问题,类似双重锁机制
casCellsBusy():利用CAS将cellsBusy == 0改为cellsBusy == 1
*/
else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
boolean init = false;
try { // Initialize table
//为啥要if (cells == as)判断?防止多线程并发问题将原有的Cell覆盖掉(重复new),造成数据丢失.
if (cells == as) {
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
//执行完后将cellsBusy == 0
cellsBusy = 0;
}
if (init)
break;
}
/*C:
当前cellsBusy==1处于加锁状态表示其它线程正在初始化cells,所以当前线程将值累加到base
2.cells被其它线程初始化后,当前线程需要将数据累加到base*/
else if (casBase(v = base, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break; // Fall back on using base
}
}
总结 1.:LongAdder是一种以空间换时间的解决方案,其在高并发,竞争大的情况下性能更优.
2.sum方法拿到的只是接近值,追求最终一致性。如果业务场景追求高精度,高准确性,用AtomicLong