共享模型之无锁
问题提出 有如下需求,保证 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 public class TestCAS { public static void main (String[] args) { Account.demo(new AccountUnsafe (10000 )); } } 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" ); } } class AccountUnsafe implements Account { private Integer balance; public AccountUnsafe (Integer balance) { this .balance = balance; } @Override public Integer getBalance () { return balance; } @Override public void withdraw (Integer amount) { balance -= amount; } }
为什么不安全 执行withdraw 方法对应的字节码:
1 2 3 4 5 6 7 8 9 ALOAD 0 ALOAD 0 GETFIELD com/heu/AccountUnsafe.balance : Ljava/lang/Integer; INVOKEVIRTUAL java/lang/Integer.intValue ()I ALOAD 1 INVOKEVIRTUAL java/lang/Integer.intValue ()I ISUB INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer; PUTFIELD com/heu/AccountUnsafe.balance : Ljava/lang/Integer;
单核的指令交错
多核的指令交错
解决思路-锁 首先想到的是给 Account 对象加锁:
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 synchronized Integer getBalance () { return balance; } @Override public synchronized void withdraw (Integer amount) { balance -= amount; } }
如上代码加锁会造成线程堵塞,堵塞的时间取决于临界区代码执行的时间,这使用加锁的性能不高,因此可以使用无锁来解决此问题。
解决思路-无锁 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 class AccountUnsafe implements Account { AtomicInteger atomicInteger; public AccountUnsafe (Integer balance) { this .atomicInteger = new AtomicInteger (balance); } @Override public Integer getBalance () { return atomicInteger.get(); } @Override public void withdraw (Integer amount) { while (true ) { Integer pre = getBalance(); int next = pre - amount; if (atomicInteger.compareAndSet(pre, next)) { break ; } } } }
CAS与volatile 工作方式 前面的AtomicInteger的解决方法,内部并没有用锁来保护共享变量的线程安全。那么它是如何实现的?
1 2 3 4 5 6 7 8 9 public void withdraw (Integer amount) { while (true ){ int prev = balance.get(); int next = prev - amount; if (balance.compareAndSet(prev,next)){ break ; } } }
其中的关键是compareAndSet,它的简称就是CAS(也有Compare And Swap的说法),它必须是原子操作。
volatile 获取共享变量时,为了保证该变量的可见性,需要使用volatile修饰。
它可以用来修饰成员变量和静态成员变量,它可以避免线程从自己的工作缓存中查找变量的值,必须到主存中获取它的值,线程操作volatile变量都是直接操作主存,即一个线程对volatile变量的修改,对另一个线程可见。
注意:volatile仅仅保证了共享变量的可见性,让其它线程能够看到最新值,但不能解决指令交错问题(不能保证原子性)。
CAS必须借助volatile才能读取到共享变量的最新值来实现比较并交换的效果。
为什么无锁效率高
无锁情况下,即使重试失败,线程始终在高速运行,没有停歇,而 synchronized 会让线程在没有获得锁的时候,发生上下文切换,进入阻塞。
打个比喻:线程就好像高速跑道上的赛车,高速运行时,速度超快,一旦发生上下文切换,就好比赛车要减速、熄火,等被唤醒又得重新打火、启动、加速… 恢复到高速运行,代价比较大。
但无锁情况下,因为线程要保持运行,需要额外 CPU 的支持,CPU 在这里就好比高速跑道,没有额外的跑道,线程想高速运行也无从谈起,虽然不会进入阻塞,但由于没有分到时间片,仍然会进入可运行状态,还是会导致上下文切换。
CAS的特点 结合 CAS 和 volatile 可以实现无锁并发,适用于线程数少、多核 CPU 的场景下。
CAS 是基于乐观锁的思想:最乐观的估计,不怕别的线程来修改共享变量,就算改了也没关系,吃亏点再重试呗。
synchronized 是基于悲观锁的思想:最悲观的估计,得防着其它线程来修改共享变量,我上了锁你们都别想改,我改完了解开锁,你们才有机会。
CAS 体现的是无锁并发、无阻塞并发,请仔细体会这两句话的意思。
因为没有使用 synchronized,所以线程不会陷入阻塞,这是效率提升的因素之一。
但如果竞争激烈(写操作多),可以想到重试必然频繁发生,反而效率会受影响。
原子整数 java.util.concurrent.atomic 并发包提供了一些并发工具类,这里把它分成五类,分别是:
原子类
AtomicInteger:整型原子类
AtomicLong:长整型原子类
AtomicBoolean:布尔型原子类
原子引用
原子数组
字段更新器
原子累加器
以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 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)); }
原子引用 为什么需要原子引用类型
保证引用类型的共享变量是线程安全的(确保这个原子引用没有引用过别人)。基本类型原子类只能更新一个变量,如果需要原子更新多个变量,需要使用引用类型原子类。
AtomicReference
AtomicMarkableReference
AtomicStampedReference
如下方法
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); } }
当执行 withdraw 方法时,可能会有线程安全问题,我们可以加锁解决或者是使用无锁的方式 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 DecimalAccountCas implements DecimalAccount { private 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 preVal = balance.get(); BigDecimal nextVal = preVal.subtract(amount); if (balance.compareAndSet(preVal, nextVal)) { break ; } } } }
ABA问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public static AtomicReference<String> ref = new AtomicReference <>("A" ); public static void main (String[] args) throws InterruptedException { log.debug("main start..." ); String preVal = ref.get(); other(); TimeUnit.SECONDS.sleep(1 ); log.debug("change A->C {}" , ref.compareAndSet(preVal, "C" )); } private static void other () throws InterruptedException { new Thread (() -> { log.debug("change A->B {}" , ref.compareAndSet(ref.get(), "B" )); }, "t1" ).start(); TimeUnit.SECONDS.sleep(1 ); new Thread (() -> { log.debug("change B->A {}" , ref.compareAndSet(ref.get(), "A" )); }, "t2" ).start(); }
主线程仅能判断出共享变量的值与最初值 A 是否相同,不能感知到这种从 A 改为 B 又改回 A 的情况,如果主线程希望只要有其它线程【动过了】共享变量,那么自己的 cas 就算失败的话,这时,仅比较值是不够的,需要再加一个版本号。使用AtomicStampedReference来解决。
AtomicStampedReference
使用 AtomicStampedReference 加 stamp (版本号或者时间戳)的方式解决 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 public class TestAtomicStampedReference { public static AtomicStampedReference<String> ref = new AtomicStampedReference <>("A" , 0 ); public static void main (String[] args) throws InterruptedException { log.debug("main start..." ); String preVal = ref.getReference(); int stamp = ref.getStamp(); log.info("main 拿到的版本号 {}" ,stamp); other(); TimeUnit.SECONDS.sleep(1 ); log.info("修改后的版本号 {}" ,ref.getStamp()); log.info("change A->C:{}" , ref.compareAndSet(preVal, "C" , stamp, stamp + 1 )); } private static void other () throws InterruptedException { new Thread (() -> { int stamp = ref.getStamp(); log.info("{}" ,stamp); log.info("change A->B:{}" , ref.compareAndSet(ref.getReference(), "B" , stamp, stamp + 1 )); }).start(); TimeUnit.SECONDS.sleep(1 ); new Thread (() -> { int stamp = ref.getStamp(); log.info("{}" ,stamp); log.debug("change B->A:{}" , ref.compareAndSet(ref.getReference(), "A" ,stamp,stamp + 1 )); }).start(); } }
输出:
1 2 3 4 5 6 7 16 :48 :22.772 [main] DEBUG com.heu.test.TestAtomicStampedReference - main start...16 :48 :22.782 [main] INFO com.heu.test.TestAtomicStampedReference - main 拿到的版本号 0 16 :48 :22.788 [Thread-0 ] INFO com.heu.test.TestAtomicStampedReference - 0 16 :48 :22.788 [Thread-0 ] INFO com.heu.test.TestAtomicStampedReference - change A->B:true 16 :48 :23.792 [Thread-1 ] INFO com.heu.test.TestAtomicStampedReference - 1 16 :48 :23.792 [Thread-1 ] DEBUG com.heu.test.TestAtomicStampedReference - change B->A:true 16 :48 :24.793 [main] INFO com.heu.test.TestAtomicStampedReference - 修改后的版本号 2
AtomicMarkableReference
AtomicStampedReference 可以给原子引用加上版本号,追踪原子引用整个的变化过程,如:A -> B -> A ->C,通过AtomicStampedReference可以知道,引用变量中途被更改了几次。但是有时候,并不关心引用变量更改了几次,只是单纯的关心是否更改过,所以就有了AtomicMarkableReference 。
原子数组 使用原子的方式更新数组里的某个元素:
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 public class TestAtomicIntegerArray { 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) { ArrayList<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 7 1 2 3 [9470, 9579, 9616, 9594, 9566, 9633, 9605, 9611, 9892, 9879] [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000]
字段更新器
AtomicReferenceFieldUpdater // 域 字段
AtomicIntegerFieldUpdater
AtomicLongFieldUpdater
利用字段更新器,可以针对对象的某个域(Field)进行原子操作,只能配合 volatile 修饰的字段使用,否则会出现异常。
1 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 public class TestFieldUpdater { private volatile int field; public static void main (String[] args) { AtomicIntegerFieldUpdater<TestFieldUpdater> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(TestFieldUpdater.class, "field" ); TestFieldUpdater updater = new TestFieldUpdater (); fieldUpdater.compareAndSet(updater, 0 , 10 ); System.out.println(updater.field); fieldUpdater.compareAndSet(updater, 10 , 20 ); System.out.println(updater.field); fieldUpdater.compareAndSet(updater, 10 , 30 ); System.out.println(updater.field); }
输出:
原子累加器 AtomicLong Vs LongAdder
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 public class TestLongAdder { public static void main (String[] args) { for (int i = 0 ; i < 5 ; i++) { demo(()->new AtomicLong (0 ),(ref)->ref.getAndIncrement()); } for (int i = 0 ; i < 5 ; i++) { demo(()->new LongAdder (),(ref)->ref.increment()); } } private static <T> void demo (Supplier<T> supplier, Consumer<T> consumer) { ArrayList<Thread> list = new ArrayList <>(); T adder = supplier.get(); for (int i = 0 ; i < 4 ; i++) { list.add(new Thread (() -> { for (int j = 0 ; j < 500000 ; j++) { consumer.accept(adder); } })); } long start = System.nanoTime(); list.forEach(t -> t.start()); list.forEach(t -> { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); long end = System.nanoTime(); System.out.println(adder + " cost:" + (end - start)/1000_000 ); } }
输出:
1 2 3 4 5 6 7 8 9 10 2000000 cost:80 2000000 cost:76 2000000 cost:60 2000000 cost:56 2000000 cost:52 2000000 cost:32 2000000 cost:5 2000000 cost:8 2000000 cost:8 2000000 cost:20
结论:
执行代码后,发现使用 LongAdder 比 AtomicLong 快2,3倍,使用 LongAdder 性能提升的原因很简单,就是在有竞争时,设置多个累加单元(但不会超过cpu的核心数),Therad-0 累加 Cell[0],而 Thread-1 累加Cell[1]… 最后将结果汇总。这样它们在累加时操作的不同的 Cell 变量,因此减少了 CAS 重试失败,从而提高性能。
CAS锁 使用 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 41 42 43 44 45 public class TestLockCas { public 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 ); } public static void main (String[] args) { Code_13_LockCas lock = new Code_13_LockCas (); new Thread (() -> { log.info("begin..." ); lock.lock(); try { log.info("上锁成功" ); TimeUnit.SECONDS.sleep(1 ); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }, "t1" ).start(); new Thread (() -> { log.info("begin..." ); lock.lock(); try { log.info("上锁成功" ); TimeUnit.SECONDS.sleep(1 ); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }, "t2" ).start(); } }
LongAdder原理 LongAdder 类有几个关键域,在public class LongAdder extends Striped64 implements Serializable {},下面的变量属于 Striped64 被 LongAdder 继承:
1 2 3 4 5 6 transient volatile Cell[] cells;transient volatile long base;transient volatile int cellsBusy;
原理之伪共享 其中 Cell 即为累加单元。
1 2 3 4 5 6 7 8 9 10 11 @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); } }
要想讨论 @sun.misc.Contended 注解的重要意义得从缓存说起,缓存与内存的速度比较
因为 CPU 与 内存的速度差异很大,需要靠预读数据至缓存来提升效率。缓存离 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 将对象预读至缓存时占用不同的缓存行,这样,不会造成对方缓存行的失效。
add 方法分析 LongAdder 进行累加操作是调用 increment 方法,它又调用 add 方法。
1 2 3 public void increment () { add(1L ); }
第一步: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 26 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); } } }
第二步: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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 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 ) { if (cellsBusy == 0 ) { Cell r = new Cell (x); if (cellsBusy == 0 && casCellsBusy()) { boolean created = false ; try { Cell[] 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 ; } if (created) break ; continue ; } } 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()) { boolean init = false ; try { if (cells == as) { Cell[] rs = new Cell [2 ]; rs[h & 1 ] = new Cell (x); cells = rs; init = true ; } } finally { cellsBusy = 0 ; } if (init) break ; } else if (casBase(v = base, ((fn == null ) ? v + x : fn.applyAsLong(v, x)))) break ; } }
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 对象不能直接调用,只能通过反射获得。LockSupport 的 park 方法,CAS 相关的方法底层都是通过Unsafe类来实现的。
1 2 3 4 5 6 7 public static void main (String[] args) throws NoSuchFieldException, IllegalAccessException { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe" ); theUnsafe.setAccessible(true ); Unsafe unsafe = (Unsafe)theUnsafe.get(null ); }
Unsafe 模拟实现 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 public class UnsafeTest { public static void main (String[] args) throws NoSuchFieldException, IllegalAccessException { Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe" ); theUnsafe.setAccessible(true ); Unsafe unsafe = (Unsafe)theUnsafe.get(null ); long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id" )); long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name" )); Teacher teacher = new Teacher (); unsafe.compareAndSwapLong(teacher, idOffset, 0 , 100 ); unsafe.compareAndSwapObject(teacher, nameOffset, null , "lisi" ); System.out.println(teacher); } } @Data class Teacher { private volatile int id; private volatile String name; }
Unsafe 模拟实现原子整数 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 public class UnsafeAccessor { public static void main (String[] args) { Account.demo(new MyAtomicInteger (10000 )); } } class MyAtomicInteger implements Account { private volatile Integer value; private static final Unsafe UNSAFE = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = UNSAFE.objectFieldOffset (AtomicInteger.class.getDeclaredField("value" )); } catch (Exception ex) { throw new Error (ex); } } public MyAtomicInteger (Integer value) { this .value = value; } public Integer get () { return value; } public void decrement (Integer amount) { while (true ) { Integer preVal = this .value; Integer nextVal = preVal - amount; if (UNSAFE.compareAndSwapObject(this , valueOffset, preVal, nextVal)) { break ; } } } @Override public Integer getBalance () { return get(); } @Override public void withdraw (Integer amount) { decrement(amount); } }