问题提出 (如何保证取款方法的线程安全) 有如下需求,保证 account.withdraw
取款方法的线程安全
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 import java.util.ArrayList;import java.util.List;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::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" ); } }
原有实现并不是线程安全的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class AccountUnsafe implements Account { private Integer balance; public AccountUnsafe (Integer balance) { this .balance = balance; } @Override public Integer getBalance () { return this .balance; } @Override public void withdraw (Integer amount) { this .balance -= amount; } }
执行测试代码
1 2 3 public static void main (String[] args) { Account.demo(new AccountUnsafe (10000 )); }
某次的执行结果 330 cost: 306 ms
为什么不安全 withdraw 方法
1 2 3 public void withdraw (Integer amount) { balance -= amount; }
对应的字节码
多线程执行流程
解决思路-synchronized锁 首先想到的是给 Account 对象加锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class AccountUnsafe implements Account { private Integer balance; public AccountUnsafe (Integer balance) { this .balance = balance; } @Override public synchronized Integer getBalance () { return balance; } @Override public synchronized void withdraw (Integer amount) { balance -= amount; } }
结果为 0 cost: 399 ms
解决思路-无锁(AtomicInteger) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class AccountSafe implements Account { private AtomicInteger balance; public AccountSafe (Integer 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 ; } } } }
执行测试代码
1 2 3 public static void main (String[] args) { Account.demo(new AccountSafe (10000 )); }
某次的执行结果
CAS 与 volatile 前面看到的 AtomicInteger
的解决方法,内部并没有用锁来保护共享变量的线程安全。那么它是如何实现的呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public void withdraw (Integer amount) { while (true ) { while (true ) { int prev = balance.get(); int next = prev - amount; if (balance.compareAndSet(prev, next)) { break ; } } } }
其中的关键是 compareAndSet,它的简称就是 CAS (也有 Compare And Swap 的说法),它必须是原子操作。
注意
其实 CAS 的底层是 lock cmpxchg
指令(X86 架构),在单核 CPU 和多核 CPU 下都能够保证【比较-交换】的原子性。
在多核状态下,某个核执行到带 lock 的指令时,CPU 会让总线锁住,当这个核把此指令执行完毕,再开启总线。这个过程中不会被线程的调度机制所打断,保证了多个线程对内存操作的准确性,是原子的。
volatile 获取共享变量时,为了保证该变量的可见性,需要使用 volatile 修饰。
它可以用来修饰成员变量和静态成员变量,他可以避免线程从自己的工作缓存中查找变量的值,必须到主存中获取它的值,线程操作 volatile 变量都是直接操作主存。即一个线程对 volatile 变量的修改,对另一个线程可见。
注意
volatile 仅仅保证了共享变量的可见性,让其它线程能够看到最新值,但不能解决指令交错问题(不能保证原子性)
CAS 必须借助 volatile 才能读取到共享变量的最新值来实现【比较并交换】的效果
为什么(相对而言)无锁效率高 synchronized 和 cas 没有绝对的谁效率高,要看所处的场景
无锁情况下,即使重试失败,线程始终在高速运行,没有停歇,而 synchronized 会让线程在没有获得锁的时候,发生上下文切换,进入阻塞。
打个比喻:线程就好像高速跑道上的赛车,高速运行时,速度超快,一旦发生上下文切换,就好比赛车要减速、熄火,等被唤醒又得重新打火、启动、加速… 恢复到高速运行,代价比较大。
但无锁情况下,因为线程要保持运行,需要额外 CPU 的支持,CPU 在这里就好比高速跑道,没有额外的跑道,线程想高速运行也无从谈起,虽然不会进入阻塞,但由于没有分到时间片,仍然会进入可运行状态,还是会导致上下文切换。
CAS 的特点 结合 CAS 和 volatile 可以实现无锁并发,适用于线程数少、多核 CPU 的场景下。
CAS 是基于乐观锁的思想 :最乐观的估计,不怕别的线程来修改共享变量,就算改了也没关系,我吃亏点再重试呗。
synchronized 是基于悲观锁的思想 :最悲观的估计,得防着其它线程来修改共享变量,我上了锁你们都别想改,我改完了解开锁,你们才有机会。
CAS 体现的是无锁并发、无阻塞并发 ,请仔细体会这两句话的意思
原子整数 J.U.C 并发包提供了:
AtomicBoolean
AtomicInteger
AtomicLong
以 AtomicInteger 为例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 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 )); public static int updateAndGet (AtomicInteger i, IntUnaryOperator operator) { while (true ) { int prev = i.get(); int next = operator.applyAsInt(prev); if (i.compareAndSet(prev, next)) { return next; } } } System.out.println(i.getAndAccumulate(10 , (p, x) -> p + x)); System.out.println(i.accumulateAndGet(-10 , (p, x) -> p + x));
原子引用 AtomicXXXReference 为什么需要原子引用类型?
AtomicReference
AtomicMarkableReference
AtomicStampedReference
有如下方法
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 public 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()); } }
试着提供不同的 DecimalAccount 实现,实现安全的取款操作
不安全实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class DecimalAccountUnsafe implements DecimalAccount { BigDecimal balance; public DecimalAccountUnsafe (BigDecimal balance) { this .balance = balance; } @Override public BigDecimal getBalance () { return this .balance; } @Override public void withdraw (BigDecimal amount) { BigDecimal balance = this .getBalance(); this .balance = balance.subtract(amount); } }
安全实现-使用锁 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class DecimalAccountSafeLock implements DecimalAccount { private final Object lock = new Object (); BigDecimal balance; public DecimalAccountSafeLock (BigDecimal balance) { this .balance = balance; } @Override public BigDecimal getBalance () { return balance; } @Override public void withdraw (BigDecimal amount) { synchronized (lock) { BigDecimal balance = this .getBalance(); this .balance = balance.subtract(amount); } } }
安全实现-使用 CAS AtomicReference 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class DecimalAccountSafeCas implements DecimalAccount { private AtomicReference<BigDecimal> ref; public DecimalAccountSafeCas (BigDecimal balance) { ref = new AtomicReference <>(balance); } @Override public BigDecimal getBalance () { return ref.get(); } @Override public void withdraw (BigDecimal amount) { while (true ) { BigDecimal prev = ref.get(); BigDecimal next = prev.subtract(amount); if (ref.compareAndSet(prev, next)) { break ; } } } }
测试代码
1 2 3 4 5 public static void main (String[] args) { DecimalAccount.demo(new DecimalAccountUnsafe (new BigDecimal ("10000" ))); DecimalAccount.demo(new DecimalAccountSafeLock (new BigDecimal ("10000" ))); DecimalAccount.demo(new DecimalAccountSafeCas (new BigDecimal ("10000" ))); }
运行结果
1 2 3 4310 cost: 425 ms 0 cost: 285 ms 0 cost: 274 ms
ABA 问题及解决 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 static AtomicReference<String> ref = new AtomicReference <>("A" );public static void main (String[] args) throws InterruptedException { log.debug("main start..." ); String prev = ref.get(); other(); sleep(1 ); log.debug("change A->C {}" , ref.compareAndSet(prev, "C" )); } private 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(); }
输出
1 2 3 4 11 :29 :52.325 c.Test36 [main] - main start... 11 :29 :52.379 c.Test36 [t1] - change A->B true 11 :29 :52.879 c.Test36 [t2] - change B->A true 11 :29 :53.880 c.Test36 [main] - change A->C true
主线程仅能判断出共享变量的值与最初值 A 是否相同,不能感知到这种从 A 改为 B 又 改回 A 的情况
如果主线程希望: 只要有其它线程【动过了】共享变量,那么自己的 cas 就算失败,这时,仅比较值是不够的,需要再加一个版本号
AtomicStampedReference(维护版本号) 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 @Slf4j(topic = "c.Test") public class Test { static AtomicStampedReference<String> ref = new AtomicStampedReference <>("A" , 0 ); public static void main (String[] args) throws InterruptedException { log.debug("main start..." ); String prev = ref.getReference(); int stamp = ref.getStamp(); log.debug("版本 {}" , stamp); other(); sleep(1 ); log.debug("change A->C {}" , ref.compareAndSet(prev, "C" , stamp, stamp + 1 )); } private static void other () { new Thread (() -> { log.debug("change A->B {}" , ref.compareAndSet(ref.getReference(), "B" , ref.getStamp(), ref.getStamp() + 1 )); log.debug("更新版本为 {}" , ref.getStamp()); }, "t1" ).start(); sleep(0.5 ); new Thread (() -> { log.debug("change B->A {}" , ref.compareAndSet(ref.getReference(), "A" , ref.getStamp(), ref.getStamp() + 1 )); log.debug("更新版本为 {}" , ref.getStamp()); }, "t2" ).start(); } }
输出为
1 2 3 4 5 6 7 13 :01 :20.968 c.Test36 [main] - main start...13 :01 :20.970 c.Test36 [main] - 版本 0 13 :01 :21.002 c.Test36 [t1] - change A->B true 13 :01 :21.003 c.Test36 [t1] - 更新版本为 1 13 :01 :21.513 c.Test36 [t2] - change B->A true 13 :01 :21.513 c.Test36 [t2] - 更新版本为 2 13 :01 :22.523 c.Test36 [main] - change A->C false
AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,如: A -> B -> A -> C
,通过AtomicStampedReference,我们可以知道,引用变量中途被更改了几次。
但是有时候,并不关心引用变量更改了几次,只是单纯的关心是否更改过 ,所以就有了 AtomicMarkableReference
AtomicMarkableReference(仅维护是否修改过) 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 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; } } @Slf4j 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()); } }
输出
1 2 3 4 5 6 7 13 :06 :08.896 c.Test38 [main] - start...13 :06 :08.899 c.Test38 [main] - cn.itcast.test.GarbageBag@6aceb1a5 装满了垃圾13 :06 :09.001 c.Test38 [保洁阿姨] - start...13 :06 :09.001 c.Test38 [保洁阿姨] - cn.itcast.test.GarbageBag@6aceb1a5 空垃圾袋13 :06 :10.014 c.Test38 [main] - 想换一只新垃圾袋?13 :06 :10.014 c.Test38 [main] - 换了么?false 13 :06 :10.014 c.Test38 [main] - cn.itcast.test.GarbageBag@6aceb1a5 空垃圾袋
可以注释掉打扫卫生线程代码,再观察输出
常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 public AtomicMarkableReference (V initialRef, boolean initialMark) public V getReference () public int isMarked () public V get (boolean [] markHolder) public boolean weakCompareAndSet (V expectedReference, V newReference, boolean expectedMark, boolean newMark) public boolean compareAndSet (V expectedReference, V newReference, boolean expectedMark, boolean newMark) public void set (V newReference, boolean newMark) public boolean attemptMark (V expectedReference, boolean newMark) private boolean casPair (Pair<V> cmp, Pair<V> val)
原子数组
AtomicIntegerArray
AtomicLongArray
AtomicReferenceArray
有如下方法
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 public class Test39 { public static void main (String[] args) { demo( ()->new int [10 ], (array)->array.length, (array, index) -> array[index]++, array-> System.out.println(Arrays.toString(array)) ); demo( ()-> new AtomicIntegerArray (10 ), (array) -> array.length(), (array, index) -> array.getAndIncrement(index), array -> System.out.println(array) ); } private static <T> void demo ( Supplier<T> arraySupplier, Function<T, Integer> lengthFun, BiConsumer<T, Integer> putConsumer, Consumer<T> printConsumer ) { 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); } }
不安全的数组 1 2 3 4 5 6 demo( ()->new int [10 ], (array)->array.length, (array, index) -> array[index]++, array-> System.out.println(Arrays.toString(array)) );
结果 [9870, 9862, 9774, 9697, 9683, 9678, 9679, 9668, 9680, 9698]
安全的数组AtomicIntegerArray 1 2 3 4 5 6 demo( ()-> new AtomicIntegerArray (10 ), (array) -> array.length(), (array, index) -> array.getAndIncrement(index), array -> System.out.println(array) );
结果 [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]
字段原子更新器 AtomicXXXFieldUpdater
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 @Slf4j(topic = "c.Test40") public class Test40 { 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(stu); } } class Student { volatile String name; @Override public String toString () { return "Student{" + "name='" + name + '\'' + '}' ; } }
输出
原子累加器 累加器性能比较 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 public class Test41 { public static void main (String[] args) { for (int i = 0 ; i < 5 ; i++) { demo( () -> new AtomicLong (0 ), (adder) -> adder.getAndIncrement() ); } 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(); List<Thread> ts = new ArrayList <>(); for (int i = 0 ; i < 4 ; i++) { ts.add(new Thread (() -> { for (int j = 0 ; j < 500000 ; j++) { action.accept(adder); } })); } long start = System.nanoTime(); 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 与 LongAdder
输出
1 2 3 4 5 6 7 8 9 10 11 12 2000000 cost:35 2000000 cost:31 2000000 cost:32 2000000 cost:23 2000000 cost:28 2000000 cost:15 2000000 cost:13 2000000 cost:4 2000000 cost:7 2000000 cost:5
性能提升的原因很简单,就是 LongAdder 在有竞争时,设置多个累加单元,Therad-0 累加 Cell[0],而 Thread-1 累加Cell[1]… 最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性能。
源码之 LongAdder LongAdder 是并发大师 @author Doug Lea (大哥李)的作品,设计的非常精巧
LongAdder 类有几个关键域
1 2 3 4 5 6 7 8 transient volatile Cell[] cells;transient volatile long base;transient volatile int cellsBusy;
(cellsBusy作为) cas 锁(实现示例) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public class LockCas { private AtomicInteger state = new AtomicInteger (0 ); public void lock () { while (true ) { if (state.compareAndSet(0 , 1 )) { break ; } } } public void unlock () { log.debug("unlock..." ); state.set(0 ); } }
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 LockCas lock = new LockCas ();new Thread (() -> { log.debug("begin..." ); lock.lock(); try { log.debug("lock..." ); sleep(1 ); } finally { lock.unlock(); } }).start(); new Thread (() -> { log.debug("begin..." ); lock.lock(); try { log.debug("lock..." ); } finally { lock.unlock(); } }).start();
输出
1 2 3 4 5 6 18 :27 :07.198 c.Test42 [Thread-0 ] - begin... 18 :27 :07.202 c.Test42 [Thread-0 ] - lock... 18 :27 :07.198 c.Test42 [Thread-1 ] - begin... 18 :27 :08.204 c.Test42 [Thread-0 ] - unlock... 18 :27 :08.204 c.Test42 [Thread-1 ] - lock... 18 :27 :08.204 c.Test42 [Thread-1 ] - unlock...
原理之伪共享 为了提高读取速度,每个 CPU 有自己的缓存,CPU 读取数据后会存到自己的缓存里。而且为了节省空间,一个缓存行可能存储着多个变量,即伪共享 。但是这对于共享变量,会造成性能问题:
当一个 CPU 要修改某共享变量 A 时会先锁定 自己缓存里 A 所在的缓存行,并且把其他 CPU 缓存上相关的缓存行设置为无效 。但如果被锁定或失效的缓存行里,还存储了其他不相干的变量 B,其他线程此时就访问不了 B,或者由于缓存行失效需要重新从内存中读取加载到缓存里,这就造成了开销 。所以让共享变量 A 单独使用一个缓存行就不会影响到其他线程的访问。
Cell 需要防止防止缓存行伪共享问题 其中 Cell 即为累加单元
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 @sun .misc.Contendedstatic final class Cell { volatile long value; Cell(long x) { value = x; } final boolean cas (long prev, long next) { return UNSAFE.compareAndSwapLong(this , valueOffset, prev, next); } }
关于缓存行伪共享问题 得从缓存说起
缓存与内存的速度比较
因为 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 的缓存行失效 ;
同理 Core-1修改Cell[1]也会让 Core-0 的缓存行失效.
解决方法: @sun.misc.Contended @sun.misc.Contended
用来解决这个问题,它的原理是在使用此注解的对象或字段的前后各增加 128 字节大小的padding,从而让 CPU 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效 (JVM 添加 -XX:-RestrictContended 参数后 @sun.misc.Contended 注解才有效)
add 源码 累加主要调用下面的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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); } } }
add 流程图
longAccumulate源码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 流程图
每个线程刚进入 longAccumulate 时,会尝试对应一个 cell 对象(找到一个坑位)
sum源码 获取最终结果通过 sum 方法
1 2 3 4 5 6 7 8 9 10 11 public long sum () { Cell[] as = cells; Cell a; long sum = base; if (as != null ) { for (int i = 0 ; i < as.length; ++i) { if ((a = as[i]) != null ) sum += a.value; } } return sum; }
(底层类) Unsafe 取名 Unsafe 并不是说该类不安全,而是因为该类直接操作内存,比较复杂,意在告诉程序员使用该类有较大风险
概述 Unsafe 对象提供了非常底层的,操作内存、线程的方法,Unsafe 对象不能直接调用,只能通过反射获得
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class UnsafeAccessor { static Unsafe unsafe; static { try { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe" ); theUnsafe.setAccessible(true ); unsafe = (Unsafe) theUnsafe.get(null ); } catch (NoSuchFieldException | IllegalAccessException e) { throw new Error (e); } } static Unsafe getUnsafe () { return unsafe; } }
Unsafe CAS 操作 unsafe.compareAndSwapXXX 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 import lombok.Data;import sun.misc.Unsafe;import java.lang.reflect.Field;public class TestUnsafeCAS { public static void main (String[] args) throws NoSuchFieldException, IllegalAccessException { Unsafe unsafe = UnsafeAccessor.getUnsafe(); System.out.println(unsafe); long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id" )); long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name" )); Teacher t = new Teacher (); System.out.println(t); unsafe.compareAndSwapInt(t, idOffset, 0 , 1 ); unsafe.compareAndSwapObject(t, nameOffset, null , "张三" ); System.out.println(t); } } @Data class Teacher { volatile int id; volatile String name; }
输出
1 2 3 sun.misc.Unsafe@77556fd Teacher (id=0 , name=null ) Teacher(id=1 , name=张三)
模拟实现原子整数 使用自定义的 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 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 12 13 14 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); } });
本章小结
CAS 与 volatile
API
原子整数
原子引用
原子数组
字段更新器
原子累加器
Unsafe
原理方面