Java并发编程(七) (共享模型之无锁)_ CAS概念、原子操作类、LongAddr原子累加器、Unsafe·
一、 共享模型之无锁·
- Java中 synchronized 和 ReentrantLock 等 独占锁 就是 悲观锁 思想的实现
- 在Java中java.util.concurrent.atomic包下面的原子变量类就是使用了乐观锁的一种实现方式 CAS 实现的
- 管程即monitor是阻塞式的悲观锁实现并发控制,这章我们将通过非阻塞式的乐观锁的来实现并发控制
1、 问题提出·
- 有如下需求,保证account.withdraw取款方法的线程安全, 下面使用synchronized保证线程安全
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
|
@Slf4j(topic = "guizy.Test1") public class Test1 {
public static void main(String[] args) { Account.demo(new AccountUnsafe(10000)); Account.demo(new AccountCas(10000)); } }
class AccountUnsafe implements Account { private Integer balance;
public AccountUnsafe(Integer balance) { this.balance = balance; }
@Override public Integer getBalance() { synchronized (this) { return balance; } }
@Override public void withdraw(Integer amount) { synchronized (this) { balance -= amount; } } }
interface Account { Integer getBalance();
void withdraw(Integer amount);
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 -> 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"); } }
|
解决思路-无锁·
- 上面的代码中使用synchronized加锁操作来保证线程安全,但是 synchronized加锁操作太耗费资源 (因为底层使用了操作系统mutex指令, 造成内核态和用户态的切换) ,这里我们使用 无锁 来解决此问题
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
| class AccountCas implements Account { private AtomicInteger balance;
public AccountCas(int balance) { this.balance = new AtomicInteger(balance); }
@Override public Integer getBalance() { return balance.get(); }
@Override public void withdraw(Integer amount) { while(true) { int prev = balance.get(); int next = prev - amount;
if(balance.compareAndSet(prev, next)) { break; } } } }
|
2、 CAS 与 volatile (重点)·
使用原子操作来保证线程访问共享资源的安全性, cas+重试的机制来确保(乐观锁思想), 相对于悲观锁思想的synchronized,reentrantLock来说, cas的方式效率会更好!
2.1、cas + 重试 的原理·
- 前面看到的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
| @Override public void withdraw(Integer amount) { while (true){ int prev = balance.get(); int next = prev - amount;
if (atomicInteger.compareAndSet(prev,next)){ break; } } }
|
- 其中的关键是 compareAndSwap(比较并设置值),它的简称就是 CAS (也有 Compare And Swap 的说法),它必须是原子操作。
流程 :
- 当一个线程要去修改Account对象中的值时,先获取值prev(调用get方法),然后再将其设置为新的值next(调用cas方法)。在调用cas方法时,会将prev与Account中的余额进行比较。
- 如果两者相等,就说明该值还未被其他线程修改,此时便可以进行修改操作。
- 如果两者不相等,就不设置值,重新获取值prev(调用get方法),然后再将其设置为新的值next(调用cas方法),直到修改成功为止。
注意 :
- 其实 CAS 的底层是 lock cmpxchg 指令(X86 架构),在单核 CPU 和多核 CPU 下都能够保证【比较-交换】的 原子性。
- 在多核状态下,某个核执行到带 lock 的指令时,CPU 会让总线锁住,当这个核把此指令执行完毕,再开启总线。这个过程中不会被线程的调度机制所打断,保证了多个线程对内存操作的准确性,是原子的。
/network-asset-1646751829323-74dfb992-d699-4d1e-aa91-d575c4c4dc54-20240104144835-65bpmf0.png)
2.2、volatile的作用·
- 在上面代码中的AtomicInteger类,保存值的value属性使用了volatile 修饰。获取共享变量时,为了保证该变量的可见性,需要使用 volatile 修饰。
- volatile可以用来修饰 成员变量和静态成员变量,他可以避免线程从自己的工作缓存中查找变量的值,必须到主存中获取它的值,线程操作 volatile 变量都是直接操作主存。即一个线程对 volatile 变量的修改,对另一个线程可见。
注意: volatile 仅仅保证了共享变量的可见性,让其它线程能够看到最新值,但不能解决指令交错问题(不能保证原子性)
- CAS 必须借助 volatile 才能读取到共享变量的最新值来实现【比较并交换】的效果
2.3、为什么CAS+重试(无锁)效率高·
- 使用CAS+重试—无锁情况下,即使重试失败,线程始终在高速运行,没有停歇,而 synchronized会让线程在没有获得锁的时候,发生上下文切换,进入阻塞。
- 打个比喻:线程就好像高速跑道上的赛车,高速运行时,速度超快,一旦发生上下文切换,就好比赛车要减速、熄火,等被唤醒又得重新打火、启动、加速… 恢复到高速运行,代价比较大
- 但无锁情况下,因为线程要保持运行,需要额外 CPU 的支持,CPU 在这里就好比高速跑道,没有额外的跑道,线程想高速运行也无从谈起,虽然不会进入阻塞,但由于没有分到时间片,仍然会进入可运行状态,还是会导致上下文切换。
2.4、CAS 的特点 (乐观锁和悲观锁的特点)·
结合 CAS 和 volatile 可以实现无锁并发,适用于线程数少、多核 CPU 的场景下。
- CAS 是基于乐观锁的思想:最乐观的估计,不怕别的线程来修改共享变量,就算改了也没关系,我吃亏点再重试呗。
- synchronized 是基于悲观锁的思想:最悲观的估计,得防着其它线程来修改共享变量,我上了锁你们都别想改,我改完了解开锁,你们才有机会。
- CAS 体现的是无锁并发、无阻塞并发,请仔细体会这两句话的意思
- 因为没有使用 synchronized,所以线程不会陷入阻塞,这是效率提升的因素之一
- 但如果竞争激烈(写操作多),可以想到重试必然频繁发生,反而效率会受影响
3、原子整数 (内部通过CAS来实现-AtomicInteger)·
- java.util.concurrent.atomic并发包提供了一些并发工具类,这里把它分成五类:
- 使用原子的方式 (共享数据为基本数据类型原子类)
- AtomicInteger:整型原子类
- AtomicLong:长整型原子类
- AtomicBoolean :布尔型原子类
- 上面三个类提供的方法几乎相同,所以我们将以 AtomicInteger为例子来介绍。先讨论原子整数类,以 AtomicInteger 为例讨论它的api接口:通过观察源码可以发现
- AtomicInteger 内部都是通过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
| public static void main(String[] args) { AtomicInteger i = new AtomicInteger(0); System.out.println(i.getAndIncrement()); System.out.println(i.incrementAndGet()); System.out.println(i.decrementAndGet()); System.out.println(i.getAndDecrement()); System.out.println(i.getAndAdd(5)); System.out.println(i.addAndGet(-5)); System.out.println(i.getAndUpdate(p -> p - 2)); System.out.println(i.updateAndGet(p -> p + 2)); System.out.println(i.getAndAccumulate(10, (p, x) -> p + x)); System.out.println(i.accumulateAndGet(-10, (p, x) -> p + x)); }
|
举个例子: updateAndGet的实现·
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(5); updateAndGet(i, new IntUnaryOperator() { @Override public int applyAsInt(int operand) { return operand / 2; } }); System.out.println(i.get()); }
public static void updateAndGet(AtomicInteger i, IntUnaryOperator operator) { while (true) { int prev = i.get(); int next = operator.applyAsInt(prev); if (i.compareAndSet(prev, next)) { break; } } }
|
步骤:
- 调用updateAndGet方法, 将共享变量i, IntUnaryOperator对象传递过去
- updateAndGet方法内部, 传过来的operator对象, 调用IntUnaryOperator中的applyAsInt方法, 实际调用的就是传递过来的对象的方法, 进行 / 操作
/network-asset-1647181649928-0a25abfc-2107-4eb8-a1dc-f9c525402cbd-20240104144835-vzjlei1.png)
4、原子引用 (AtomicReference)·
原子引用的作用: 保证引用类型的共享变量是线程安全的(确保这个原子引用没有引用过别人)
- AtomicReference
- AtomicMarkableReference
- AtomicStampedReference (可以解决ABA问题)
为什么需要原子引用类型?保证引用类型的共享变量是线程安全的(确保这个原子引用没有引用过别人)。 基本类型原子类只能更新一个变量,如果需要原子更新多个变量,需要使用引用类型原子类。
- AtomicReference:引用类型原子类
- AtomicStampedReference:原子更新带有版本号的引用类型。该类将整数值与引用关联起来,可用于解决原子的更新数据和数据的版本号,可以解决使用 CAS 进行原子更新时可能出现的 ABA 问题。
- AtomicMarkableReference :原子更新带有标记的引用类型。该类将 boolean 标记与引用关联起来,
也可以解决使用 CAS 进行原子更新时可能出现的 ABA 问题。
例子 : 使用原子引用实现BigDecimal存取款的线程安全:下面这个是不安全的实现过程:
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); } }
|
解决代码如下:在AtomicReference类中,存在一个value类型的变量,保存对BigDecimal对象的引用。
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
| public class Test1 {
public static void main(String[] args) { DecimalAccount.demo(new DecimalAccountCas(new BigDecimal("10000"))); } }
class DecimalAccountCas implements DecimalAccount {
private final 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 prev = balance.get(); BigDecimal next = prev.subtract(amount); if (balance.compareAndSet(prev, next)) { break; } } } }
interface DecimalAccount { BigDecimal getBalance();
void withdraw(BigDecimal amount);
static void demo(DecimalAccount account) { List<Thread> ts = new ArrayList<>(); for (int i = 0; i < 1000; i++) { ts.add(new Thread(() -> { account.withdraw(BigDecimal.TEN); })); } ts.forEach(Thread::start); ts.forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); System.out.println(account.getBalance()); } }
|
ABA 问题及解决 (重点)·
- 如下程序所示,虽然 在other方法中存在两个线程对共享变量进行了修改,但是修改之后又变成了原值,main线程对修改过共享变量的过程是不可见的,这种操作这对业务代码并无影响。
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
| public class Test1 {
static AtomicReference<String> ref = new AtomicReference<>("A");
public static void main(String[] args) { new Thread(() -> { String pre = ref.get(); System.out.println("change"); try { other(); } catch (InterruptedException e) { e.printStackTrace(); } Sleeper.sleep(1); System.out.println("change A->C " + ref.compareAndSet(pre, "C")); }).start(); }
static void other() throws InterruptedException { new Thread(() -> { System.out.println("change A->B " + ref.compareAndSet(ref.get(), "B")); }).start(); Thread.sleep(500); new Thread(() -> { System.out.println("change B->A " + ref.compareAndSet(ref.get(), "A")); }).start(); } }
|
change change A->B true change B->A true change A->C true
- 主线程仅能判断出共享变量的值与最初值 A是否相同,不能感知到这种从 A 改为 B 又改回 A 的情况,如果主线程希望:只要有其它线程【动过】共享变量,那么自己的 cas 就算失败,这时,仅比较值是不够的,需要再加一个版本号。使用AtomicStampedReference来解决。
AtomicStampedReference (加版本号解决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 28 29 30 31 32 33 34 35 36 37 38
| public class Test1 { static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
public static void main(String[] args) { new Thread(() -> { String pre = ref.getReference(); int stamp = ref.getStamp(); System.out.println("change"); try { other(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("change A->C stamp " + stamp + ref.compareAndSet(pre, "C", stamp, stamp + 1)); }).start(); }
static void other() throws InterruptedException { new Thread(() -> { int stamp = ref.getStamp(); System.out.println("change A->B stamp " + stamp + ref.compareAndSet(ref.getReference(), "B", stamp, stamp + 1)); }).start(); Thread.sleep(500); new Thread(() -> { int stamp = ref.getStamp(); System.out.println("change B->A stamp " + stamp + ref.compareAndSet(ref.getReference(), "A", stamp, stamp + 1)); }).start(); } }
|
change change A->B stamp 0true change B->A stamp 1true change A->C stamp 0false
AtomicMarkableReference (标记cas的共享变量是否被修改过)·
- AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,如:A -> B -> A ->C,通过AtomicStampedReference,我们可以知道,引用变量中途被更改了几次。
- 但是有时候,并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了AtomicMarkableReference
/network-asset-1647269992442-287e9e2e-daae-42e9-babf-e6c5da23888d-20240104144836-56mfn8r.png)
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
| @Slf4j(topic = "guizy.TestABAAtomicMarkableReference") public class TestABAAtomicMarkableReference { public static void main(String[] args) throws InterruptedException { GarbageBag bag = new GarbageBag("装满了垃圾"); AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true); log.debug("主线程 start..."); GarbageBag prev = ref.getReference(); log.debug(prev.toString()); new Thread(() -> { log.debug("打扫卫生的线程 start..."); bag.setDesc("空垃圾袋"); while (!ref.compareAndSet(bag, bag, true, false)) { } log.debug(bag.toString()); }).start(); Thread.sleep(1000); log.debug("主线程想换一只新垃圾袋?"); boolean success = ref.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false); log.debug("换了么?" + success); log.debug(ref.getReference().toString()); } }
class GarbageBag { String desc;
public GarbageBag(String desc) { this.desc = desc; }
public void setDesc(String desc) { this.desc = desc; }
@Override public String toString() { return super.toString() + " " + desc; } }
|
23:01:04.703 [main] DEBUG create.thread - 主线程 start… 23:01:04.705 [main] DEBUG create.thread - com.fei.GarbageBag@4b168fa9 装满了垃圾 23:01:04.706 [Thread-1] DEBUG create.thread - 打扫卫生的线程 start… 23:01:04.706 [Thread-1] DEBUG create.thread - com.fei.GarbageBag@4b168fa9 空垃圾袋 23:01:05.706 [main] DEBUG create.thread - 主线程想换一只新垃圾袋? 23:01:05.706 [main] DEBUG create.thread - 换了么?false 23:01:05.706 [main] DEBUG create.thread - com.fei.GarbageBag@4b168fa9 空垃圾袋
举例2:
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 Test1 { static AtomicMarkableReference<String> ref = new AtomicMarkableReference<>("A", true);
public static void main(String[] args) { new Thread(() -> { String pre = ref.getReference(); System.out.println("change"); try { other(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("change A->C mark " + ref.compareAndSet(pre, "C", true, false)); }).start(); }
static void other() throws InterruptedException { new Thread(() -> { System.out.println("change A->A mark " + ref.compareAndSet(ref.getReference(), "A", true, false)); }).start(); } }
|
change change A->A mark true change A->C mark false
AtomicStampedReference和AtomicMarkableReference两者的区别·
- AtomicStampedReference 需要我们传入 整型变量 作为版本号,来判定是否被更改过
- AtomicMarkableReference需要我们传入布尔变量 作为标记,来判断是否被更改过
5、原子数组 (AtomicIntegerArray)·
- 保证数组内的元素的线程安全
- 使用原子的方式更新数组里的某个元素
- 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 47
| public class AtomicArrayTest { public static void main(String[] args) { demo( () -> new int[10], array -> array.length, (array, index) -> array[index]++, array -> System.out.println(Arrays.toString(array)) ); }
private static <T> void demo(Supplier<T> arraySupplier, Function<T, Integer> lengthFun, BiConsumer<T, Integer> putConsumer, Consumer<T> printConsumer) { List<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); } }
|
[9870, 9862, 9774, 9697, 9683, 9678, 9679, 9668, 9680, 9698]
- 使用AtomicIntegerArray来创建安全数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| demo( ()-> new AtomicIntegerArray(10), (array) -> array.length(), (array, index) -> array.getAndIncrement(index), array -> System.out.println(array) );
demo( ()-> new AtomicIntegerArray(10), AtomicIntegerArray::length, AtomicIntegerArray::getAndIncrement, System.out::println );
|
[10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]
6、字段更新器·
保证多线程访问同一个对象的成员变量时, 成员变量的线程安全性。
- AtomicReferenceFieldUpdater —引用类型的属性
- AtomicIntegerFieldUpdater —整形的属性
- AtomicLongFieldUpdater —长整形的属性
注意:利用字段更新器,可以针对对象的某个域(Field)进行原子操作,只能配合 volatile 修饰的字段使用,否则会出现异常。
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 17 18 19 20 21 22 23 24 25 26 27
| @Slf4j(topic = "guizy.AtomicFieldTest") public class AtomicFieldTest { public static void main(String[] args) { Student stu = new Student(); AtomicReferenceFieldUpdater updater = AtomicReferenceFieldUpdater.newUpdater(Student.class, String.class, "name"); System.out.println(updater.compareAndSet(stu, null, "张三")); System.out.println(updater.compareAndSet(stu, stu.name, "王五")); System.out.println(stu); } }
class Student { volatile String name;
@Override public String toString() { return "Student{" + "name='" + name + '\'' + '}'; } }
|
true true Student{name=‘王五’}
7、原子累加器 (LongAddr) (重要)·
- LongAddr
- LongAccumulator
- DoubleAddr
- DoubleAccumulator
累加器性能比较 AtomicLong, LongAddr·
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
| @Slf4j(topic = "guizy.Test") public class Test { public static void main(String[] args) { System.out.println("----AtomicLong----"); for (int i = 0; i < 5; i++) { demo(() -> new AtomicLong(), adder -> adder.getAndIncrement()); }
System.out.println("----LongAdder----"); for (int i = 0; i < 5; i++) { demo(() -> new LongAdder(), adder -> adder.increment()); } }
private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) { T adder = adderSupplier.get(); long start = System.nanoTime(); List<Thread> ts = new ArrayList<>(); for (int i = 0; i < 40; i++) { ts.add(new Thread(() -> { for (int j = 0; j < 500000; j++) { action.accept(adder); } })); } ts.forEach(t -> t.start()); ts.forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); long end = System.nanoTime(); System.out.println(adder + " cost:" + (end - start) / 1000_000); } }
|
----AtomicLong---- 20000000 cost:276 20000000 cost:235 20000000 cost:241 20000000 cost:245 20000000 cost:251 ----LongAdder---- 20000000 cost:34 20000000 cost:31 20000000 cost:26 20000000 cost:27 20000000 cost:27
LongAdder
- 性能提升的原因很简单,就是在有竞争时,设置多个累加单元(但不会超过cpu的核心数),Therad-0 累加 Cell[0],而 Thread-1 累加Cell[1]… 最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性能。
AtomicLong
- 之前AtomicLong等都是在一个共享资源变量上进行竞争, while(true)循环进行CAS重试, 性能没有LongAdder高
8、LongAdder原理 (了解)·
原理之伪共享·
/network-asset-1647270491593-df78d6c4-9a6c-4ef9-8ace-c5740b6d1641-20240104144836-j6zy1fj.png)
/network-asset-1647270520659-d9880ba3-61f7-4905-8b39-5e184d4bc55f-20240104144836-afgpfd3.png)
- 因为 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 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效
累加主要调用以下方法
1 2 3 4 5 6 7 8 9 10 11
| public void add(long x) { Cell[] as; long b, v; int m; Cell a; if ((as = cells) != null || !casBase(b = base, b + x)) { boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[getProbe() & m]) == null || !(uncontended = a.cas(v = a.value, v + x))) longAccumulate(x, null, uncontended); } }
|
累加流程图/network-asset-1647270604470-2e89ad0f-2437-4ade-9aa8-d0c9d7a46ed8-20240104144837-mwqpmgk.png)
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
| final void longAccumulate(long x, LongBinaryOperator fn, boolean wasUncontended) { int h; if ((h = getProbe()) == 0) { ThreadLocalRandom.current(); h = getProbe(); wasUncontended = true; } boolean collide = false; for (; ; ) { Cell[] as; Cell a; int n; long v; if ((as = cells) != null && (n = as.length) > 0) { if ((a = as[(n - 1) & h]) == null) { } else if (!wasUncontended) { wasUncontended = true; } else if (a.cas(v = a.value, ((fn == null) ? v + x : fn.applyAsLong(v, x)))) { break; } else if (n >= NCPU || cells != as) { collide = false; } else if (!collide) { collide = true; } else if (cellsBusy == 0 && casCellsBusy()) { continue; } h = advanceProbe(h); } else if (cellsBusy == 0 && cells == as && casCellsBusy()) { } else if (casBase(v = base, ((fn == null) ? v + x : fn.applyAsLong(v, x)))) { break; } } }
|
longAccumulate 流程图
/image-20240123003852925.png)
/image-20240123003903652.png)
每个线程刚进入 longAccumulate 时,会尝试对应一个 cell 对象(找到一个坑位)
/image-20240123003921777.png)
获取最终结果通过 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 对象不能直接调用,只能通过反射获得
- 可以发现AtomicInteger以及其他的原子类, 底层都使用的是Unsafe类
/network-asset-1647270624908-cb75302d-4362-488e-9a0a-3e9a72d3b3e0-20240104144837-kbmz6qc.png)
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
| public class Test { public static void main(String[] args) throws Exception { Class unsafeClass = Unsafe.class; Constructor constructor = unsafeClass.getDeclaredConstructor(); constructor.setAccessible(true); Unsafe unsafe = (Unsafe) constructor.newInstance();
Person person = new Person(); long nameOffset = unsafe.objectFieldOffset(Person.class.getDeclaredField("name")); long ageOffset = unsafe.objectFieldOffset(Person.class.getDeclaredField("age"));
unsafe.compareAndSwapObject(person, nameOffset, null, "guizy"); unsafe.compareAndSwapInt(person, ageOffset, 0, 22); System.out.println(person); } }
class Person { volatile String name; volatile int age; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
|
- 使用自定义的 AtomicData 实现之前线程安全的原子整数 Account 实现
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
| class AtomicData {
private volatile int data; static final Unsafe unsafe; static final long DATA_OFFSET;
static { unsafe = UnsafeAccessor.getUnsafe(); try { DATA_OFFSET = unsafe.objectFieldOffset( AtomicData.class.getDeclaredField("data") ); } catch (NoSuchFieldException e) { throw new Error(e); } }
public AtomicData(int data) { this.data = data; }
public void decrease(int amount) { int oldValue; while (true) { oldValue = data; if ( unsafe.compareAndSwapInt( this, DATA_OFFSET, oldValue, oldValue - amount ) ) { return; } } }
public int getData() { return data; } }
|
Account 实现
1 2 3 4 5 6 7 8 9 10 11
| Account.demo(new Account() { AtomicData atomicData = new AtomicData(10000); @Override public Integer getBalance() { return atomicData.getData(); } @Override public void withdraw(Integer amount) { atomicData.decrease(amount); } });
|