参考资料:
并发编程.pdf
使用AtomicLong 与 LongAdder效率对比,大概在4倍左右。
1000000 cost:43
1000000 cost:9
1000000 cost:7
1000000 cost:7
1000000 cost:7
1000000 cost:31
1000000 cost:27
1000000 cost:28
1000000 cost:24
1000000 cost:22
- add原理
加的时候首先尝试用CAS对base进行加,如果失败,那么转而对cell进行累加。
对cell进行累加需要查看cell是否存在,存在进行累加,如果不存在或者累加失败,直接调用longAccumulate对cells进行扩容
public void add(long x) {
Cell[] cs; long b, v; int m; Cell c;
// cells已经存在或者CAS失败
if ((cs = cells) != null || !casBase(b = base, b + x)) {
boolean uncontended = true;
// cells不存在或者长度为0
if (cs == null || (m = cs.length - 1) < 0 ||
// 取余看对应的cell是否存在
(c = cs[getProbe() & m]) == null ||
// 设置是否成功
!(uncontended = c.cas(v = c.value, v + x)))
longAccumulate(x, null, uncontended);
}
}
- longAccumulate原理
比较复杂,有空再看看
网友评论