Java并发编程之美——第三章 Java并发包中ThreadLocalRandom类原理剖析
文章目录
JUC包提供了一系列的原子性操作类,这些类都是使用非阻塞算法CAS实现的。
Time 2021-12-29——Hireek
原子变量操作类
JUC并发包中包含有Atomiclnteger、AtomicLong和AtomicBoolean等原子性操作类,它们的原理类似。调用Unsafe类的CAS非阻塞原子操作即可。
缺点
但是在高并发情况下AtomicLong还会存在性能问题。
大量线程会同时去竞争更新同→个原子变量,但是由于同时只有一个线程的CAS操作会成功,这就造成了大量线程竞争失败后,会通过无限循环不断进行自旋尝试CAS的操作,而这会白白浪费CPU资源。
JDK8 新增的原子操作类LongAdder
类图
由此可见,LongAdder继承了Striped64这个类。核心在Striped64,值得一提的是,ConcurrentHashMap的计数也是如此。
分布计数,降低高并发的冲突。吞吐量变高,代价是更高的空间消耗。
Striped64
先来介绍下Striped64这个类的成员变量和Cell内部类,只要了解这四个参数的意义,就能
abstract class Striped64 extends Number {
/**
* Padded variant of AtomicLong supporting only raw accesses plus CAS.
*
* JVM intrinsics note: It would be possible to use a release-only
* form of CAS here, if it were provided.
*/
@sun.misc.Contended static final class Cell { // @Contended to reduce cache contention
volatile long value;
Cell(long x) { value = x; }
final boolean cas(long cmp, long val) {
return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long valueOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> ak = Cell.class;
valueOffset = UNSAFE.objectFieldOffset
(ak.getDeclaredField("value"));
} catch (Exception e) {
throw new Error(e);
}
}
}
/** Number of CPUS, to place bound on table size */
static final int NCPU = Runtime.getRuntime().availableProcessors(); // cpu核心数,限制cells size,性能考虑。再多Cell元素没有冲突了,也是浪费空间。
/**
* 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.
*/
transient volatile long base;
/**
* Spinlock (locked via CAS) used when resizing and/or creating Cells.
*/
transient volatile int cellsBusy;
}
LongAdder add(long x)
/**
* Adds the given value.
*
* @param x the value to add
*/
public void add(long x) {
Cell[] as; long b, v; int m; Cell a;
if ((as = cells) != null || !casBase(b = base, b + x)) { // (1) cells数组不为空或更新base原子操作失败了
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 || // (2)
(a = as[getProbe() & m]) == null || // (3)
!(uncontended = a.cas(v = a.value, v + x))) // (4)
longAccumulate(x, null, uncontended); // (5) 核心。
}
}
Striped64类 中longAccumulate(long x, LongBinaryOperator fn,boolean wasUncontended)方法
该方法看上去比较复杂,只要理解了Striped64的成员变量的意义,自然就会理解。
/**
* Handles cases of updates involving initialization, resizing,
* creating new Cells, and/or contention. See above for
* explanation. This method suffers the usual non-modularity
* problems of optimistic retry code, relying on rechecked sets of
* reads.
*
* @param x the value
* @param fn the update function, or null for add (this convention
* avoids the need for an extra field or function in LongAdder).
* @param wasUncontended false if CAS failed before call
*/
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;
if ((as = cells) != null && (n = as.length) > 0) { // cells是否为空
if ((a = as[(n - 1) & h]) == null) {
if (cellsBusy == 0) { // Try to attach new Cell
Cell r = new Cell(x); // Optimistically create
if (cellsBusy == 0 && casCellsBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs; int m, j;
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
else if (a.cas(v = a.value, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break;
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
else if (!collide)
collide = true;
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);
}
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;
}
else if (casBase(v = base, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break; // Fall back on using base
}
}
LongAccumulator
使用
/**
* LongAccumulator test
*
* @author Hireek
* @date 2021/12/30 14:56
*/
public class LongAccumulatorTest {
public static void main(String[] args) {
LongAdder longAdder = new LongAdder();
longAdder.add(9L);
System.out.println(longAdder.sum());
LongAccumulator longAccumulator = new LongAccumulator((a, b) -> a * b, 9);
longAccumulator.accumulate(9);
long l = longAccumulator.get();
System.out.println(l);
}
}
可以发现LongAccumulator的用法比LongAdder更加灵活强大。
其实底层实现一样,都是基于Striped64去实现的。
LongAccumulator与LongAdder的区别
构造函数参数不一样。
/**
* Creates a new instance using the given accumulator function
* and identity element.
* @param accumulatorFunction a side-effect-free function of two arguments
* @param identity identity (initial value) for the accumulator function
*/
public LongAccumulator(LongBinaryOperator accumulatorFunction,
long identity) {
this.function = accumulatorFunction; // 调用longAccumulate传入
base = this.identity = identity; //base 初始值
}