JUC并发编程共享模型之无锁(五)

5.1 问题引出

public interface Account {
    // 获取余额
    Integer getBalance();

    void withdraw(Integer amount);

    /**
     * 方法内会启动1000个线程,每个线程做-10元的操作
     * 如果初始余额为 10000 那么正确的结果应当是0
     */
    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)/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;
    }

    @Override
    public Integer getBalance() {
        return balance;
    }

    @Override
    public 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;
    }

    @Override
    public Integer getBalance() {
        return balance;
    }

    @Override
    public 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);
    }

    @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;
            }
        }
        // 可以简化为下面的方法
        // balance.addAndGet(-1 * amount);
    }
}

在这里插入图片描述

5.2 CAS 与 volatile

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

    public void withdraw(Integer amount) {
        // 需要不断尝试,直到成功为止
        while (true){
            // 拿到了旧值 如:1000
            int prev = balance.get();
            // 在这个基础上  1000-10 = 990
            int 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) 类似++i
        System.out.println(i.incrementAndGet());

        // 自减并获取(i = 2, 结果 i = 1, 返回 1),类似于 --i
        System.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 中因此不必是 final
        System.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<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());
    }

}
不安全的实现
@Slf4j
public class DecimalAccountTest01 implements DecimalAccount{

    BigDecimal balance;

    public DecimalAccountTest01(BigDecimal balance) {
        this.balance = balance;
    }

    @Override
    public BigDecimal getBalance() {
        return balance;
    }

    @Override
    public 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;
    }

    @Override
    public BigDecimal getBalance() {
        return balance;
    }

    @Override
    public 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<BigDecimal> ref;

    public DecimalAccountTest02(BigDecimal balance) {
        ref = new AtomicReference<BigDecimal>(balance);
    }

    @Override
    public BigDecimal getBalance() {
        return ref.get();
    }

    @Override
    public 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<String> ref = new AtomicReference<>("A");

    public static void main(String[] args) {
        log.debug("main start");
        // 获取值A
        // 这个共享变量被其它线程改过吗
        String prev = ref.get();
        other();
        sleep(1);
        // 尝试改为C
        log.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<String> ref = new AtomicStampedReference<String>("A",0);

    public static void main(String[] args) {
        log.debug("main start");
        // 获取值A
        String prev = ref.getReference();
        // 获取版本号
        int stamp = ref.getStamp();

        other();
        sleep(1);
        // 尝试改为C
        log.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<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);  // 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;
    }

    @Override
    public 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 <T> void demo(
        Supplier<T> arraySuppiler,
        Function<T, Integer> lengthFun,
        BiConsumer<T,Integer> putConsumer,
        Consumer<T> printConsumer){

        List<Thread> 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 <T> void demo(
        Supplier<T> arraySuppiler,
        Function<T, Integer> lengthFun,
        BiConsumer<T,Integer> putConsumer,
        Consumer<T> printConsumer){

        List<Thread> 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 = 10
        System.out.println(test.field);

        // 修改成功 field = 20
        fieldUpdater.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 <T> void demo(Supplier<T> adderSuppiler, Consumer<T> action){
        T adder = adderSuppiler.get();

        long start = System.nanoTime();

        List<Thread> 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 mechanics
        private 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,需要随机生成一个值用来绑定到cell
        if ((h = getProbe()) == 0) {
            // 初始化probe
            ThreadLocalRandom.current(); // force initialization
            // h 对应新的 probe 值, 用来对应 cell
            h = getProbe();
            wasUncontended = true;
        }
        // collide 为 true 表示扩容
        boolean collide = false;                // True if last slot nonempty
        for (;;) {
            Cell[] as; Cell a; int n; long v;
            // 已经有了cells
            if ((as = cells) != null && (n = as.length) > 0) {
                // 还没有cell
                if ((a = as[(n - 1) & h]) == null) {
                    // cellBusy = 0
                    if (cellsBusy == 0) {       // Try to attach new Cell
                        // 乐观创建
                        Cell r = new Cell(x);   // Optimistically create
                        // 为 cellsBusy 加锁,cell 初始累加值为 x
                        if (cellsBusy == 0 && casCellsBusy()) {
                            boolean created = false;
                            try {               // Recheck under lock
                                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;
                            }
                            // 成功 break  否则 continue
                            if (created)  
                                break;
                            continue;           // Slot is now non-empty
                        }
                    }
                    // 扩容标记改为false
                    collide = false;
                }
                // 有竞争, 改变线程对应的 cell 来重试 cas
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Contqinue after rehash
                // cas 尝试累加,配合LongAccumulator不为null,配合LongAddr 为null
                else if (a.cas(v = a.value, ((fn == null) ? v + x :
                                             fn.applyAsLong(v, x))))
                    break;
                // 如果cells 长度已经超过了最大程度,或者已经扩容,改变线程对应的cell来重试cas
                else 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 stale
                            Cell[] 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
                }
                // 改变线程对应的 cell
                h = advanceProbe(h);
            }
            // 还没有cells, 尝试给 cellsBusy 加锁
            else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
                // 加锁成功, 初始化 cells, 最开始长度为 2, 并填充一个 cell
                boolean init = false;
                try {                           // Initialize table
                    if (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); // 返回 true
        MyUnsafe.unsafe.compareAndSwapObject(student, nameOffset, null, "张三"); // 返回 true

        System.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,如果期间旧值被别的线程改了,返回 false
            if (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);

            @Override
            public Integer getBalance() {
                return atomicData.getData();
            }

            @Override
            public void withdraw(Integer amount) {
                atomicData.decrease(amount);
            }
        });
    }
}

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晓风残月Lx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值