6.1 问题提出

有如下需求,保证 account.withdraw 取款方法的线程安全

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. interface Account {
  4. // 获取余额
  5. Integer getBalance();
  6. // 取款
  7. void withdraw(Integer amount);
  8. /**
  9. * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
  10. * 如果初始余额为 10000 那么正确的结果应当是 0
  11. */
  12. static void demo(Account account) {
  13. List<Thread> ts = new ArrayList<>();
  14. long start = System.nanoTime();
  15. for (int i = 0; i < 1000; i++) {
  16. ts.add(new Thread(() -> {
  17. account.withdraw(10);
  18. }));
  19. }
  20. ts.forEach(Thread::start);
  21. ts.forEach(t -> {
  22. try {
  23. t.join();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. });
  28. long end = System.nanoTime();
  29. System.out.println(account.getBalance()
  30. + " cost: " + (end-start)/1000_000 + " ms");
  31. }
  32. }

原有实现并不是线程安全的

  1. class AccountUnsafe implements Account {
  2. private Integer balance;
  3. public AccountUnsafe(Integer balance) {
  4. this.balance = balance;
  5. }
  6. @Override
  7. public Integer getBalance() {
  8. return balance;
  9. }
  10. @Override
  11. public void withdraw(Integer amount) {
  12. balance -= amount;
  13. }
  14. }

执行测试代码

  1. public static void main(String[] args) {
  2. Account.demo(new AccountUnsafe(10000));
  3. }

某次的执行结果

  1. 390 cost: 344 ms

withdraw 方法为什么不安全

  1. public void withdraw(Integer amount) {
  2. balance -= amount;
  3. }

对应的字节码

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

多线程执行流程

  1. ALOAD 0 // thread-0 <- this
  2. ALOAD 0
  3. GETFIELD cn/itcast/AccountUnsafe.balance // thread-0 <- this.balance
  4. INVOKEVIRTUAL java/lang/Integer.intValue // thread-0 拆箱
  5. ALOAD 1 // thread-0 <- amount
  6. INVOKEVIRTUAL java/lang/Integer.intValue // thread-0 拆箱
  7. ISUB // thread-0 减法
  8. INVOKESTATIC java/lang/Integer.valueOf // thread-0 结果装箱
  9. PUTFIELD cn/itcast/AccountUnsafe.balance // thread-0 -> this.balance
  10. ALOAD 0 // thread-1 <- this
  11. ALOAD 0
  12. GETFIELD cn/itcast/AccountUnsafe.balance // thread-1 <- this.balance
  13. INVOKEVIRTUAL java/lang/Integer.intValue // thread-1 拆箱
  14. ALOAD 1 // thread-1 <- amount
  15. INVOKEVIRTUAL java/lang/Integer.intValue // thread-1 拆箱
  16. ISUB // thread-1 减法
  17. INVOKESTATIC java/lang/Integer.valueOf // thread-1 结果装箱
  18. PUTFIELD cn/itcast/AccountUnsafe.balance // thread-1 -> this.balance

单核的指令交错
多核的指令交错

解决思路-锁

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

  1. class AccountUnsafe implements Account {
  2. private Integer balance;
  3. public AccountUnsafe(Integer balance) {
  4. this.balance = balance;
  5. }
  6. @Override
  7. public synchronized Integer getBalance() {
  8. return balance;
  9. }
  10. @Override
  11. public synchronized void withdraw(Integer amount) {
  12. balance -= amount;
  13. }
  14. }

结果为

  1. 0 cost: 399 ms

解决思路-无锁

  1. class AccountSafe implements Account {
  2. private AtomicInteger balance;
  3. public AccountSafe(Integer balance) {
  4. this.balance = new AtomicInteger(balance);}
  5. @Override
  6. public Integer getBalance() {
  7. return balance.get();
  8. }
  9. @Override
  10. public void withdraw(Integer amount) {
  11. while (true) {
  12. int prev = balance.get();
  13. int next = prev - amount;
  14. if (balance.compareAndSet(prev, next)) {
  15. break;
  16. }
  17. }
  18. // 可以简化为下面的方法
  19. // balance.addAndGet(-1 * amount);
  20. }
  21. }

执行测试代码

  1. public static void main(String[] args) {
  2. Account.demo(new AccountSafe(10000));
  3. }

某次的执行结果

  1. 0 cost: 302 ms

6.2 CAS 与 volatile

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

  1. public void withdraw(Integer amount) {
  2. while(true) {
  3. // 需要不断尝试,直到成功为止
  4. while (true) {
  5. // 比如拿到了旧值 1000
  6. int prev = balance.get();
  7. // 在这个基础上 1000-10 = 990
  8. int next = prev - amount;
  9. /**
  10. compareAndSet 正是做这个检查,在 set 前,先比较 prev 与当前值
  11. - 不一致了,next 作废,返回 false 表示失败
  12. 比如,别的线程已经做了减法,当前值已经被减成了 990
  13. 那么本线程的这次 990 就作废了,进入 while 下次循环重试
  14. - 一致,以 next 设置为新值,返回 true 表示成功
  15. */
  16. if (balance.compareAndSet(prev, next)) {
  17. break;
  18. }
  19. }
  20. }
  21. }

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

注意 其实 CAS 的底层是 lock cmpxchg 指令(X86 架构),在单核 CPU 和多核 CPU 下都能够保证【比较-交换】的原子性。 在多核状态下,某个核执行到带 lock 的指令时,CPU 会让总线锁住,当这个核把此指令执行完毕,再开启总线。这个过程中不会被线程的调度机制所打断,保证了多个线程对内存操作的准确性,是原子的。

慢动作分析

  1. @Slf4j
  2. public class SlowMotion {
  3. public static void main(String[] args) {
  4. AtomicInteger balance = new AtomicInteger(10000);
  5. int mainPrev = balance.get();
  6. log.debug("try get {}", mainPrev);
  7. new Thread(() -> {
  8. sleep(1000);
  9. int prev = balance.get();
  10. balance.compareAndSet(prev, 9000);
  11. log.debug(balance.toString());
  12. }, "t1").start();
  13. sleep(2000);
  14. log.debug("try set 8000...");
  15. boolean isSuccess = balance.compareAndSet(mainPrev, 8000);
  16. log.debug("is success ? {}", isSuccess);
  17. if(!isSuccess){
  18. mainPrev = balance.get();
  19. log.debug("try set 8000...");
  20. isSuccess = balance.compareAndSet(mainPrev, 8000);
  21. log.debug("is success ? {}", isSuccess);
  22. }
  23. }
  24. private static void sleep(int millis) {
  25. try {
  26. Thread.sleep(millis);
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }

输出结果

  1. 2019-10-13 11:28:37.134 [main] try get 10000
  2. 2019-10-13 11:28:38.154 [t1] 9000
  3. 2019-10-13 11:28:39.154 [main] try set 8000...
  4. 2019-10-13 11:28:39.154 [main] is success ? false
  5. 2019-10-13 11:28:39.154 [main] try set 8000...
  6. 2019-10-13 11:28:39.154 [main] is success ? true

volatile

获取共享变量时,为了保证该变量的可见性,需要使用 volatile 修饰。
它可以用来修饰成员变量和静态成员变量,他可以避免线程从自己的工作缓存中查找变量的值,必须到主存中获取它的值,线程操作 volatile 变量都是直接操作主存。即一个线程对 volatile 变量的修改,对另一个线程可见。

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

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

为什么无锁效率高

无锁情况下,即使重试失败,线程始终在高速运行,没有停歇,而 synchronized 会让线程在没有获得锁的时候,发生上下文切换,进入阻塞。
打个比喻线程就好像高速跑道上的赛车,高速运行时,速度超快,一旦发生上下文切换,就好比赛车要减速、熄火,等被唤醒又得重新打火、启动、加速… 恢复到高速运行,代价比较大
但无锁情况下,因为线程要保持运行,需要额外 CPU 的支持,CPU 在这里就好比高速跑道,没有额外的跑道,线程想高速运行也无从谈起,虽然不会进入阻塞,但由于没有分到时间片,仍然会进入可运行状态,还是会导致上下文切换。
图片.png
CAS 的特点
结合 CAS 和 volatile 可以实现无锁并发,适用于线程数少、多核 CPU 的场景下。

  • CAS 是基于乐观锁的思想:最乐观的估计,不怕别的线程来修改共享变量,就算改了也没关系,我吃亏点再重试呗。
  • synchronized 是基于悲观锁的思想:最悲观的估计,得防着其它线程来修改共享变量,我上了锁你们都别想改,我改完了解开锁,你们才有机会。
  • CAS 体现的是无锁并发、无阻塞并发,请仔细体会这两句话的意思
    • 因为没有使用 synchronized,所以线程不会陷入阻塞,这是效率提升的因素之一
    • 但如果竞争激烈,可以想到重试必然频繁发生,反而效率会受影响

6.3 原子整数

J.U.C 并发包提供了:
AtomicBoolean
AtomicInteger
AtomicLong
以 AtomicInteger 为例

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

6.4 原子引用

为什么需要原子引用类型?
AtomicReference
AtomicMarkableReference
AtomicStampedReference
有如下方法

  1. public interface DecimalAccount {
  2. // 获取余额
  3. BigDecimal getBalance();
  4. // 取款
  5. void withdraw(BigDecimal amount);
  6. /**
  7. * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
  8. * 如果初始余额为 10000 那么正确的结果应当是 0
  9. */
  10. static void demo(DecimalAccount account) {
  11. List<Thread> ts = new ArrayList<>();
  12. for (int i = 0; i < 1000; i++) {
  13. ts.add(new Thread(() -> {
  14. account.withdraw(BigDecimal.TEN);
  15. }));
  16. }
  17. ts.forEach(Thread::start);
  18. ts.forEach(t -> {
  19. try {
  20. t.join();
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. });
  25. System.out.println(account.getBalance());
  26. }
  27. }

试着提供不同的 DecimalAccount 实现,实现安全的取款操作
不安全实现

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

安全实现-使用锁

  1. class DecimalAccountSafeLock implements DecimalAccount {
  2. private final Object lock = new Object();
  3. BigDecimal balance;
  4. public DecimalAccountSafeLock(BigDecimal balance) {
  5. this.balance = balance;
  6. }
  7. @Override
  8. public BigDecimal getBalance() {
  9. return balance;
  10. }
  11. @Override
  12. public void withdraw(BigDecimal amount) {
  13. synchronized (lock) {
  14. BigDecimal balance = this.getBalance();
  15. this.balance = balance.subtract(amount);
  16. }
  17. }
  18. }

安全实现-使用 CAS

  1. class DecimalAccountSafeCas implements DecimalAccount {
  2. AtomicReference<BigDecimal> ref;
  3. public DecimalAccountSafeCas(BigDecimal balance) {
  4. ref = new AtomicReference<>(balance);
  5. }
  6. @Override
  7. public BigDecimal getBalance() {
  8. return ref.get();
  9. }
  10. @Override
  11. public void withdraw(BigDecimal amount) {
  12. while (true) {
  13. BigDecimal prev = ref.get();
  14. BigDecimal next = prev.subtract(amount);
  15. if (ref.compareAndSet(prev, next)) {
  16. break;
  17. }
  18. }
  19. }
  20. }

测试代码

  1. DecimalAccount.demo(new DecimalAccountUnsafe(new BigDecimal("10000")));
  2. DecimalAccount.demo(new DecimalAccountSafeLock(new BigDecimal("10000")));
  3. DecimalAccount.demo(new DecimalAccountSafeCas(new BigDecimal("10000")));

运行结果

  1. 4310 cost: 425 ms
  2. 0 cost: 285 ms
  3. 0 cost: 274 ms

ABA 问题及解决
ABA 问题

  1. static AtomicReference<String> ref = new AtomicReference<>("A");
  2. public static void main(String[] args) throws InterruptedException {
  3. log.debug("main start...");
  4. // 获取值 A
  5. // 这个共享变量被它线程修改过?
  6. String prev = ref.get();
  7. other();
  8. sleep(1);
  9. // 尝试改为 C
  10. log.debug("change A->C {}", ref.compareAndSet(prev, "C"));
  11. }
  12. private static void other() {
  13. new Thread(() -> {
  14. log.debug("change A->B {}", ref.compareAndSet(ref.get(), "B"));
  15. }, "t1").start();
  16. sleep(0.5);
  17. new Thread(() -> {
  18. log.debug("change B->A {}", ref.compareAndSet(ref.get(), "A"));
  19. }, "t2").start();
  20. }

输出

  1. 11:29:52.325 c.Test36 [main] - main start...
  2. 11:29:52.379 c.Test36 [t1] - change A->B true
  3. 11:29:52.879 c.Test36 [t2] - change B->A true
  4. 11:29:53.880 c.Test36 [main] - change A->C true

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

  1. static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
  2. public static void main(String[] args) throws InterruptedException {
  3. log.debug("main start...");
  4. // 获取值 A
  5. String prev = ref.getReference();
  6. // 获取版本号
  7. int stamp = ref.getStamp();
  8. log.debug("版本 {}", stamp);
  9. // 如果中间有其它线程干扰,发生了 ABA 现象
  10. other();
  11. sleep(1);
  12. // 尝试改为 C
  13. log.debug("change A->C {}", ref.compareAndSet(prev, "C", stamp, stamp + 1));
  14. }
  15. private static void other() {
  16. new Thread(() -> {
  17. log.debug("change A->B {}", ref.compareAndSet(ref.getReference(), "B",
  18. ref.getStamp(), ref.getStamp() + 1));
  19. log.debug("更新版本为 {}", ref.getStamp());
  20. }, "t1").start();
  21. sleep(0.5);
  22. new Thread(() -> {
  23. log.debug("change B->A {}", ref.compareAndSet(ref.getReference(), "A",
  24. ref.getStamp(), ref.getStamp() + 1));
  25. log.debug("更新版本为 {}", ref.getStamp());
  26. }, "t2").start();
  27. }

输出为

  1. 15:41:34.891 c.Test36 [main] - main start...
  2. 15:41:34.894 c.Test36 [main] - 版本 0
  3. 15:41:34.956 c.Test36 [t1] - change A->B true
  4. 15:41:34.956 c.Test36 [t1] - 更新版本为 1
  5. 15:41:35.457 c.Test36 [t2] - change B->A true
  6. 15:41:35.457 c.Test36 [t2] - 更新版本为 2
  7. 15:41:36.457 c.Test36 [main] - change A->C false

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

  1. class GarbageBag {
  2. String desc;
  3. public GarbageBag(String desc) {
  4. this.desc = desc;
  5. }
  6. public void setDesc(String desc) {
  7. this.desc = desc;
  8. }
  9. @Override
  10. public String toString() {
  11. return super.toString() + " " + desc;
  12. }
  13. }
  1. @Slf4j
  2. public class TestABAAtomicMarkableReference {
  3. public static void main(String[] args) throws InterruptedException {
  4. GarbageBag bag = new GarbageBag("装满了垃圾");
  5. // 参数2 mark 可以看作一个标记,表示垃圾袋满了
  6. AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);
  7. log.debug("主线程 start...");
  8. GarbageBag prev = ref.getReference();
  9. log.debug(prev.toString());
  10. new Thread(() -> {
  11. log.debug("打扫卫生的线程 start...");
  12. bag.setDesc("空垃圾袋");
  13. while (!ref.compareAndSet(bag, bag, true, false)) {}
  14. log.debug(bag.toString());
  15. }).start();
  16. Thread.sleep(1000);
  17. log.debug("主线程想换一只新垃圾袋?");
  18. boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);
  19. log.debug("换了么?" + success);
  20. log.debug(ref.getReference().toString());
  21. }
  22. }

输出

  1. 2019-10-13 15:30:09.264 [main] 主线程 start...
  2. 2019-10-13 15:30:09.270 [main] cn.itcast.GarbageBag@5f0fd5a0 装满了垃圾
  3. 2019-10-13 15:30:09.293 [Thread-1] 打扫卫生的线程 start...
  4. 2019-10-13 15:30:09.294 [Thread-1] cn.itcast.GarbageBag@5f0fd5a0 空垃圾袋
  5. 2019-10-13 15:30:10.294 [main] 主线程想换一只新垃圾袋?
  6. 2019-10-13 15:30:10.294 [main] 换了么?false
  7. 2019-10-13 15:30:10.294 [main] cn.itcast.GarbageBag@5f0fd5a0 空垃圾袋

可以注释掉打扫卫生线程代码,再观察输出

6.5 原子数组

AtomicIntegerArray
AtomicLongArray
AtomicReferenceArray
有如下方法

  1. /**
  2. 参数1,提供数组、可以是线程不安全数组或线程安全数组
  3. 参数2,获取数组长度的方法
  4. 参数3,自增方法,回传 array, index
  5. 参数4,打印数组的方法
  6. */
  7. // supplier 提供者 无中生有 ()->结果
  8. // function 函数 一个参数一个结果 (参数)->结果 , BiFunction (参数1,参数2)->结果
  9. // consumer 消费者 一个参数没结果 (参数)->void, BiConsumer (参数1,参数2)->
  10. private static <T> void demo(
  11. Supplier<T> arraySupplier,
  12. Function<T, Integer> lengthFun,
  13. BiConsumer<T, Integer> putConsumer,
  14. Consumer<T> printConsumer ) {
  15. List<Thread> ts = new ArrayList<>();
  16. T array = arraySupplier.get();
  17. int length = lengthFun.apply(array);
  18. for (int i = 0; i < length; i++) {
  19. // 每个线程对数组作 10000 次操作
  20. ts.add(new Thread(() -> {
  21. for (int j = 0; j < 10000; j++) {
  22. putConsumer.accept(array, j%length);
  23. }
  24. }));
  25. }
  26. ts.forEach(t -> t.start()); // 启动所有线程
  27. ts.forEach(t -> {
  28. try {
  29. t.join();
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. }); // 等所有线程结束
  34. printConsumer.accept(array);
  35. }

不安全的数组

  1. demo(
  2. ()->new int[10],
  3. (array)->array.length,
  4. (array, index) -> array[index]++,
  5. array-> System.out.println(Arrays.toString(array))
  6. );

结果

  1. [9870, 9862, 9774, 9697, 9683, 9678, 9679, 9668, 9680, 9698]

安全的数组

  1. demo(
  2. ()-> new AtomicIntegerArray(10),
  3. (array) -> array.length(),
  4. (array, index) -> array.getAndIncrement(index),
  5. array -> System.out.println(array)
  6. );

结果

  1. [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]

6.6 字段更新器

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

  1. Exception in thread "main" java.lang.IllegalArgumentException: Must be volatile type
  1. public class Test5 {
  2. private volatile int field;
  3. public static void main(String[] args) {
  4. AtomicIntegerFieldUpdater fieldUpdater =AtomicIntegerFieldUpdater.newUpdater(Test5.class, "field");
  5. Test5 test5 = new Test5();
  6. fieldUpdater.compareAndSet(test5, 0, 10);
  7. // 修改成功 field = 10
  8. System.out.println(test5.field);
  9. // 修改成功 field = 20
  10. fieldUpdater.compareAndSet(test5, 10, 20);
  11. System.out.println(test5.field);
  12. // 修改失败 field = 20
  13. fieldUpdater.compareAndSet(test5, 10, 30);
  14. System.out.println(test5.field);
  15. }
  16. }

输出

  1. 10
  2. 20
  3. 20

6.7 原子累加器

累加器性能比较

  1. private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
  2. T adder = adderSupplier.get();
  3. long start = System.nanoTime();
  4. List<Thread> ts = new ArrayList<>();
  5. // 4 个线程,每人累加 50 万
  6. for (int i = 0; i < 40; i++) {
  7. ts.add(new Thread(() -> {
  8. for (int j = 0; j < 500000; j++) {
  9. action.accept(adder);
  10. }
  11. }));
  12. }
  13. ts.forEach(t -> t.start());
  14. ts.forEach(t -> {
  15. try {
  16. t.join();
  17. } catch (InterruptedException e) {
  18. e.printStackTrace();}
  19. });
  20. long end = System.nanoTime();
  21. System.out.println(adder + " cost:" + (end - start)/1000_000);
  22. }

比较 AtomicLong 与 LongAdder

  1. for (int i = 0; i < 5; i++) {
  2. demo(() -> new LongAdder(), adder -> adder.increment());
  3. }
  4. for (int i = 0; i < 5; i++) {
  5. demo(() -> new AtomicLong(), adder -> adder.getAndIncrement());
  6. }

输出

  1. 1000000 cost:43
  2. 1000000 cost:9
  3. 1000000 cost:7
  4. 1000000 cost:7
  5. 1000000 cost:7
  6. 1000000 cost:31
  7. 1000000 cost:27
  8. 1000000 cost:28
  9. 1000000 cost:24
  10. 1000000 cost:22

性能提升的原因很简单,就是在有竞争时,设置多个累加单元,Therad-0 累加 Cell[0],而 Thread-1 累加
Cell[1]… 最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性
能。
源码之 LongAdder
LongAdder 是并发大师 @author Doug Lea (大哥李)的作品,设计的非常精巧
LongAdder 类有几个关键域

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

cas 锁

  1. // 不要用于实践!!!
  2. public class LockCas {
  3. private AtomicInteger state = new AtomicInteger(0);
  4. public void lock() {
  5. while (true) {
  6. if (state.compareAndSet(0, 1)) {
  7. break;
  8. }
  9. }
  10. }
  11. public void unlock() {
  12. log.debug("unlock...");
  13. state.set(0);
  14. }
  15. }

测试

  1. LockCas lock = new LockCas();
  2. new Thread(() -> {
  3. log.debug("begin...");
  4. lock.lock();
  5. try {
  6. log.debug("lock...");
  7. sleep(1);
  8. } finally {
  9. lock.unlock();
  10. }
  11. }).start();
  12. new Thread(() -> {
  13. log.debug("begin...");
  14. lock.lock();
  15. try {
  16. log.debug("lock...");
  17. } finally {
  18. lock.unlock();
  19. }
  20. }).start();

输出

  1. 18:27:07.198 c.Test42 [Thread-0] - begin...
  2. 18:27:07.202 c.Test42 [Thread-0] - lock...
  3. 18:27:07.198 c.Test42 [Thread-1] - begin...
  4. 18:27:08.204 c.Test42 [Thread-0] - unlock...
  5. 18:27:08.204 c.Test42 [Thread-1] - lock...
  6. 18:27:08.204 c.Test42 [Thread-1] - unlock...

原理之伪共享
其中 Cell 即为累加单元

  1. // 防止缓存行伪共享
  2. @sun.misc.Contended
  3. static final class Cell {
  4. volatile long value;
  5. Cell(long x) { value = x; }
  6. // 最重要的方法, 用来 cas 方式进行累加, prev 表示旧值, next 表示新值
  7. final boolean cas(long prev, long next) {
  8. return UNSAFE.compareAndSwapLong(this, valueOffset, prev, next);
  9. }
  10. // 省略不重要代码
  11. }

得从缓存说起
缓存与内存的速度比较
图片.png
图片.png
因为 CPU 与 内存的速度差异很大,需要靠预读数据至缓存来提升效率。
而缓存以缓存行为单位,每个缓存行对应着一块内存,一般是 64 byte(8 个 long)
缓存的加入会造成数据副本的产生,即同一份数据会缓存在不同核心的缓存行中
CPU 要保证数据的一致性,如果某个 CPU 核心更改了数据,其它 CPU 核心对应的整个缓存行必须失效
图片.png
因为 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 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效
图片.png
累加主要调用下面的方法

  1. public void add(long x) {
  2. // as 为累加单元数组
  3. // b 为基础值
  4. // x 为累加值
  5. Cell[] as; long b, v; int m; Cell a;
  6. // 进入 if 的两个条件
  7. // 1. as 有值, 表示已经发生过竞争, 进入 if
  8. // 2. cas 给 base 累加时失败了, 表示 base 发生了竞争, 进入 if
  9. if ((as = cells) != null || !casBase(b = base, b + x)) {
  10. // uncontended 表示 cell 没有竞争
  11. boolean uncontended = true;
  12. if (
  13. // as 还没有创建
  14. as == null || (m = as.length - 1) < 0 ||
  15. // 当前线程对应的 cell 还没有
  16. (a = as[getProbe() & m]) == null ||
  17. // cas 给当前线程的 cell 累加失败 uncontended=false ( a 为当前线程的 cell )
  18. !(uncontended = a.cas(v = a.value, v + x))
  19. ) {
  20. // 进入 cell 数组创建、cell 创建的流程
  21. longAccumulate(x, null, uncontended);
  22. }
  23. }
  24. }

add 流程图
图片.png

  1. final void longAccumulate(long x, LongBinaryOperator fn,
  2. boolean wasUncontended) {
  3. int h;
  4. // 当前线程还没有对应的 cell, 需要随机生成一个 h 值用来将当前线程绑定到 cell
  5. if ((h = getProbe()) == 0) {
  6. // 初始化 probe
  7. ThreadLocalRandom.current();
  8. // h 对应新的 probe 值, 用来对应 cell
  9. h = getProbe();
  10. wasUncontended = true;
  11. }
  12. // collide 为 true 表示需要扩容
  13. boolean collide = false;
  14. for (;;) {
  15. Cell[] as; Cell a; int n; long v;
  16. // 已经有了 cells
  17. if ((as = cells) != null && (n = as.length) > 0) {
  18. // 还没有 cell
  19. if ((a = as[(n - 1) & h]) == null) {
  20. // 为 cellsBusy 加锁, 创建 cell, cell 的初始累加值为 x
  21. // 成功则 break, 否则继续 continue 循环
  22. }
  23. // 有竞争, 改变线程对应的 cell 来重试 cas
  24. else if (!wasUncontended)
  25. wasUncontended = true;
  26. // cas 尝试累加, fn 配合 LongAccumulator 不为 null, 配合 LongAdder 为 null
  27. else if (a.cas(v = a.value, ((fn == null) ? v + x : fn.applyAsLong(v, x))))
  28. break;
  29. // 如果 cells 长度已经超过了最大长度, 或者已经扩容, 改变线程对应的 cell 来重试 cas
  30. else if (n >= NCPU || cells != as)
  31. collide = false;
  32. // 确保 collide 为 false 进入此分支, 就不会进入下面的 else if 进行扩容了
  33. else if (!collide)
  34. collide = true;
  35. // 加锁
  36. else if (cellsBusy == 0 && casCellsBusy()) {
  37. // 加锁成功, 扩容
  38. continue;
  39. }
  40. // 改变线程对应的 cell
  41. h = advanceProbe(h);
  42. }
  43. // 还没有 cells, 尝试给 cellsBusy 加锁
  44. else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
  45. // 加锁成功, 初始化 cells, 最开始长度为 2, 并填充一个 cell
  46. // 成功则 break;
  47. }
  48. // 上两种情况失败, 尝试给 base 累加
  49. else if (casBase(v = base, ((fn == null) ? v + x : fn.applyAsLong(v, x))))
  50. break;
  51. }
  52. }

longAccumulate 流程图
图片.png
图片.png
每个线程刚进入 longAccumulate 时,会尝试对应一个 cell 对象(找到一个坑位)
图片.png
获取最终结果通过 sum 方法

  1. public long sum() {
  2. Cell[] as = cells; Cell a;
  3. long sum = base;
  4. if (as != null) {
  5. for (int i = 0; i < as.length; ++i) {
  6. if ((a = as[i]) != null)
  7. sum += a.value;
  8. }
  9. }
  10. return sum;
  11. }

6.8 Unsafe
概述
Unsafe 对象提供了非常底层的,操作内存、线程的方法,Unsafe 对象不能直接调用,只能通过反射获得

  1. public class UnsafeAccessor {
  2. static Unsafe unsafe;
  3. static {
  4. try {
  5. Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
  6. theUnsafe.setAccessible(true);
  7. unsafe = (Unsafe) theUnsafe.get(null);
  8. } catch (NoSuchFieldException | IllegalAccessException e) {
  9. throw new Error(e);
  10. }
  11. }
  12. static Unsafe getUnsafe() {
  13. return unsafe;
  14. }
  15. }

Unsafe CAS 操作

  1. @Data
  2. class Student {
  3. volatile int id;
  4. volatile String name;
  5. }
  1. Unsafe unsafe = UnsafeAccessor.getUnsafe();
  2. Field id = Student.class.getDeclaredField("id");
  3. Field name = Student.class.getDeclaredField("name");
  4. // 获得成员变量的偏移量
  5. long idOffset = UnsafeAccessor.unsafe.objectFieldOffset(id);
  6. long nameOffset = UnsafeAccessor.unsafe.objectFieldOffset(name);
  7. Student student = new Student();
  8. // 使用 cas 方法替换成员变量的值
  9. UnsafeAccessor.unsafe.compareAndSwapInt(student, idOffset, 0, 20); // 返回 true
  10. UnsafeAccessor.unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 返回 true
  11. System.out.println(student);

输出

  1. Student(id=20, name=张三)

使用自定义的 AtomicData 实现之前线程安全的原子整数 Account 实现

  1. class AtomicData {
  2. private volatile int data;
  3. static final Unsafe unsafe;
  4. static final long DATA_OFFSET;
  5. static {
  6. unsafe = UnsafeAccessor.getUnsafe();
  7. try {
  8. // data 属性在 DataContainer 对象中的偏移量,用于 Unsafe 直接访问该属性
  9. DATA_OFFSET = unsafe.objectFieldOffset(AtomicData.class.getDeclaredField("data"));
  10. } catch (NoSuchFieldException e) {
  11. throw new Error(e);
  12. }
  13. }
  14. public AtomicData(int data) {
  15. this.data = data;
  16. }
  17. public void decrease(int amount) {
  18. int oldValue;
  19. while(true) {
  20. // 获取共享变量旧值,可以在这一行加入断点,修改 data 调试来加深理解
  21. oldValue = data;
  22. // cas 尝试修改 data 为 旧值 + amount,如果期间旧值被别的线程改了,返回 false
  23. if (unsafe.compareAndSwapInt(this, DATA_OFFSET, oldValue, oldValue - amount)) {
  24. return;
  25. }
  26. }
  27. }
  28. public int getData() {
  29. return data;
  30. }
  31. }

Account 实现

  1. Account.demo(new Account() {
  2. AtomicData atomicData = new AtomicData(10000);
  3. @Override
  4. public Integer getBalance() {
  5. return atomicData.getData();
  6. }
  7. @Override
  8. public void withdraw(Integer amount) {
  9. atomicData.decrease(amount);
  10. }
  11. });

本章小结

  • CAS 与 volatile
  • API
    • 原子整数
    • 原子引用
    • 原子数组
    • 字段更新器
    • 原子累加器
  • Unsafe
    • 原理方面
      • LongAdder 源码
      • 伪共享