并发读源码——并发读源码Striped64/LongAdder/DoubleAdder/LongAccumulator/DoubleAccumulator

1、LongAdder原理介绍

LongAdder是JDK8中新增加的一个并发类,LongAdder主要用于对long型变量进行CAS(CAS可以参考前面系列文章)操作,但AtomicLong也是对long型变量进行CAS操作,两者什么区别呢?
AtomicLong内部维护了一个volatile long类型的变量,多个线程并发CAS操作该变量,而LongAdder把一个long变量拆分出多个long变量,采用分段锁的方式对多个变量进行并发。
在LongAdder内部,一个long型变量被拆分成了一个base变量和一组Cell,每个Cell内部维护了一个long型变量,多个线程并发时,如果并发低,直接累加到base变量,并发高冲突大时,平摊到一组Cell中,最后取值时,再把base和全部的Cell中的value值进行 累加求和。
上述原理内容在Striped64元子类中的longAccumulate方法实现的,LongAdder继承了Striped64,LongAdder只是一个元子类并发的框架子,其分段锁核心思想均在父类Striped64中longAccumulate方法实现。Striped64内部维护了一个base和一组Cell,当线程执行时会首先 更新base变量,如果更新失败,认为当前线程有竞争,就会对Cell进行初始化或扩容,然后根据当前线程的探针计算hash值映射到一组Cell的下标中,如果多个线程竞争同一个Cell导致更新Cell失败,会扩容Cell的数组并重新hash数组的下标,不同的并发线程分散到不同的Cell中执行。
这种分段锁的思想,在并发低的时候,不如AtomicLong的效率高,因为并发低时,LongAdder还要把base和各个Cell累加起来;当并发非常高时,LongAdder的效率就显现出来了,所以LongAdder适合大规模并发统计的场景。

2、LongAdder源码介绍

首先分析LongAdder的源码

public class LongAdder extends Striped64 implements Serializable {
    private static final long serialVersionUID = 7249069246863182397L;

    public LongAdder() {
    }

    /*
     * LongAdder继承了Striped64,所以同时继承了Striped64中的属性cells、base、cellsBusy
     * */
    public void add(long x) {
        Cell[] as; long b, v; int m; Cell a;
        /*
         **首次执行的时候,都是试着把x加到base上面,首次执行时cell都是null,如果casBase失败,则产生了竞争,进入longAccumulate处理
         **非首次执行,cells数组已经初始化过了,当前线程hash对应下标的cell为空,则进入longAccumulate创建cell,并加入cells;如果不为空,则把x值加到对应的cell商
         **如果x加到cell上失败,说明多线程产生了竞争,进入longAccumulate重试或者扩容
         *
         **在取cells下标时,是根据当前线程的hash,即getProbe()&m,getProbe为当前线程的探针值
         */
        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);
        }
    }

    /**
     * 加1
     */
    public void increment() {
        add(1L);
    }

    /**
     * 减1
     */
    public void decrement() {
        add(-1L);
    }

    /**
     * 把cells中所有的value值累加到base上返回结果
     * 该方法局限性:不能有竞争线程存在
     */
    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;
    }

    /**
     * 该方法重置base以及cells中所有value的值为0,相当于创建了一个新的LongAdder
     * 但是该方法时有局限性的,在重置时不能有并发存在,否则会导致base或cells中values未能有效置0
     */
    public void reset() {
        Cell[] as = cells; Cell a;
        base = 0L;
        if (as != null) {
            for (int i = 0; i < as.length; ++i) {
                if ((a = as[i]) != null)
                    a.value = 0L;
            }
        }
    }

    /**
     * 先把cells中所有values累加到base中,然后重置base和cells中所有value值为0
     * 该方法局限性:不能有竞争线程存在
     */
    public long sumThenReset() {
        Cell[] as = cells; Cell a;
        long sum = base;
        base = 0L;
        if (as != null) {
            for (int i = 0; i < as.length; ++i) {
                if ((a = as[i]) != null) {
                    sum += a.value;
                    a.value = 0L;
                }
            }
        }
        return sum;
    }

    public String toString() {
        return Long.toString(sum());
    }

    /**
     * 求出base以及cells中所有value总和
     */
    public long longValue() {
        return sum();
    }

    /**
     * 把sum总和向下转为int类型,如果超出Int的最大范围,则高位截断
     */
    public int intValue() {
        return (int)sum();
    }

    /**
     * sum总和转化为float类型
     */
    public float floatValue() {
        return (float)sum();
    }

    /**
     * sum总和转化为double类型
     */
    public double doubleValue() {
        return (double)sum();
    }

    /*
     * 序列化代理内部类
     * 在对LongAdder序列化时,不再直接对LongAdder进行序列化,会暴露LongAdder中各种属性,通过SerializationProxy类,只把LongAdder中的sum总和进行序列化,隐藏了LongAdder的结构
     * */
    private static class SerializationProxy implements Serializable {
        private static final long serialVersionUID = 7249069246863182397L;

        /**
         * The current value returned by sum().
         * @serial
         */
        private final long value;

        SerializationProxy(LongAdder a) {
            value = a.sum();
        }

        /*
         * 反序列化时,读取该方法进行 反序列化
         * */
        private Object readResolve() {
            LongAdder a = new LongAdder();
            a.base = value;
            return a;
        }
    }

    /*
     * 调用该方法,对LongAdder的序列化代理内部类SerializationProxy进行序列化
     * */
    private Object writeReplace() {
        return new SerializationProxy(this);
    }

    /*
     * 如果反序列结果与序列化结果不一致,调用该方法抛出无效对象异常
     * */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.InvalidObjectException {
        throw new java.io.InvalidObjectException("Proxy required");
    }

}

可以看出LongAdder内部的核心方法是add,在并发比较高时,add方法调用了父类Strped64中的方法longAccumulate。下面分析下Strped64源码

@SuppressWarnings("serial")
abstract class Striped64 extends Number {

	/*
	 * Cell为Striped64的内部类,Cell中维护了一个value变量值,当多线程并发时,把要竞争的资源摊分到不同的Cell中进行执行,减少并发
	 * *后续对value操作都是对value在Cell中内存偏移量进行操作的
	 * */
    @sun.misc.Contended static final class Cell {
        volatile long value;
        Cell(long x) { value = x; }
        final boolean cas(long cmp, long val) {
            return UNSAFE.compareAndSwapLong(this, valueOffset, cmp, val);
        }

        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数量*/
    static final int NCPU = Runtime.getRuntime().availableProcessors();

    /**
     * cells数组中容量是2的倍数
     */
    transient volatile Cell[] cells;

    /**
     * *从最开始没有竞争时,对base进行累加或累减操作
     */
    transient volatile long base;

    /**
     * *相当于一个锁标志,当对cells进行扩容或创建时,需要先获取cellBusy锁,如果获取不到,说明有其他线程已经获取了
     */
    transient volatile int cellsBusy;

    Striped64() {
    }

    /**
     * * 对base进行CAS操作
     */
    final boolean casBase(long cmp, long val) {
        return UNSAFE.compareAndSwapLong(this, BASE, cmp, val);
    }

    /**
     * *CELLSBUSY是cellsBusy的内存偏移量
     * *对CELLSBUSY做CAS操作,修改成功,cellsBusy的值为1,表示拿到锁
     */
    final boolean casCellsBusy() {
        return UNSAFE.compareAndSwapInt(this, CELLSBUSY, 0, 1);
    }

    /**
     * *返回当前线程的探针
     */
    static final int getProbe() {
        return UNSAFE.getInt(Thread.currentThread(), PROBE);
    }

    /**
     **利用xorshift算法生成伪随机数,生成当前线程的探针值
     */
    static final int advanceProbe(int probe) {
        probe ^= probe << 13;   // xorshift
        probe ^= probe >>> 17;
        probe ^= probe << 5;
        UNSAFE.putInt(Thread.currentThread(), PROBE, probe);
        return probe;
    }

    /*
     * *该函数用于处理涉及cells初始化、扩容、更新情况,对于更新cells进行从试或扩容
     * */
    final void longAccumulate(long x, LongBinaryOperator fn,
                              boolean wasUncontended) {
       /*如果当前线程还未hash,初始化线程的hash探针*/ 
    	int h;
        if ((h = getProbe()) == 0) {
            ThreadLocalRandom.current(); // force initialization
            h = getProbe();
            wasUncontended = true;
        }
        boolean collide = false;        //collide=false表示cells不会扩容,collide=true表示cells会扩容
        for (;;) {
            Cell[] as; Cell a; int n; long v;
            if ((as = cells) != null && (n = as.length) > 0) {
            	/*
            	 * 当cells不为null时,对当前线程探针作hash作为cells的下标,确定下标后,x的值就要作用到该指定位置的Cell上
            	 * 但是当cells指定位置的Cell为null时,就要在该坐标位置创建Cell
            	 * 在创建Cell时一定要先获取cellsBusy锁
            	 * */
                if ((a = as[(n - 1) & h]) == null) {
                    if (cellsBusy == 0) {       // Try to attach new Cell
                        Cell r = new Cell(x);   // Optimistically create
                        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;
                            }
                            if (created)
                                break;
                            continue;           // Slot is now non-empty
                        }
                    }
                    collide = false;
                }
                /*
                 * 在LongAdder的add方法中,在对cells做CAS时失败,wasUncontended=false传入到该longAccumulate方法,说明发生了线程竞争
                 * 现在置wasUncontended=true,重新对cells执行
                 * */
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Continue after rehash
                /*
                 * 对线程探针hash后的值对应cells的坐标有值,则对该坐标处的Cell执行CAS操作
                 * 如果fn==null,则直接把x累加到a中value上;如果fn!=null,则对v和x执行功能函数fn,执行后的值更新到a中的value值上
                 * */
                else if (a.cas(v = a.value, ((fn == null) ? v + x :
                                             fn.applyAsLong(v, x))))
                    break;
                /*
                 * 如果a做CAS失败,说明线程发生了竞争,多个线程在竞争a资源
                 * 此时判断是否对cells扩容:如果n>=CPU的个数,不扩容;或者其他线程已经修改了cells,也不扩容
                 * */
                else if (n >= NCPU || cells != as)
                    collide = false;            // At max size or stale
                /*
                 * 如果判断不对cells进行扩容,则把扩容标志collide设置true,从新进行自旋,也即执行for循环
                 * */
                else if (!collide)
                    collide = true;
                /*
                 * 如果在执行前面(a.cas(v = a.value, ((fn == null) ? v + x : fn.applyAsLong(v, x))))操作失败后,即更新Cell失败,
                 * 又满足扩容条件,即n<NCPU,则对cells进行扩容一倍,并把原来cells中内容复制到新扩容后的cells中
                 * */
                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
                }
                /*
                 * a.cas执行失败,又不满足扩容条件时,重新hash当前线程探针值,并从新执行自旋操作,即for循环
                 * */
                h = advanceProbe(h);
            }
            /*
             * cells为空时,在LongAdder中执行add方法时,首先加到base上,加到base上失败,即有竞争时,走该分支
             * *初始化cells,cells初始值容量是2,后续扩容时乘2,
             * 
             * *在初始化cells时,首先拿到cellsBusy锁,即cellsBuys为0时,证明没有其它线程竞争,后续才可以初始化cells,因为其它线程此时也可能在初始化cells,
             * *只能由一个线程初始化cells,所以要先判断是否获得锁
             * */
            else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
                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;
                }
                if (init)
                    break;
            }
            /*
             * *如果前一步初始化cells失败,即没有拿到cellsBusy锁,说明有其它线程已经拿到了cellsBusy锁,正在初始化cells
             * *在此种情况下,会把x的值加到base上
             * */
            else if (casBase(v = base, ((fn == null) ? v + x :
                                        fn.applyAsLong(v, x))))
                break;                          // Fall back on using base
        }
    }

    /**
     *  doubleAccumulate与longAccumulate操作一致
     *  只不过longAccumulate时处理long型分段锁的,doubleAccumulate是执行double类型分段锁的,
     *  但是doubleAccumulate中double类型也是转换成long类型,然后用分段锁的,最后再把执行结果转换成double类型
     */
    final void doubleAccumulate(double x, DoubleBinaryOperator fn,
                                boolean wasUncontended) {
        int h;
        if ((h = getProbe()) == 0) {
            ThreadLocalRandom.current(); // force initialization
            h = getProbe();
            wasUncontended = true;
        }
        boolean collide = false;                // True if last slot nonempty
        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) {       // Try to attach new Cell
                        Cell r = new Cell(Double.doubleToRawLongBits(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;
                            }
                            if (created)
                                break;
                            continue;           // Slot is now non-empty
                        }
                    }
                    collide = false;
                }
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Continue after rehash
                else if (a.cas(v = a.value,
                               ((fn == null) ?
                                Double.doubleToRawLongBits
                                (Double.longBitsToDouble(v) + x) :
                                Double.doubleToRawLongBits
                                (fn.applyAsDouble
                                 (Double.longBitsToDouble(v), x)))))
                    break;
                else if (n >= NCPU || cells != as)
                    collide = false;            // At max size or stale
                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
                }
                h = advanceProbe(h);
            }
            else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
                boolean init = false;
                try {                           // Initialize table
                    if (cells == as) {
                        Cell[] rs = new Cell[2];
                        rs[h & 1] = new Cell(Double.doubleToRawLongBits(x));
                        cells = rs;
                        init = true;
                    }
                } finally {
                    cellsBusy = 0;
                }
                if (init)
                    break;
            }
            else if (casBase(v = base,
                             ((fn == null) ?
                              Double.doubleToRawLongBits
                              (Double.longBitsToDouble(v) + x) :
                              Double.doubleToRawLongBits
                              (fn.applyAsDouble
                               (Double.longBitsToDouble(v), x)))))
                break;                          // Fall back on using base
        }
    }

    // Unsafe mechanics
    private static final sun.misc.Unsafe UNSAFE;
    private static final long BASE;
    private static final long CELLSBUSY;
    private static final long PROBE;
    static {
        try {
            UNSAFE = sun.misc.Unsafe.getUnsafe();
            Class<?> sk = Striped64.class;
            BASE = UNSAFE.objectFieldOffset
                (sk.getDeclaredField("base"));
            CELLSBUSY = UNSAFE.objectFieldOffset
                (sk.getDeclaredField("cellsBusy"));
            Class<?> tk = Thread.class;
            PROBE = UNSAFE.objectFieldOffset
                (tk.getDeclaredField("threadLocalRandomProbe"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

}

}

3、LongAdder并发时应用

比如对银行中热点账户问题,一个火爆的理财账户对外进行抢售卖(假设不设额度上限),如果只有一个线程对该账户执行,多个客户同时进行购买理财时就会导致其他几个客户购买失败,造成非常坏的体验,利用本节的LongAdder,把一个热点账户拆分成几个账户同时对外售卖,就可以大大减少并发失败率。

package com.lzj.atomic.striped64;

import java.util.concurrent.atomic.LongAdder;

public class LongAdderDemo {

	private static LongAdder adder = new LongAdder();  
	
	
	public static void main(String[] args) throws InterruptedException {
		
		Runnable run1 = new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<100; i++) {
					adder.add(100); 	//假设线程1每次卖理财100,统计100次
				}
			}
		};
		
		Runnable run2 = new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<100; i++) {
					adder.add(50);		//假设线程2每次卖理财50,统计100次
				}
			}
		};

		Thread thread1= new Thread(run1);
		Thread thread2 = new Thread(run2);
		thread1.start();
		thread2.start();
		thread1.join();
		thread2.join();
		System.out.println("理财账户总共卖出理财 :" + adder.sum());
	}

}

线程执行结束后,输出如下,可见所有客户购买理财成功

理财账户总共卖出理财 :15000

4、DoubleAdder分析

LongAdder是处理long型变量分段锁并发的,而DoubleAdder内部是处理double类型分段锁并发的,两者原理完全一致,用法也完全一致,DoubleAdder内部的核心方法也是add方法,该方法并发高时,调用了父类Striped64中的doubleAccumulate方法。
并且DoubleAdder的代码与LongAdder的代码都一致,两者都继承了Striped64基类,DoubleAdder内部就是利用long型分段锁进行并发的,并发结束后,又把long型变量转化了double类型,可见DoubleAdder内部也是利用LongAdder进行并发计算的。

5、LongAccumulator分析

LongAccumulator与LongAdder原理类似,都是调用了父类Striped64中longAccumulate方法完成分段锁的更新,只是LongAccumulator的功能更强大。

LongAdder只能进行累加操作,并且初始值为0;LongAccumulator可以进行两个二维元素的操作,初始值可以自定义。LongAdder在调用Striped64中longAccumulate中方法时,传入的LongBinaryOperator对象为null,导致LongAdder只能进行累加减操作,因为LongAdder在执行CAS的时候执行的casBase(b, b+x),或者a.cas(v = a.value, v + x);而LongAccumulator在调用Striped64中longAccumulate中方法时,自定义了一个对二维元素操作的LongBinaryOperator对象,可以对这个二维元素进行任意操作,因为LongAccumulator在CAS时候执行的casBase(b,r),或者a.cas(v=a.value,r),其中r=LongBinaryOperator.applyAsLong(base,x),或者LongBinaryOperator(a.value,x)。

用法示例如下,假设对一个指定因子,用多个线程对其翻倍处理,示例中因子为1

public class LongAccumulatorDemo {

	public static void main(String[] args) throws InterruptedException  {
		LongBinaryOperator operator = (x, y) -> x*y;
		LongAccumulator accumulator = new LongAccumulator(operator, 1);
		
		Runnable runn1 = new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<10; i++) {
					accumulator.accumulate(2);
				}
			}
		};
		
		Runnable runn2 = new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<10; i++) {
					accumulator.accumulate(2);
				}
			}
		};
		
		Thread thread1 = new Thread(runn1);
		Thread thread2 = new Thread(runn2);
		thread1.start();
		thread2.start();
		thread1.join();
		thread2.join();
		System.out.println("并发结果为:" + accumulator.get());
	}

}

执行结果如下:

并发结果为:1048576

6、DoubleAccumulator分析

DoubleAccumulator原理与用法与LongAccumulator完全一致,只是DoubleAccumulator用来处理double类型的数值,LongAccumulator用来处理long类型的数值。其实DoubleAccumulator内部与DoubleAdder一样都是先转化为Long类型处理,结果再转化为Double类型。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值