共享模型之无锁

  • CAS 与 volatile
  • API
    • 原子整数
    • 原子引用
    • 原子数组
    • 字段更新器
    • 原子累加器
  • Unsafe

* 原理方面

  • LongAdder 源码
  • 伪共享

    引入

问题

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

  1. package cn.itcast;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. interface Account {
  5. // 获取余额
  6. Integer getBalance();
  7. // 取款
  8. void withdraw(Integer amount);
  9. /**
  10. * 方法内会启动 1000 个线程,每个线程做 -10 元 的操作
  11. * 如果初始余额为 10000 那么正确的结果应当是 0
  12. */
  13. static void demo(Account account) {
  14. List<Thread> ts = new ArrayList<>();
  15. long start = System.nanoTime();
  16. for (int i = 0; i < 1000; i++) {
  17. ts.add(new Thread(() -> {
  18. account.withdraw(10);
  19. }));
  20. }
  21. ts.forEach(Thread::start);
  22. ts.forEach(t -> {
  23. try {
  24. t.join();
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. });
  29. long end = System.nanoTime();
  30. System.out.println(account.getBalance()
  31. + " cost: " + (end-start)/1000_000 + " ms");
  32. }
  33. }
  34. class AccountUnsafe implements Account {
  35. private Integer balance;
  36. public AccountUnsafe(Integer balance) {
  37. this.balance = balance;
  38. }
  39. @Override
  40. public Integer getBalance() {
  41. return balance;
  42. }
  43. @Override
  44. public void withdraw(Integer amount) {
  45. balance -= amount;
  46. }
  47. }
  48. public static void main(String[] args) {
  49. Account.demo(new AccountUnsafe(10000));
  50. }

1000个线程相互扣钱是线程不安全的。

解决思路-锁

给扣钱方法加锁

  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. 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. synchronized (this) {
  9. return this.balance;
  10. }
  11. }
  12. @Override
  13. public void withdraw(Integer amount) {
  14. synchronized (this) {
  15. this.balance -= amount;
  16. }
  17. }
  18. }

此时运行结果都是:0 cost: 399 ms ,账户为0

CAS 与 volatile

CAS原理

前面看到的 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 的说法),它必须是原子操作。

共享模型之无锁 - 图1

每次都获取以前的值来比较,判断是否修改过,值都是存在value变量中,而且使用volatile保证可见性,每次获取最新值。

  1. private volatile int value;

注意

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

volatile

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

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

注意

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

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

为什么无锁效率高?

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

上下文切换非常消耗时间。

共享模型之无锁 - 图2

CAS 的特点

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

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

注意:再无锁并发时,尽量控制CPU的核数大于线程数,不然线程的时间片使用完后会造成上下文切换,性能反而降低。

以下源码就说明了需要一直重试:

  1. public final int getAndUpdate(IntUnaryOperator updateFunction) {
  2. int prev, next;
  3. do {
  4. prev = get();
  5. next = updateFunction.applyAsInt(prev);
  6. } while (!compareAndSet(prev, next));
  7. return prev;
  8. }

原子整数

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));

原子引用

为什么需要原子引用类型?

  • 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. }
  6. @Override
  7. public BigDecimal getBalance() {
  8. return balance;
  9. }
  10. @Override
  11. public void withdraw(BigDecimal amount) {
  12. BigDecimal balance = this.getBalance();
  13. this.balance = balance.subtract(amount);
  14. }
  15. }

安全实现-使用锁

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

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

AtomicStampedReference

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

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

输出:

  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

AtomicMarkableReference

AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,如: A -> B -> A -> C ,通过AtomicStampedReference,我们可以知道,引用变量中途被更改了几次。

但是有时候,并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了AtomicMarkableReference。

举例:

共享模型之无锁 - 图3

  1. @Slf4j(topic = "c.Test38")
  2. public class Test38 {
  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. ref.compareAndSet(bag, bag, true, false);
  14. log.debug(bag.toString());
  15. },"保洁阿姨").start();
  16. sleep(1);
  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. }
  23. class GarbageBag {
  24. String desc;
  25. public GarbageBag(String desc) {
  26. this.desc = desc;
  27. }
  28. public void setDesc(String desc) {
  29. this.desc = desc;
  30. }
  31. @Override
  32. public String toString() {
  33. return super.toString() + " " + desc;
  34. }
  35. }

只用boolean表示是否被修改过就行。

输出:

  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 空垃圾袋

原子数组

  • AtomicIntegerArray
  • AtomicLongArray
  • AtomicReferenceArray
  1. public class Test39 {
  2. public static void main(String[] args) {
  3. // 不安全的数组 [9870, 9862, 9774, 9697, 9683, 9678, 9679, 9668, 9680, 9698]
  4. demo(
  5. ()->new int[10],
  6. (array)->array.length,
  7. (array, index) -> array[index]++,
  8. array-> System.out.println(Arrays.toString(array))
  9. );
  10. // 安全的数组 [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]
  11. demo(
  12. ()-> new AtomicIntegerArray(10),
  13. (array) -> array.length(),
  14. (array, index) -> array.getAndIncrement(index),
  15. array -> System.out.println(array)
  16. );
  17. }
  18. /**
  19. 参数1,提供数组、可以是线程不安全数组或线程安全数组
  20. 参数2,获取数组长度的方法
  21. 参数3,自增方法,回传 array, index
  22. 参数4,打印数组的方法
  23. */
  24. // supplier 提供者 无中生有 ()->结果
  25. // function 函数 一个参数一个结果 (参数)->结果 , BiFunction (参数1,参数2)->结果
  26. // consumer 消费者 一个参数没结果 (参数)->void, BiConsumer (参数1,参数2)->
  27. private static <T> void demo(
  28. Supplier<T> arraySupplier,
  29. Function<T, Integer> lengthFun,
  30. BiConsumer<T, Integer> putConsumer,
  31. Consumer<T> printConsumer ) {
  32. List<Thread> ts = new ArrayList<>();
  33. T array = arraySupplier.get();
  34. int length = lengthFun.apply(array);
  35. for (int i = 0; i < length; i++) {
  36. // 每个线程对数组作 10000 次操作
  37. ts.add(new Thread(() -> {
  38. for (int j = 0; j < 10000; j++) {
  39. putConsumer.accept(array, j%length);
  40. }
  41. }));
  42. }
  43. ts.forEach(t -> t.start()); // 启动所有线程
  44. ts.forEach(t -> {
  45. try {
  46. t.join();
  47. } catch (InterruptedException e) {
  48. e.printStackTrace();
  49. }
  50. }); // 等所有线程结束
  51. printConsumer.accept(array);
  52. }
  53. }

字段更新器

  • AtomicReferenceFieldUpdater // 域 字段
  • AtomicIntegerFieldUpdater
  • AtomicLongFieldUpdater

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

  1. @Slf4j(topic = "c.Test40")
  2. public class Test40 {
  3. public static void main(String[] args) {
  4. Student stu = new Student();
  5. AtomicReferenceFieldUpdater updater =
  6. AtomicReferenceFieldUpdater.newUpdater(Student.class, String.class, "name");
  7. // 需要stu的name字段为空才能更新,否则更新失败
  8. System.out.println(updater.compareAndSet(stu, null, "张三"));
  9. System.out.println(stu);
  10. }
  11. }
  12. class Student {
  13. volatile String name;
  14. @Override
  15. public String toString() {
  16. return "Student{" +
  17. "name='" + name + '\'' +
  18. '}';
  19. }
  20. }

原子累加器

再多个线程对一个数据进行累加时,可以使用原子累加器提高效率。

  1. public class Test41 {
  2. public static void main(String[] args) {
  3. for (int i = 0; i < 5; i++) {
  4. demo(
  5. () -> new AtomicLong(0),
  6. (adder) -> adder.getAndIncrement()
  7. );
  8. }
  9. for (int i = 0; i < 5; i++) {
  10. demo(
  11. () -> new LongAdder(),
  12. adder -> adder.increment()
  13. );
  14. }
  15. }
  16. /*
  17. () -> 结果 提供累加器对象
  18. (参数) -> 执行累加操作
  19. */
  20. private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
  21. T adder = adderSupplier.get();
  22. List<Thread> ts = new ArrayList<>();
  23. // 4 个线程,每人累加 50 万
  24. for (int i = 0; i < 4; i++) {
  25. ts.add(new Thread(() -> {
  26. for (int j = 0; j < 500000; j++) {
  27. action.accept(adder);
  28. }
  29. }));
  30. }
  31. long start = System.nanoTime();
  32. ts.forEach(t -> t.start());
  33. ts.forEach(t -> {
  34. try {
  35. t.join();
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. });
  40. long end = System.nanoTime();
  41. System.out.println(adder + " cost:" + (end - start) / 1000_000);
  42. }
  43. }

结果:

  1. 2000000 cost:44
  2. 2000000 cost:40
  3. 2000000 cost:36
  4. 2000000 cost:29
  5. 2000000 cost:36
  6. 2000000 cost:13
  7. 2000000 cost:5
  8. 2000000 cost:6
  9. 2000000 cost:6
  10. 2000000 cost:5

性能提升的原因很简单,就是在有竞争时,设置多个累加单元,Therad-0 累加 Cell[0],而 Thread-1 累加Cell[1]… 最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性能。

源码之 LongAdder

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. }

得从缓存说起

缓存与内存的速度比较

共享模型之无锁 - 图4

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

共享模型之无锁 - 图5

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

共享模型之无锁 - 图6

累加主要调用下面的方法

add方法

  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流程图

共享模型之无锁 - 图7

longAccumulate

  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 流程图

共享模型之无锁 - 图8

共享模型之无锁 - 图9

每个线程刚进入 longAccumulate 时,会尝试对应一个 cell 对象(找到一个坑位)

共享模型之无锁 - 图10

获取最终结果通过 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; }

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. public class UncafeTest {
  2. public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
  3. // 通过反射来获取对象
  4. Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
  5. theUnsafe.setAccessible(true);
  6. Unsafe unsafe = (Unsafe) theUnsafe.get(null);
  7. // 获取成员变量的偏移地址
  8. long idOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("id"));
  9. long nameOffset = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));
  10. Student student = new Student();
  11. // 执行cas操作
  12. unsafe.compareAndSwapInt(student,idOffset,0,2);
  13. unsafe.compareAndSwapObject(student,nameOffset,null,"黄忠");
  14. System.out.println(student);
  15. }
  16. }
  17. class Student {
  18. volatile int id;
  19. volatile String name;
  20. @Override
  21. public String toString() {
  22. return "Student{" +
  23. "id=" + id +
  24. ", name='" + name + '\'' +
  25. '}';
  26. }
  27. }

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

  1. @Slf4j(topic = "c.Test42")
  2. public class Test42 {
  3. public static void main(String[] args) {
  4. Account.demo(new MyAtomicInteger(10000));
  5. }
  6. }
  7. class MyAtomicInteger implements Account {
  8. private volatile int value;
  9. private static final long valueOffset;
  10. private static final Unsafe UNSAFE;
  11. static {
  12. UNSAFE = UnsafeAccessor.getUnsafe();
  13. try {
  14. valueOffset = UNSAFE.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
  15. } catch (NoSuchFieldException e) {
  16. e.printStackTrace();
  17. throw new RuntimeException();
  18. }
  19. }
  20. public int getValue() {
  21. return value;
  22. }
  23. public void decrement(int amount) {
  24. while (true) {
  25. int pre = this.value;
  26. int next = value - amount;
  27. if (UNSAFE.compareAndSwapInt(this, valueOffset, pre, next)) {
  28. break;
  29. }
  30. }
  31. }
  32. public MyAtomicInteger(int value) {
  33. this.value = value;
  34. }
  35. @Override
  36. public Integer getBalance() {
  37. return getValue();
  38. }
  39. @Override
  40. public void withdraw(Integer amount) {
  41. decrement(amount);
  42. }
  43. }