JUC并发编程共享模型之不可变(五)
创始人
2025-06-01 16:42:45
0

5.1 问题引出

public interface Account {// 获取余额Integer getBalance();void withdraw(Integer amount);/*** 方法内会启动1000个线程,每个线程做-10元的操作* 如果初始余额为 10000 那么正确的结果应当是0*/static void demo(Account account){List 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)/1000000 + "ms");}
}
@Slf4j
public class AccountTest {public static void main(String[] args) {Account.demo(new AccountUnsafe(10000));}
}class AccountUnsafe implements Account {private Integer balance;public AccountUnsafe(Integer balance) {this.balance = balance;}@Overridepublic Integer getBalance() {return balance;}@Overridepublic void withdraw(Integer amount) {balance -= amount;}
}

在这里插入图片描述

为什么不安全

  • 线程不安全的
  • 问题出在withdraw方法上
    public void withdraw(Integer amount) {balance -= amount;}// 对应的字节码文件
ALOAD 0 // <- this
ALOAD 0
GETFIELD cn/itcast/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 cn/itcast/AccountUnsafe.balance : Ljava/lang/Integer; // -> this.balance// 多线程执行流程
ALOAD 0 // thread-0 <- this 
ALOAD 0 
GETFIELD cn/itcast/AccountUnsafe.balance // thread-0 <- this.balance 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-0 拆箱
ALOAD 1 // thread-0 <- amount 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-0 拆箱
ISUB // thread-0 减法
INVOKESTATIC java/lang/Integer.valueOf // thread-0 结果装箱
PUTFIELD cn/itcast/AccountUnsafe.balance // thread-0 -> this.balance ALOAD 0 // thread-1 <- this 
ALOAD 0 
GETFIELD cn/itcast/AccountUnsafe.balance // thread-1 <- this.balance 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-1 拆箱
ALOAD 1 // thread-1 <- amount 
INVOKEVIRTUAL java/lang/Integer.intValue // thread-1 拆箱
ISUB // thread-1 减法
INVOKESTATIC java/lang/Integer.valueOf // thread-1 结果装箱
PUTFIELD cn/itcast/AccountUnsafe.balance // thread-1 -> this.balance 
  • 单核的指令交错
  • 多核的指令交错

解决思路-锁

@Slf4j
public class AccountTest01 {public static void main(String[] args) {Account.demo(new AccountSafe(10000));}
}class AccountSafe implements Account {private Integer balance;public AccountSafe(Integer balance) {this.balance = balance;}@Overridepublic Integer getBalance() {return balance;}@Overridepublic synchronized void withdraw(Integer amount) {balance -= amount;}
}

在这里插入图片描述

解决思路-无锁

@Slf4j
public class AccountTest02 {public static void main(String[] args) {Account.demo(new AccountSafe01(10000));}
}class AccountSafe01 implements Account {private AtomicInteger balance;public AccountSafe01(Integer balance) {this.balance = new AtomicInteger(balance);}@Overridepublic Integer getBalance() {return balance.get();}@Overridepublic void withdraw(Integer amount) {while (true){int prev = balance.get();int next = prev - amount;if (balance.compareAndSet(prev, next)){break;}}// 可以简化为下面的方法// balance.addAndGet(-1 * amount);}
}

在这里插入图片描述

5.2 CAS 与 volatile

前面看到的 AtomicInteger 的解决方法,内部并没有用锁来保护共享变量的线程安全

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

其中的关键 compareAndSet,它的简称是CAS(Compare And Swap),它必须是原子操作

在这里插入图片描述

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

换一种简单的代码

@Slf4j
public class SlowMontionTest {public static void main(String[] args) {AtomicInteger balance = new AtomicInteger(10000);int mainPrev = balance.get();log.debug("try get {}",mainPrev);new Thread(() -> {sleep(1000);int prev = balance.get();balance.compareAndSet(prev, 9000);log.debug(balance.toString());},"t1").start();sleep(2000);log.debug("try set 8000....");boolean isSuccess = balance.compareAndSet(mainPrev, 8000);log.debug("is success ? {}",isSuccess);if (!isSuccess){mainPrev = balance.get();log.debug("try set 8000...");isSuccess = balance.compareAndSet(mainPrev, 8000);log.debug("is success  ? {}",isSuccess);}}private static void sleep(int millis) {try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}
}

在这里插入图片描述

volatile

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

  • 它可以用来修饰成员变量和静态成员变量,他可以避免线程从自己的工作缓存中查找变量的值,线程操作 volatile 变量都是直接操作主存,即一个线程对 volatile 变量的修改,对另一个线程可见
    • volatile 仅仅保证了共享变量的可见性,让其它线程能够看到最新值,但不能解决指令交错问题(不能保证原 子性)
  • CAS 必须借助 volatile 才能读取到共享变量的最新值来实现 【比较并交换】的效果

为什么无锁效率高

看开头的那两个运行时间

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

在这里插入图片描述

CAS特点

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

  • CAS 是基于乐观锁的思想:最乐观的估计,不怕别的线程来修改共享变量,就算改了,我再重试
  • synchronized 是基于悲观锁的思想:最悲观的估计,放着其他线程去修改共享变量,上了锁都别改,解了锁才有机会能改
  • CAS 体现的是无锁并发、无阻塞并发
    • 因为没有使用 synchronized ,所以线程不会陷入阻塞,这是效率提升的因素之一
    • 但如果竞争激烈,可以想到重试必然频繁发生,反而效率受影响

5.3 原子整数

J.U.C 并发包提供了:

  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
@Slf4j
public class AtomicIntegerTest {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) 类似++iSystem.out.println(i.incrementAndGet());// 自减并获取(i = 2, 结果 i = 1, 返回 1),类似于 --iSystem.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.getAndUpdate(p -> p + 2));// 获取并计算(i = 0, p 为 i 的当前值, x 为参数1, 结果 i = 10, 返回 0)// 其中函数中的操作能保证原子,但函数需要无副作用// getAndUpdate 如果在 lambda 中引用了外部的局部变量,要保证该局部变量是 final 的// getAndAccumulate 可以通过 参数1 来引用外部的局部变量,但因为其不在 lambda 中因此不必是 finalSystem.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));}
}

5.4 原子引用

为什么需要原子引用? 因为引用类型也需要被保护

  • AtomicReference
  • AtomicMarkableReference
  • AtomicStampedReference

测试代码

声明一个接口

public interface DecimalAccount {// 获取余额BigDecimal getBalance();// 取款void withdraw(BigDecimal amout);/*** 方法内会启动 1000 个线程,每个线程做 -10 元的操作* 如果初始余额为 10000  那么正确的结果应当 0*/static void demo(DecimalAccount account){List 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());}}

不安全的实现

@Slf4j
public class DecimalAccountTest01 implements DecimalAccount{BigDecimal balance;public DecimalAccountTest01(BigDecimal balance) {this.balance = balance;}@Overridepublic BigDecimal getBalance() {return balance;}@Overridepublic void withdraw(BigDecimal amout) {BigDecimal balance = this.getBalance();this.balance = balance.subtract(amout);}public static void main(String[] args) {DecimalAccount.demo(new DecimalAccountTest01(new BigDecimal("10000")));}
}

在这里插入图片描述

用synchronized锁安全实现

@Slf4j
public class DecimalAccountTest03 implements DecimalAccount{BigDecimal balance;private final Object lock = new Object();public DecimalAccountTest03(BigDecimal balance) {this.balance = balance;}@Overridepublic BigDecimal getBalance() {return balance;}@Overridepublic void withdraw(BigDecimal amout) {synchronized (lock){BigDecimal balance = this.getBalance();this.balance = balance.subtract(amout);}}public static void main(String[] args) {DecimalAccount.demo(new DecimalAccountTest03(new BigDecimal("10000")));}
}

在这里插入图片描述

用CAS 安全实现

@Slf4j
public class DecimalAccountTest02 implements DecimalAccount{AtomicReference ref;public DecimalAccountTest02(BigDecimal balance) {ref = new AtomicReference(balance);}@Overridepublic BigDecimal getBalance() {return ref.get();}@Overridepublic void withdraw(BigDecimal amout) {while (true){BigDecimal prev = ref.get();BigDecimal next = prev.subtract(amout);if (ref.compareAndSet(prev,next)){break;}}}public static void main(String[] args) {DecimalAccount.demo(new DecimalAccountTest02(new BigDecimal("10000")));}
}

在这里插入图片描述

ABA问题及解决

ABA问题

@Slf4j
public class AtomicMarkTest01 {static AtomicReference ref = new AtomicReference<>("A");public static void main(String[] args) {log.debug("main start");// 获取值A// 这个共享变量被其它线程改过吗String prev = ref.get();other();sleep(1);// 尝试改为Clog.debug("change A -> C  {}",ref.compareAndSet(prev, "C"));}public static void other(){new Thread(() -> {log.debug("change A -> B  {}",ref.compareAndSet(ref.get(), "B"));},"t1").start();sleep(0.5);new Thread(() -> {log.debug("change B -> A  {}",ref.compareAndSet(ref.get(), "A"));},"t2").start();}}

在这里插入图片描述

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

AtomicStampedReference

@Slf4j
public class AtomicStampedTest01 {static AtomicStampedReference ref = new AtomicStampedReference("A",0);public static void main(String[] args) {log.debug("main start");// 获取值AString prev = ref.getReference();// 获取版本号int stamp = ref.getStamp();other();sleep(1);// 尝试改为Clog.debug("change A -> C  {}",ref.compareAndSet(prev, "C",stamp,stamp+1));log.debug("版本号  {}",stamp);}public static void other(){new Thread(() -> {int stamp = ref.getStamp();log.debug("change A -> B  {}",ref.compareAndSet(ref.getReference(), "B", stamp,stamp+1));log.debug("版本号  {}",stamp);},"t1").start();sleep(0.5);new Thread(() -> {int stamp = ref.getStamp();log.debug("change B -> A  {}",ref.compareAndSet(ref.getReference(), "A",stamp,stamp+1));log.debug("版本号  {}",stamp);  // 获取的版本号为 0  实际版本号已经为 1 所以更改失败},"t2").start();}
}

在这里插入图片描述

  • AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,通过AtomicStampedReference,我们可以知道,引用变量被修改了几次
  • 但是有时候,并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了 AtomicMarkableReference

AtomicMarkableReference

在这里插入图片描述

@Slf4j
public class AtomicMarkableTest01 {public static void main(String[] args) throws InterruptedException {GarbageBag bag = new GarbageBag("垃圾袋满了");// true 表示垃圾袋满了AtomicMarkableReference 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);  // success如果是false,表示阿姨换过了log.debug(ref.getReference().toString());}
}// 垃圾袋
class GarbageBag{String desc;public GarbageBag(String desc){this.desc = desc;}public void setDesc(String desc){this.desc = desc;}@Overridepublic String toString() {return super.toString() + " " + desc;}
}

5.5 原子数组

  • AtomicIntegerArray
  • AtomicLongArray
  • AtomicRefenceArray

不安全的例子

@Slf4j
public class AtomicArrayUnsafeTest {public static void main(String[] args) {demo(() -> new int[10],(array) -> array.length,(array,index) -> array[index]++,array -> System.out.println(Arrays.toString(array)));}/**参数1,提供数组、可以是线程不安全数组或线程安全数组参数2,获取数组长度的方法参数3,自增方法,回传 array, index参数4,打印数组的方法*/
// supplier 提供者 无中生有 ()->结果
// function 函数 一个参数一个结果 (参数)->结果 , BiFunction (参数1,参数2)->结果
// consumer 消费者 一个参数没结果 (参数)->void, BiConsumer (参数1,参数2)->private static  void demo(Supplier arraySuppiler,Function lengthFun,BiConsumer putConsumer,Consumer printConsumer){List ts = new ArrayList<>();T array = arraySuppiler.get();Integer length = lengthFun.apply(array);for(int i = 0; i < length; i++){// 每个线程对数组做 10000 次操作ts.add(new Thread(() -> {for (int j = 0; j < 10000; j++){putConsumer.accept(array, j%length);}}));}ts.forEach(Thread::start);ts.forEach(t -> {try {t.join();} catch (InterruptedException e) {e.printStackTrace();}});  // 等待所有线程结束printConsumer.accept(array);}
}

在这里插入图片描述

使用CAS安全的例子

@Slf4j
public class AtomicArraySafeTest {public static void main(String[] args) {demo(() -> new AtomicIntegerArray(10),(array) -> array.length(),(array,index) -> array.getAndIncrement(index),array -> System.out.println(array));}/**参数1,提供数组、可以是线程不安全数组或线程安全数组参数2,获取数组长度的方法参数3,自增方法,回传 array, index参数4,打印数组的方法*/
// supplier 提供者 无中生有 ()->结果
// function 函数 一个参数一个结果 (参数)->结果 , BiFunction (参数1,参数2)->结果
// consumer 消费者 一个参数没结果 (参数)->void, BiConsumer (参数1,参数2)->private static  void demo(Supplier arraySuppiler,Function lengthFun,BiConsumer putConsumer,Consumer printConsumer){List ts = new ArrayList<>();T array = arraySuppiler.get();Integer length = lengthFun.apply(array);for(int i = 0; i < length; i++){// 每个线程对数组做 10000 次操作ts.add(new Thread(() -> {for (int j = 0; j < 10000; j++){putConsumer.accept(array, j%length);}}));}ts.forEach(Thread::start);ts.forEach(t -> {try {t.join();} catch (InterruptedException e) {e.printStackTrace();}});  // 等待所有线程结束printConsumer.accept(array);}
}

在这里插入图片描述

5.6 字段更新器

  • AtomicReferenceFieldUpdater // 域 字段
  • AtomicIntegerFieldUpdater
  • AtomicLongFieldUpdater

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

Exception in thread "main" java.lang.IllegalArgumentException: Must be volatile type
@Slf4j
public class AtomicFieldTest {private volatile int field;public static void main(String[] args) {AtomicIntegerFieldUpdater fieldUpdater =AtomicIntegerFieldUpdater.newUpdater(AtomicFieldTest.class,"field");AtomicFieldTest test = new AtomicFieldTest();fieldUpdater.compareAndSet(test, 0, 10);// 修改成功 field = 10System.out.println(test.field);// 修改成功 field = 20fieldUpdater.compareAndSet(test,10 , 20);System.out.println(test.field);// 修改失败 field = 20  因为第二个参数传的和现在的值不同fieldUpdater.compareAndSet(test,10 , 30);System.out.println(test.field);}
}

在这里插入图片描述

5.7 原子累加器

累加器性能比较

@Slf4j
public class AtomicLongAndLongAdder {public static void main(String[] args) {for (int i = 0; i < 5; i++) {demo(() -> new LongAdder(), adder -> adder.increment());}System.out.println();for (int i = 0; i < 5; i++) {demo(() -> new AtomicLong(), adder -> adder.getAndIncrement());}}private static  void demo(Supplier adderSuppiler, Consumer action){T adder = adderSuppiler.get();long start = System.nanoTime();List ts = new ArrayList<>();// 4个线程,没人累加50万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);}
}

在这里插入图片描述

  • 性能提升的原因很简单,就是在有竞争时,设置多个累加单元,Therad-0 累加 Cell[0],而 Thread-1 累加 Cell[1]… 最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性 能。
  • LongAdder在高并发的场景下会比它的前辈————AtomicLong 具有更好的性能,代价是消耗更多的内存空间

为什么引入LongAdder

AtomicLong是利用了底层的CAS操作来提供并发性的,比如addAndGet方法:

在这里插入图片描述

上述方法调用了Unsafe类的getAndAddLong方法,该方法是个native方法,它的逻辑是采用自旋的方式不断更新目标值,直到更新成功。

在并发量较低的环境下,线程冲突的概率比较小,自旋的次数不会很多。但是,高并发环境下,N个线程同时进行自旋操作,会出现大量失败并不断自旋的情况,此时AtomicLong的自旋会成为瓶颈。

这就是LongAdder引入的初衷——解决高并发环境下AtomicLong的自旋瓶颈问题。

LongAdder分析

LongAdder 是并发大师 @author Doug lea 的作品

LongAdder 类有几个关键域(这几个值都在 Striped64类中)

    /*** Table of cells. When non-null, size is a power of 2.*///  累加单元数组, 懒惰初始化transient volatile Cell[] cells;/*** Base value, used mainly when there is no contention, but also as* a fallback during table initialization races. Updated via CAS.*/// 基础值, 如果没有竞争, 则用 cas 累加这个域transient volatile long base;/*** Spinlock (locked via CAS) used when resizing and/or creating Cells.*/// 基础值, 如果没有竞争, 则用 cas 累加这个域transient volatile int cellsBusy;
  • AtomicLong中有个内部变量value保存着实际的long值,所有的操作都是针对该变量进行。也就是说,高并发环境下,value变量其实是一个热点,也就是N个线程竞争一个热点。
  • LongAdder的基本思路就是分散热点,将value值分散到一个数组中,不同线程会命中到数组的不同槽中,各个线程只对自己槽中的那个值进行CAS操作,这样热点就被分散了,冲突的概率就小很多。如果要获取真正的long值,只要将各个槽中的变量值累加返回。

在这里插入图片描述

伪共享问题

在LongAdder的父类Striped64中存在一个transient volatile Cell[] cells数组,其长度是2的幂次方,每个cell单元格都使用@sun.misc.Contended注解进行修饰,而@sun.misc.Contended注解可以进行缓冲行填充,从而解决伪共享问题。伪共享会导致缓冲行失效缓存一致性开销变大。

    // 防止缓存行伪共享@sun.misc.Contended static final class Cell {volatile long value;Cell(long x) { value = x; }// 最重要的方法, 用来 cas 方式进行累加, cmp 表示旧值, va; 表示新final boolean cas(long cmp, long val) {return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val);}// Unsafe mechanicsprivate static final sun.misc.Unsafe UNSAFE;private static final long valueOffset;static {try {UNSAFE = sun.misc.Unsafe.getUnsafe();Class ak = Cell.class;valueOffset = UNSAFE.objectFieldOffset(ak.getDeclaredField("value"));} catch (Exception e) {throw new Error(e);}}}

缓存和内存的速度比较

在这里插入图片描述

  • 因为CPU 与 内存的速度差异很大,需要靠预读数据至缓存来提升效率
  • 而缓存以缓存行为单位,每个缓存行对应着一块内存,一般是 64byte(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(long x)

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

在这里插入图片描述

    final void longAccumulate(long x, LongBinaryOperator fn,boolean wasUncontended) {int h;// 当前线程还没有对应的cell,需要随机生成一个值用来绑定到cellif ((h = getProbe()) == 0) {// 初始化probeThreadLocalRandom.current(); // force initialization// h 对应新的 probe 值, 用来对应 cellh = getProbe();wasUncontended = true;}// collide 为 true 表示扩容boolean collide = false;                // True if last slot nonemptyfor (;;) {Cell[] as; Cell a; int n; long v;// 已经有了cellsif ((as = cells) != null && (n = as.length) > 0) {// 还没有cellif ((a = as[(n - 1) & h]) == null) {// cellBusy = 0if (cellsBusy == 0) {       // Try to attach new Cell// 乐观创建Cell r = new Cell(x);   // Optimistically create// 为 cellsBusy 加锁,cell 初始累加值为 xif (cellsBusy == 0 && casCellsBusy()) {boolean created = false;try {               // Recheck under lockCell[] 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;}// 成功 break  否则 continueif (created)  break;continue;           // Slot is now non-empty}}// 扩容标记改为falsecollide = false;}// 有竞争, 改变线程对应的 cell 来重试 caselse if (!wasUncontended)       // CAS already known to failwasUncontended = true;      // Contqinue after rehash// cas 尝试累加,配合LongAccumulator不为null,配合LongAddr 为nullelse if (a.cas(v = a.value, ((fn == null) ? v + x :fn.applyAsLong(v, x))))break;// 如果cells 长度已经超过了最大程度,或者已经扩容,改变线程对应的cell来重试caselse if (n >= NCPU || cells != as)collide = false;            // At max size or stale// 确保colllide 为false 进入此分支,就不会进行下面的 扩容else if (!collide)collide = true;// 加锁else if (cellsBusy == 0 && casCellsBusy()) {// 扩容操作try {if (cells == as) {      // Expand table unless staleCell[] rs = new Cell[n << 1];for (int i = 0; i < n; ++i)rs[i] = as[i];cells = rs;}} finally {cellsBusy = 0;}collide = false;// 加锁成功continue;                   // Retry with expanded table}// 改变线程对应的 cellh = advanceProbe(h);}// 还没有cells, 尝试给 cellsBusy 加锁else if (cellsBusy == 0 && cells == as && casCellsBusy()) {// 加锁成功, 初始化 cells, 最开始长度为 2, 并填充一个 cellboolean init = false;try {                           // Initialize tableif (cells == as) {Cell[] rs = new Cell[2];rs[h & 1] = new Cell(x);cells = rs;init = true;}} finally {cellsBusy = 0;}// 成功则 break;if (init)break;}// 上两种情况失败, 尝试给 base 累加else if (casBase(v = base, ((fn == null) ? v + x :fn.applyAsLong(v, x))))break;                          // Fall back on using base}}
  • longAccumulate 流程图

在这里插入图片描述

在这里插入图片描述

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

在这里插入图片描述

    public long sum() {Cell[] as = cells; Cell a;// 基值 没创建数组时用long sum = base;// as 不为空if (as != null) {for (int i = 0; i < as.length; ++i) {if ((a = as[i]) != null)sum += a.value;  // 将值都加起来}}// 返回return sum;}

5.8 Unsafe

1 概述

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

public class MyUnsafe {static Unsafe unsafe;static {try {Field myUnsafe = Unsafe.class.getDeclaredField("theUnsafe");myUnsafe.setAccessible(true);unsafe = (Unsafe) myUnsafe.get(null);} catch (NoSuchFieldException | IllegalAccessException e) {e.printStackTrace();}}static Unsafe getUnsafe(){return unsafe;}
}

2 Unsafe CAS 操作

@Data
public class Student {volatile int id;volatile String name;public static void main(String[] args) throws Exception {Unsafe unsafe = MyUnsafe.getUnsafe();Field id = Student.class.getDeclaredField("id");Field name = Student.class.getDeclaredField("name");// 获得成员变量的偏移量long idOffset = MyUnsafe.unsafe.objectFieldOffset(id);long nameOffset = MyUnsafe.unsafe.objectFieldOffset(name);Student student = new Student();// 使用 cas 方法替换成员变量的值MyUnsafe.unsafe.compareAndSwapInt(student, idOffset, 0, 20); // 返回 trueMyUnsafe.unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 返回 trueSystem.out.println(student);}
}

在这里插入图片描述

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

public class AtomicData {private volatile int data;static final Unsafe unsafe;static final long DATA_OFFSET;static {unsafe = MyUnsafe.getUnsafe();try {// data 属性在 DataContainer 对象中的偏移量,用于 Unsafe 直接访问该属性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) {// 获取共享变量旧值,可以在这一行加入断点,修改 data 调试来加深理解oldValue = data;// cas 尝试修改 data 为 旧值 + amount,如果期间旧值被别的线程改了,返回 falseif (unsafe.compareAndSwapInt(this, DATA_OFFSET, oldValue, oldValue - amount)) {return;}}}public int getData() {return data;}public static void main(String[] args) {Account.demo(new Account() {AtomicData atomicData = new AtomicData(10000);@Overridepublic Integer getBalance() {return atomicData.getData();}@Overridepublic void withdraw(Integer amount) {atomicData.decrease(amount);}});}
}

在这里插入图片描述

相关内容

热门资讯

宽基ETF被抢筹,市场风格走向... 近期,股票市场震荡加剧,宽基类ETF(交易型开放式指数基金)的成交明显放量。截至12月17日,近一个...
价值10万的皮肤“到手价”仅6... 近日,围绕腾讯手游《金铲铲之战》(下称《金铲铲》)新赛季核心活动“不朽传奇召唤”的重大规则失误,一场...
成本3元卖60元,“99%高纯... 宣传“99%高纯”的产品,实测核心成分含量竟为0?近期,北京同仁堂一款南极磷虾油被质疑虚假宣传,在舆...
深夜,全线狂飙!美联储,突传重... 美股全线反攻!今晚,美股三大指数集体高开,纳指、标普500指数均大涨超1%,芯片股全线大涨,美光科技...
国盾量子公告:公司董事长吕品不... 科大国盾量子技术股份有限公司(以下简称“公司”)董事会沉痛公告,公司董事长吕品先生不幸逝世。吕品先生...
芯原股份弃“芯来”追“逐点” ... 中经记者 顾梦轩 李正豪 广州、北京报道虽然终止收购芯来智融,但芯原股份(688521.SH)收购逐...
国盾量子董事长意外离世,警方通... 12月18日晚间,国盾量子发布公告,公司董事长吕品不幸逝世。吕品于2025年5月起担任公司董事长,并...
开源中国马越:除了DeepSe... “靠烧钱做to B市场的时代一去不复返了。”文|《中国企业家》记者 闫俊文编辑|何伊凡见习编辑|李原...
“白酒第二”不稳,业绩被汾酒反... 出品|达摩财经12月18日,以“新形势 新机遇 新征程”为主题的五粮液第二十九届“12·18”共识共...
康师傅更换CEO,创始人之子将... 红星资本局12月18日消息,今日,康师傅(康师傅控股,0322.HK)公告称,原首席执行官陈应让已决...