JUC高并发编程-共享模型之无锁

共享模型之无锁

问题提出

有如下需求,保证 account.withdraw 取款方法的线程安全,先看一个线程不安全的情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class TestCAS {
public static void main(String[] args) {
Account.demo(new AccountUnsafe(10000));
}
}

interface Account{
//获取余额
Integer getBalance();
//取款
void withdraw(Integer amount);

/**
* 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
* 如果初始余额为 10000 那么正确的结果应当是 0
*/
static void demo(Account account) {
List<Thread> ts = new ArrayList<>();
long start = System.nanoTime();
for (int i = 0; i < 1000; i++) {
ts.add(new Thread(()->{
account.withdraw(10);
}));
}
ts.forEach(Thread::start);
ts.forEach(t->{
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end = System.nanoTime();
System.out.println(account.getBalance()
+ " cost: " + (end-start)/1000_000 + " ms");

}
}

class AccountUnsafe implements Account {
private Integer balance;

public AccountUnsafe(Integer balance) {
this.balance = balance;
}

@Override
public Integer getBalance() {
return balance;
}

@Override
public void withdraw(Integer amount) {
balance -= amount;
}
}
为什么不安全

执行withdraw 方法对应的字节码:

1
2
3
4
5
6
7
8
9
ALOAD 0 													// <- this
ALOAD 0
GETFIELD com/heu/AccountUnsafe.balance : Ljava/lang/Integer; // <- this.balance
INVOKEVIRTUAL java/lang/Integer.intValue ()I // 拆箱
ALOAD 1 // <- amount
INVOKEVIRTUAL java/lang/Integer.intValue ()I // 拆箱
ISUB // 减法
INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer; // 结果装箱
PUTFIELD com/heu/AccountUnsafe.balance : Ljava/lang/Integer; // -> this.balance

单核的指令交错

多核的指令交错

解决思路-锁

首先想到的是给 Account 对象加锁:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class AccountUnsafe implements Account {
private Integer balance;

public AccountUnsafe(Integer balance) {
this.balance = balance;
}

@Override
public synchronized Integer getBalance() {
return balance;
}

@Override
public synchronized void withdraw(Integer amount) {
balance -= amount;
}
}

如上代码加锁会造成线程堵塞,堵塞的时间取决于临界区代码执行的时间,这使用加锁的性能不高,因此可以使用无锁来解决此问题。

解决思路-无锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

class AccountUnsafe implements Account {
AtomicInteger atomicInteger;

public AccountUnsafe(Integer balance) {
this.atomicInteger = new AtomicInteger(balance);
}

@Override
public Integer getBalance() {
return atomicInteger.get();
}

@Override
public void withdraw(Integer amount) {
while (true) {
Integer pre = getBalance();
int next = pre - amount;
//如果当前值等于参数给定的期望值,则将值设置为参数中的传递值。该函数返回一个布尔值,该布尔值使我们了解更新是否完成.
//compareAndSet方法实际上是做了两步操作,第一步是比较,第二步是把value的值更新,这两步是原子操作,在没有多线程锁的情况下,借助cpu锁保证数据安全。
if (atomicInteger.compareAndSet(pre, next)) {
break;
}
}
}
}

CAS与volatile

工作方式

前面的AtomicInteger的解决方法,内部并没有用锁来保护共享变量的线程安全。那么它是如何实现的?

1
2
3
4
5
6
7
8
9
public void withdraw(Integer amount){
while(true){
int prev = balance.get();
int next = prev - amount;
if(balance.compareAndSet(prev,next)){
break;
}
}
}

其中的关键是compareAndSet,它的简称就是CAS(也有Compare And Swap的说法),它必须是原子操作。

img92

volatile

获取共享变量时,为了保证该变量的可见性,需要使用volatile修饰。

它可以用来修饰成员变量和静态成员变量,它可以避免线程从自己的工作缓存中查找变量的值,必须到主存中获取它的值,线程操作volatile变量都是直接操作主存,即一个线程对volatile变量的修改,对另一个线程可见。

注意:volatile仅仅保证了共享变量的可见性,让其它线程能够看到最新值,但不能解决指令交错问题(不能保证原子性)。

CAS必须借助volatile才能读取到共享变量的最新值来实现比较并交换的效果。

为什么无锁效率高
  • 无锁情况下,即使重试失败,线程始终在高速运行,没有停歇,而 synchronized 会让线程在没有获得锁的时候,发生上下文切换,进入阻塞。

  • 打个比喻:线程就好像高速跑道上的赛车,高速运行时,速度超快,一旦发生上下文切换,就好比赛车要减速、熄火,等被唤醒又得重新打火、启动、加速… 恢复到高速运行,代价比较大。

  • 但无锁情况下,因为线程要保持运行,需要额外 CPU 的支持,CPU 在这里就好比高速跑道,没有额外的跑道,线程想高速运行也无从谈起,虽然不会进入阻塞,但由于没有分到时间片,仍然会进入可运行状态,还是会导致上下文切换。

CAS的特点

结合 CAS 和 volatile 可以实现无锁并发,适用于线程数少、多核 CPU 的场景下。

  • CAS 是基于乐观锁的思想:最乐观的估计,不怕别的线程来修改共享变量,就算改了也没关系,吃亏点再重试呗。

  • synchronized 是基于悲观锁的思想:最悲观的估计,得防着其它线程来修改共享变量,我上了锁你们都别想改,我改完了解开锁,你们才有机会。

  • CAS 体现的是无锁并发、无阻塞并发,请仔细体会这两句话的意思。

    • 因为没有使用 synchronized,所以线程不会陷入阻塞,这是效率提升的因素之一。
    • 但如果竞争激烈(写操作多),可以想到重试必然频繁发生,反而效率会受影响。

原子整数

java.util.concurrent.atomic 并发包提供了一些并发工具类,这里把它分成五类,分别是:

原子类

  • AtomicInteger:整型原子类
  • AtomicLong:长整型原子类
  • AtomicBoolean:布尔型原子类

原子引用

原子数组

字段更新器

原子累加器

以AtomicInteger为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(0);
// 获取并自增(i = 0, 结果 i = 1, 返回 0),类似于 i++
System.out.println(i.getAndIncrement());
// 自增并获取(i = 1, 结果 i = 2, 返回 2),类似于 ++i
System.out.println(i.incrementAndGet());
// 自减并获取(i = 2, 结果 i = 1, 返回 1),类似于 --i
System.out.println(i.decrementAndGet());
// 获取并自减(i = 1, 结果 i = 0, 返回 1),类似于 i--
System.out.println(i.getAndDecrement());
// 获取并加值(i = 0, 结果 i = 5, 返回 0)
System.out.println(i.getAndAdd(5));
// 加值并获取(i = 5, 结果 i = 0, 返回 0)
System.out.println(i.addAndGet(-5));
// 获取并更新(i = 0, p 为 i 的当前值, 结果 i = -2, 返回 0)
// 函数式编程接口,其中函数中的操作能保证原子,但函数需要无副作用
System.out.println(i.getAndUpdate(p -> p - 2));
// 更新并获取(i = -2, p 为 i 的当前值, 结果 i = 0, 返回 0)
// 函数式编程接口,其中函数中的操作能保证原子,但函数需要无副作用
System.out.println(i.updateAndGet(p -> p + 2));
// 获取并计算(i = 0, p 为 i 的当前值, x 为参数1, 结果 i = 10, 返回 0)
// 函数式编程接口,其中函数中的操作能保证原子,但函数需要无副作用
// getAndUpdate 如果在 lambda 中引用了外部的局部变量,要保证该局部变量是 final 的
// getAndAccumulate 可以通过 参数1 来引用外部的局部变量,但因为其不在 lambda 中因此不必是 final
System.out.println(i.getAndAccumulate(10, (p, x) -> p + x));
// 计算并获取(i = 10, p 为 i 的当前值, x 为参数1值, 结果 i = 0, 返回 0)
// 函数式编程接口,其中函数中的操作能保证原子,但函数需要无副作用
System.out.println(i.accumulateAndGet(-10, (p, x) -> p + x));
}

原子引用

为什么需要原子引用类型

保证引用类型的共享变量是线程安全的(确保这个原子引用没有引用过别人)。基本类型原子类只能更新一个变量,如果需要原子更新多个变量,需要使用引用类型原子类。

  • AtomicReference
  • AtomicMarkableReference
  • AtomicStampedReference

如下方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class DecimalAccountUnsafe implements DecimalAccount {
BigDecimal balance;
public DecimalAccountUnsafe(BigDecimal balance) {
this.balance = balance;
}
@Override
public BigDecimal getBalance() {
return balance;
}
// 取款任务
@Override
public void withdraw(BigDecimal amount) {
BigDecimal balance = this.getBalance();
this.balance = balance.subtract(amount);
}
}

当执行 withdraw 方法时,可能会有线程安全问题,我们可以加锁解决或者是使用无锁的方式 CAS 来解决,这里的解决方式是用AtomicReference 原子引用解决。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class DecimalAccountCas implements DecimalAccount {

private AtomicReference<BigDecimal> balance;

public DecimalAccountCas(BigDecimal balance) {
this.balance = new AtomicReference<>(balance);
}

@Override
public BigDecimal getBalance() {
return balance.get();
}

@Override
public void withdraw(BigDecimal amount) {
while (true) {
BigDecimal preVal = balance.get();
BigDecimal nextVal = preVal.subtract(amount);
if(balance.compareAndSet(preVal, nextVal)) {
break;
}
}
}
}

ABA问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static AtomicReference<String> ref = new AtomicReference<>("A");

public static void main(String[] args) throws InterruptedException {
log.debug("main start...");
String preVal = ref.get();
other();
TimeUnit.SECONDS.sleep(1);
log.debug("change A->C {}", ref.compareAndSet(preVal, "C"));
}

private static void other() throws InterruptedException {
new Thread(() -> {
log.debug("change A->B {}", ref.compareAndSet(ref.get(), "B"));
}, "t1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
log.debug("change B->A {}", ref.compareAndSet(ref.get(), "A"));
}, "t2").start();
}

主线程仅能判断出共享变量的值与最初值 A 是否相同,不能感知到这种从 A 改为 B 又改回 A 的情况,如果主线程希望只要有其它线程【动过了】共享变量,那么自己的 cas 就算失败的话,这时,仅比较值是不够的,需要再加一个版本号。使用AtomicStampedReference来解决。

AtomicStampedReference

使用 AtomicStampedReference 加 stamp (版本号或者时间戳)的方式解决 ABA 问题。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class TestAtomicStampedReference {
public static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
public static void main(String[] args) throws InterruptedException {
log.debug("main start...");
String preVal = ref.getReference();
int stamp = ref.getStamp();
log.info("main 拿到的版本号 {}",stamp);
other();
TimeUnit.SECONDS.sleep(1);
log.info("修改后的版本号 {}",ref.getStamp());
log.info("change A->C:{}", ref.compareAndSet(preVal, "C", stamp, stamp + 1));
}

private static void other() throws InterruptedException {
new Thread(() -> {
int stamp = ref.getStamp();
log.info("{}",stamp);
log.info("change A->B:{}", ref.compareAndSet(ref.getReference(), "B", stamp, stamp + 1));
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
int stamp = ref.getStamp();
log.info("{}",stamp);
log.debug("change B->A:{}", ref.compareAndSet(ref.getReference(), "A",stamp,stamp + 1));
}).start();
}
}

输出:

1
2
3
4
5
6
7
16:48:22.772 [main] DEBUG com.heu.test.TestAtomicStampedReference - main start...
16:48:22.782 [main] INFO com.heu.test.TestAtomicStampedReference - main 拿到的版本号 0
16:48:22.788 [Thread-0] INFO com.heu.test.TestAtomicStampedReference - 0
16:48:22.788 [Thread-0] INFO com.heu.test.TestAtomicStampedReference - change A->B:true
16:48:23.792 [Thread-1] INFO com.heu.test.TestAtomicStampedReference - 1
16:48:23.792 [Thread-1] DEBUG com.heu.test.TestAtomicStampedReference - change B->A:true
16:48:24.793 [main] INFO com.heu.test.TestAtomicStampedReference - 修改后的版本号 2

AtomicMarkableReference

AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,如:A -> B -> A ->C,通过AtomicStampedReference可以知道,引用变量中途被更改了几次。但是有时候,并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了AtomicMarkableReference 。

原子数组

使用原子的方式更新数组里的某个元素:

  • AtomicIntegerArray:整形数组原子类
  • AtomicLongArray:长整形数组原子类
  • AtomicReferenceArray :引用类型数组原子类

使用原子数组可以保证元素的线程安全。

上面三个类提供的方法几乎相同,所以这里以 AtomicIntegerArray 为例子来介绍,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class TestAtomicIntegerArray {
public static void main(String[] args) {

//不安全的数组
demo(
()->new int[10],
(array)->array.length,
(array, index) -> array[index]++,
array-> System.out.println(Arrays.toString(array))
);

//安全的数组
demo(
()->new AtomicIntegerArray(10),
(array) -> array.length(),
(array, index) -> array.getAndIncrement(index),
(array) -> System.out.println(array)
);
}
private static <T> void demo(
Supplier<T> arraySupplier,
Function<T,Integer> lengthFun,
BiConsumer<T,Integer> putConsumer,
Consumer<T> printConsumer) {
ArrayList<Thread> ts = new ArrayList<>();
T array = arraySupplier.get();
int length = lengthFun.apply(array);
for (int i = 0; i < length; i++) {
ts.add(new Thread(()->{
for (int j = 0; j < 10000; j++) {
putConsumer.accept(array,j%length);
}
}));
}
ts.forEach(t->t.start());
ts.forEach(t->{
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
printConsumer.accept(array);
}

}

输出:

1
2
3
4
5
6
7

1
2
3
[9470, 9579, 9616, 9594, 9566, 9633, 9605, 9611, 9892, 9879]

[10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]

字段更新器

  • AtomicReferenceFieldUpdater // 域 字段
  • AtomicIntegerFieldUpdater
  • AtomicLongFieldUpdater

利用字段更新器,可以针对对象的某个域(Field)进行原子操作,只能配合 volatile 修饰的字段使用,否则会出现异常。

1
Exception in thread "main" java.lang.IllegalArgumentException: Must be volatile type。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class TestFieldUpdater {
private volatile int field;

public static void main(String[] args) {
AtomicIntegerFieldUpdater<TestFieldUpdater> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(TestFieldUpdater.class, "field");
TestFieldUpdater updater = new TestFieldUpdater();
fieldUpdater.compareAndSet(updater, 0, 10);
// 修改成功 field = 10
System.out.println(updater.field);
// 修改成功 field = 20
fieldUpdater.compareAndSet(updater, 10, 20);
System.out.println(updater.field);
// 修改失败 field = 20
fieldUpdater.compareAndSet(updater, 10, 30);
System.out.println(updater.field);
}

输出:

1
2
3
10 
20
20

原子累加器

AtomicLong Vs LongAdder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class TestLongAdder {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
demo(()->new AtomicLong(0),(ref)->ref.getAndIncrement());
}

for (int i = 0; i < 5; i++) {
demo(()->new LongAdder(),(ref)->ref.increment());
}
}
private static <T> void demo(Supplier<T> supplier, Consumer<T> consumer) {
ArrayList<Thread> list = new ArrayList<>();

T adder = supplier.get();
// 4 个线程,每人累加 50 万
for (int i = 0; i < 4; i++) {
list.add(new Thread(() -> {
for (int j = 0; j < 500000; j++) {
consumer.accept(adder);
}
}));
}
long start = System.nanoTime();
list.forEach(t -> t.start());
list.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end = System.nanoTime();
System.out.println(adder + " cost:" + (end - start)/1000_000);
}
}

输出:

1
2
3
4
5
6
7
8
9
10
2000000 cost:80
2000000 cost:76
2000000 cost:60
2000000 cost:56
2000000 cost:52
2000000 cost:32
2000000 cost:5
2000000 cost:8
2000000 cost:8
2000000 cost:20

结论:

执行代码后,发现使用 LongAdder 比 AtomicLong 快2,3倍,使用 LongAdder 性能提升的原因很简单,就是在有竞争时,设置多个累加单元(但不会超过cpu的核心数),Therad-0 累加 Cell[0],而 Thread-1 累加Cell[1]… 最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性能。

CAS锁

使用 cas 实现一个自旋锁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class TestLockCas {

public AtomicInteger state = new AtomicInteger(0); // 如果 state 值为 0 表示没上锁, 1 表示上锁

public void lock() {
while (true) {
if(state.compareAndSet(0, 1)) {
break;
}
}
}

public void unlock() {
log.debug("unlock...");
state.set(0);
}

public static void main(String[] args) {
Code_13_LockCas lock = new Code_13_LockCas();
new Thread(() -> {
log.info("begin...");
lock.lock();
try {
log.info("上锁成功");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}, "t1").start();
new Thread(() -> {
log.info("begin...");
lock.lock();
try {
log.info("上锁成功");
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}, "t2").start();
}
}

LongAdder原理

LongAdder 类有几个关键域,在public class LongAdder extends Striped64 implements Serializable {},下面的变量属于 Striped64 被 LongAdder 继承:

1
2
3
4
5
6
// 累加单元数组, 懒惰初始化
transient volatile Cell[] cells;
// 基础值, 如果没有竞争, 则用 cas 累加这个域
transient volatile long base;
// 在 cells 创建或扩容时, 置为 1, 表示加锁
transient volatile int cellsBusy;
原理之伪共享

其中 Cell 即为累加单元。

1
2
3
4
5
6
7
8
9
10
11
// 防止缓存行伪共享
@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);
}
// 省略不重要代码
}

要想讨论 @sun.misc.Contended 注解的重要意义得从缓存说起,缓存与内存的速度比较

因为 CPU 与 内存的速度差异很大,需要靠预读数据至缓存来提升效率。缓存离 cpu 越近速度越快。 而缓存以缓存行为单位,每个缓存行对应着一块内存,一般是 64 byte(8 个 long),缓存的加入会造成数据副本的产生,即同一份数据会缓存在不同核心的缓存行中,CPU 要保证数据的一致性,如果某个 CPU 核心更改了数据,其它 CPU 核心对应的整个缓存行必须失效。

因为 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 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效。

add 方法分析

LongAdder 进行累加操作是调用 increment 方法,它又调用 add 方法。

1
2
3
public void increment() {
add(1L);
}

第一步:add 方法分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
// 3. 如果 as 没有创建, 然后 cas 累加成功就返回,累加到 base 中 不存在线程竞争的时候用到。
if ((as = cells) != null || !casBase(b = base, b + x)) {
// uncontended 表示 cell 是否有竞争,这里赋值为 true 表示有竞争
boolean uncontended = true;
if (
// as 还没有创建
as == null || (m = as.length - 1) < 0 ||
// 当前线程对应的 cell 还没有被创建,a为当线程的cell
(a = as[getProbe() & m]) == null ||
// 给当前线程的 cell 累加失败 uncontended=false ( a 为当前线程的 cell )
!(uncontended = a.cas(v = a.value, v + x))
) {
// 当 cells 为空时,累加操作失败会调用方法,
// 当 cells 不为空,当前线程的 cell 创建了但是累加失败了会调用方法,
// 当 cells 不为空,当前线程 cell 没创建会调用这个方法
// 进入 cell 数组创建、cell 创建的流程
longAccumulate(x, null, uncontended);
}
}
}

第二步:longAccumulate 方法分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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 循环
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
}
}
// 有竞争, 改变线程对应的 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, cells==as是指没有其它线程修改cells,as和cells引用相同的对象,使用casCellsBusy()尝试给 cellsBusy 加锁
else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
// 加锁成功, 初始化 cells, 最开始长度为 2, 并填充一个 cell
// 成功则 break;
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;
}
// 上两种情况失败, 尝试给 base 使用casBase累加
else if (casBase(v = base, ((fn == null) ? v + x : fn.applyAsLong(v, x))))
break;
}
}
sum 方法分析

获取最终结果通过 sum 方法,将各个累加单元的值加起来就得到了总的结果:

1
2
3
4
5
6
7
8
9
10
11
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;
}

Unsafe方法

Unsafe 对象的获取

Unsafe 对象提供了非常底层的操作内存、线程的方法,Unsafe 对象不能直接调用,只能通过反射获得。LockSupport 的 park 方法,CAS 相关的方法底层都是通过Unsafe类来实现的。

1
2
3
4
5
6
7
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
// Unsafe 使用了单例模式,unsafe 对象是类中的一个私有的变量
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe)theUnsafe.get(null);

}
Unsafe 模拟实现 cas 操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class UnsafeTest {

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

// 创建 unsafe 对象
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe)theUnsafe.get(null);

// 拿到偏移量
long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));

// 进行 cas 操作
Teacher teacher = new Teacher();
unsafe.compareAndSwapLong(teacher, idOffset, 0, 100);
unsafe.compareAndSwapObject(teacher, nameOffset, null, "lisi");

System.out.println(teacher);
}

}

@Data
class Teacher {

private volatile int id;
private volatile String name;

}
Unsafe 模拟实现原子整数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class UnsafeAccessor {

public static void main(String[] args) {
Account.demo(new MyAtomicInteger(10000));
}
}

class MyAtomicInteger implements Account {

private volatile Integer value;
private static final Unsafe UNSAFE = Unsafe.getUnsafe();
private static final long valueOffset;

static {
try {
valueOffset = UNSAFE.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}

public MyAtomicInteger(Integer value) {
this.value = value;
}

public Integer get() {
return value;
}

public void decrement(Integer amount) {
while (true) {
Integer preVal = this.value;
Integer nextVal = preVal - amount;
if(UNSAFE.compareAndSwapObject(this, valueOffset, preVal, nextVal)) {
break;
}
}
}

@Override
public Integer getBalance() {
return get();
}

@Override
public void withdraw(Integer amount) {
decrement(amount);
}
}
-------------本文结束感谢您的阅读-------------