美文网首页
线程安全之原子操作

线程安全之原子操作

作者: 佐蓝Gogoing | 来源:发表于2019-05-19 17:39 被阅读0次

    数据一致性问题

    有以下一段代码

    public class LockDemo {
    
        volatile int i = 0;
    
        public void add() {
            i++;
        }
    
        public static void main(String[] args) throws InterruptedException {
            LockDemo demo = new LockDemo();
    
            for (int k = 0; k < 2; k++) {
                new Thread(() -> {
                    for (int j = 0; j < 10000; j++) {
                        demo.add();
                    }
                    System.out.println("线程结束");
                }).start();
            }
    
            TimeUnit.SECONDS.sleep(2);
            System.out.println(demo.i);
    
        }
    }
    

    运行结果为,与预期的输出 20000 不一样

    线程结束
    线程结束
    14701
    

    如图,线程 T1 和 T2 都获取到 i = 1,将 i++ 后写入,T1 将 i 赋值为 2 后,T2 又一次赋值也是2,这就产生了数据一致性问题,导致结果并不是预期的 20000.

    CAS机制

    CAS(compare and swap,比较和交换)属于硬件同步原语,提供了基本内存操作的原子性保证,当赋值时使用 cas,需要输入两个数值,一个旧值A(操作前的值)和一个新值B,在操作期间比较旧值有没有发生变化,如果没有发生变化,才替换为新值。

    public void add() {
            int current = i;
            int value = current + 1;
            if (current == i) {
                i = value;
            }
        }
    

    如上图所示,CAS 的作用就是保证比较(if(current == i))和赋值(i = value)的原子性。
    JAVA 的 sun.misc.Unsafe 类提供了 compareAndSwapInt() 和 compareAndSwapLong() 等方法实现CAS。

    在 Unsafe 类中 有一个 theUnsafe 实例,它自带一个 getUnsafe()方法

    private static final Unsafe theUnsafe;
    
    public static Unsafe getUnsafe() {
        Class var0 = Reflection.getCallerClass();
        if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
            throw new SecurityException("Unsafe");
        } else {
            return theUnsafe;
        }
    }
    

    但是这个方法不能用,所以只能用反射的方式获取,可以使用 compareAndSwapInt() 来实现预期的结果。

    compareAndSwapInt 方法有四个参数

    compareAndSwapInt(基址(对象的引用), 偏移(对象的属性偏移量), 当前值, 目标值)
    

    使用 CAS 修改代码,如下

    public class LockDemo {
    
        volatile int i = 0;
    
        private static Unsafe unsafe;
    
        private static long valueOffset;
    
        static {
            try {
                Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
                theUnsafe.setAccessible(true);
                unsafe = (Unsafe) theUnsafe.get(null);
                valueOffset = unsafe.objectFieldOffset(LockDemo.class.getDeclaredField("i"));
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    
        public void add() {
            int current;
            int value;
            do {
                current = i;
                // 也可以直接去内存读取 current = unsafe.getIntVolatile(this,valueOffset);
                value = current + 1;
            }while (!unsafe.compareAndSwapInt(this, valueOffset,current,value));
        }
    
        public static void main(String[] args) throws InterruptedException {
            LockDemo demo = new LockDemo();
    
            for (int k = 0; k < 2; k++) {
                new Thread(() -> {
                    for (int j = 0; j < 10000; j++) {
                        demo.add();
                    }
                    System.out.println("线程结束");
                }).start();
            }
    
            TimeUnit.SECONDS.sleep(2);
            System.out.println(demo.i);
    
        }
    }
    

    在 j.u.c 包中已经给我们提供了现成的工具类,如:AtomicInteger 和 AtomicLong
    以 AtomicInteger 为例,这个类也是使用了 Unsafe 类中的方法,下图是其中的一个方法

    public final boolean weakCompareAndSet(int expect, int update) {
            return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
        }
    

    与手写的代码不同之处在于,因为是 jdk 自己的包,所以可以它可以直接使用 Unsafe.getUnsafe(); 来获得 unsafe 对象

    多线程计数工具类

    j.u.c 还提供了专门针对多线程优化的计数工具类 DoubleAdder 、 LongAdder 、 DoubleAccumulator 和 LongAccumulator。
    这几个工具类在进行计算时,每个线程都有一份自己的值,当需要获取总数时,把每个线程的数相加。所以这些工具适合在频繁更新但读取较少的情况下使用。

    CAS 的缺点

    1. CAS 循环+CAS,自旋的实现让所有线程都处于高频运行,争抢 CPU 的状态,如果长时间操作不成功,会带来很大的 CPU 资源消耗
    2. 仅针对单个变量进行操作,不能用于多个变量实现原子性操作
    3. ABA 问题(无法体现出数据的变动)

    相关文章

      网友评论

          本文标题:线程安全之原子操作

          本文链接:https://www.haomeiwen.com/subject/fbhqzqtx.html