当前位置:网站首页>JUC 原子累加器 源码之 LongAdder
JUC 原子累加器 源码之 LongAdder
2022-06-13 09:00:00 【Q z1997】
LongAdder 是并发大师 @author Doug Lea (大哥李)的作品,设计的非常精巧
LongAdder 类有几个关键域
// 累加单元数组, 懒惰初始化
transient volatile Cell[] cells;
// 基础值, 如果没有竞争, 则用 cas 累加这个域
transient volatile long base;
// 在 cells 创建或扩容时, 置为 1, 表示加锁
transient volatile int cellsBusy;
cas 锁
// 不要用于实践!!!
public class LockCas {
private AtomicInteger state = new AtomicInteger(0);
public void lock() {
while (true) {
if (state.compareAndSet(0, 1)) {
break;
}
}
}
public void unlock() {
log.debug("unlock...");
state.set(0);
}
}
其中 Cell 即为累加单元
// 防止缓存行伪共享
@sun.misc.Contended
static final class Cell {
volatile long value;
Cell(long x) {
value = x; }
// 最重要的方法, 用来 cas 方式进行累加, prev 表示旧值, next 表示新值
final boolean cas(long prev, long next) {
return UNSAFE.compareAndSwapLong(this, valueOffset, prev, next);
}
// 省略不重要代码
}
得从缓存说起
缓存与内存的速度比较
因为 Cell 是数组形式,在内存中是连续存储的,一个 Cell 为 24 字节(16 字节的对象头和 8 字节的 value),因此缓存行可以存下 2 个的 Cell 对象。这样问题来了:
- Core-0 要修改 Cell[0]
- Core-1 要修改 Cell[1]
无论谁修改成功,都会导致对方 Core 的缓存行失效,比如 Core-0 中 Cell[0]=6000, Cell[1]=8000 要累加Cell[0]=6001, Cell[1]=8000 ,这时会让 Core-1 的缓存行失效
@sun.misc.Contended 用来解决这个问题,它的原理是在使用此注解的对象或字段的前后各增加 128 字节大小的
padding,从而让 CPU 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效
累加主要调用下面的方法
public void add(long x) {
// as 为累加单元数组
// b 为基础值
// x 为累加值
Cell[] as; long b, v; int m; Cell a;
// 进入 if 的两个条件
// 1. as 有值, 表示已经发生过竞争, 进入 if
// 2. cas 给 base 累加时失败了, 表示 base 发生了竞争, 进入 if
if ((as = cells) != null || !casBase(b = base, b + x)) {
// uncontended 表示 cell 没有竞争
boolean uncontended = true;
if (
// as 还没有创建
as == null || (m = as.length - 1) < 0 ||
// 当前线程对应的 cell 还没有
(a = as[getProbe() & m]) == null ||
// cas 给当前线程的 cell 累加失败 uncontended=false ( a 为当前线程的 cell )
!(uncontended = a.cas(v = a.value, v + x))
) {
// 进入 cell 数组创建、cell 创建的流程
longAccumulate(x, null, uncontended);
}
}
}
final void longAccumulate(long x, LongBinaryOperator fn,
boolean wasUncontended) {
int h;
// 当前线程还没有对应的 cell, 需要随机生成一个 h 值用来将当前线程绑定到 cell
if ((h = getProbe()) == 0) {
// 初始化 probe
ThreadLocalRandom.current();
// h 对应新的 probe 值, 用来对应 cell
h = getProbe();
wasUncontended = true;
}
// collide 为 true 表示需要扩容
boolean collide = false;
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) {
// 为 cellsBusy 加锁, 创建 cell, cell 的初始累加值为 x
// 成功则 break, 否则继续 continue 循环
}
// 有竞争, 改变线程对应的 cell 来重试 cas
else if (!wasUncontended)
wasUncontended = true;
// cas 尝试累加, fn 配合 LongAccumulator 不为 null, 配合 LongAdder 为 null
else if (a.cas(v = a.value, ((fn == null) ? v + x : fn.applyAsLong(v, x))))
break;
// 如果 cells 长度已经超过了最大长度, 或者已经扩容, 改变线程对应的 cell 来重试 cas
else if (n >= NCPU || cells != as)
collide = false;
// 确保 collide 为 false 进入此分支, 就不会进入下面的 else if 进行扩容了
else if (!collide)
collide = true;
// 加锁
else if (cellsBusy == 0 && casCellsBusy()) {
// 加锁成功, 扩容
continue;
}
// 改变线程对应的 cell
h = advanceProbe(h);
}
// 还没有 cells, 尝试给 cellsBusy 加锁
else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
// 加锁成功, 初始化 cells, 最开始长度为 2, 并填充一个 cell
// 成功则 break;
}
// 上两种情况失败, 尝试给 base 累加
else if (casBase(v = base, ((fn == null) ? v + x : fn.applyAsLong(v, x))))
break;
}
}
获取最终结果通过 sum 方法
public long sum() {
Cell[] as = cells; Cell a;
long sum = base;
if (as != null) {
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum; }
边栏推荐
- System analysis - detailed description
- MySQL startup error: innodb: operating system error number 13 in a file operation
- Object array de encapsulation
- 教程篇(5.0) 03. 安全策略 * FortiEDR * Fortinet 网络安全专家 NSE 5
- ""? "& in URL Role of "" sign
- An error CV2 is reported when the picture is converted to grayscale cvtColor(img, cv2.COLOR_BGR2GRAY)
- Vscode plug in
- 20211104 为什么相似矩阵的迹相同
- ERP outlet
- Opencv gaussianblur() explanation (Sigma value)
猜你喜欢
Some websites of QT (software download, help documents, etc.)
What exactly is Huawei cloud desktop saying when it says "smooth"?
CentOS installing MySQL and setting up remote access
關於RSA加密解密原理
教程篇(5.0) 02. 管理 * FortiEDR * Fortinet 网络安全专家 NSE 5
VI editor
类的加载概述
Screenshot of cesium implementation scenario
[security] how to counter attack from 0 to 1 to become a security engineer with zero Foundation
System analysis - detailed description
随机推荐
Map 23 summary
Uni app essay
20211104 为什么相似矩阵的迹相同
JS obtain geographic location information according to longitude and latitude and mark it on the map
Module build failed: TypeError: this. getOptions is not a function at Object. stylusLoader
Vscode plug in
教程篇(5.0) 01. 产品简介及安装 * FortiEDR * Fortinet 网络安全专家 NSE 5
15. copy constructor
""? "& in URL Role of "" sign
Simulink的Variant Model和Variant Subsystem用法
Sonar scan ignores the specified file
Neo4j - CQL使用
pytorch相同结构不同参数名模型加载权重
20211108 det(AB)=det(A)det(B)
Mapbox usage, including drawing, loading, modifying, deleting points and faces, displaying pop ups, etc
[QNX hypervisor 2.2 user manual] 4.5.1 build QNX guest
20211108 A转置乘A是正定矩阵吗?A转置乘A是正定矩阵的充分必要条件是什么?
20211108 能观能控,可稳可测
output. Interpretation of topk() function
Qvector shallow copy performance test