LongAdder原理解析

一般都是CAS對一個變量進行操作,但Doug Lea大神覺得不滿足,又寫了一個LongAdder

先看下傳統的

 

AtomicLong的原理.png


再來看下LongAdder的

 

LongAdder原理圖.png

即將一個變量進一步拆分到一個base數組中,減少資源競爭

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

        // 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);
            }
        }
    }
  • 類似於AtomicLong,利用CAS來更新變量
  • @Contended避免value僞共享

將多個cell數組中的值加起來的和就類似於AtomicLong中的value

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;
    }

increment()的調用鏈

java.util.concurrent.atomic.LongAdder.increment
  ->java.util.concurrent.atomic.LongAdder.add

多個線程操作的時候.png

add()方法如下

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);
        }
    }

第一次Cell數組爲空,進入casBase()

final boolean casBase(long cmp, long val) {
        return UNSAFE.compareAndSwapLong(this, BASE, cmp, val);
    }

即原子更新,成功則直接返回,失敗則說明出現併發了
if的三個判斷

  • 數組爲空
  • 或者數組長度小於1
  • 或者位置上沒有Cell對象,即getProbe()&m其實相當於hashMap裏面的tab[i = (n - 1) & hash]
  • 或者修改cell的值失敗

纔會最終進入到longAccumulate()方法中

小結

  • 如果Cells表爲空,嘗試用CAS更新base字段,成功則退出;
  • 如果Cells表爲空,CAS更新base字段失敗,出現競爭,uncontended爲true,調用longAccumulate;
  • 如果Cells表非空,但當前線程映射的槽爲空,uncontended爲true,調用longAccumulate;
  • 如果Cells表非空,且前線程映射的槽非空,CAS更新Cell的值,成功則返回,否則,uncontended設爲false,調用longAccumulate。

看到這裏大概應該知道爲什麼LongAdder會比AtomicLong更高效了,沒錯,唯一會制約AtomicLong高效的原因是高併發,高併發意味着CAS的失敗機率更高, 重試次數更多,越多線程重試,CAS失敗機率又越高,變成惡性循環,AtomicLong效率降低。 那怎麼解決? LongAdder給了我們一個非常容易想到的解決方案:減少併發,將單一value的更新壓力分擔到多個value中去,降低單個value的 “熱度”,分段更新!!!

這樣,線程數再多也會分擔到多個value上去更新,只需要增加value就可以降低 value的 “熱度” AtomicLong中的 惡性循環不就解決了嗎? cells 就是這個 “段” cell中的value 就是存放更新值的, 這樣,當我需要總數時,把cells 中的value都累加一下不就可以了麼!!

在看看add方法中的代碼,casBase方法可不可以不要,直接分段更新,上來就計算 索引位置,然後更新value?

不是不行,而是有所考慮的,因爲,casBase操作等價於AtomicLong中的CAS操作,要知道,LongAdder這樣的處理方式是有壞處的,分段操作必然帶來空間上的浪費,可以空間換時間,但是,能不換就不換,空間時間都節約.

casBase操作保證了在低併發時,不會立即進入分支做分段更新操作,因爲低併發時,casBase操作基本都會成功,只有併發高到一定程度了,纔會進入分支

longAccumulate()方法如下

final void longAccumulate(long x, LongBinaryOperator 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(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;
                }
                else if (!wasUncontended)       // CAS already known to fail
                    wasUncontended = true;      // Continue after rehash
                else if (a.cas(v = a.value, ((fn == null) ? v + x :
                                             fn.applyAsLong(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(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;                          // Fall back on using base
        }
    }

longAccumulate.png

  • 如果Cells表爲空,嘗試獲取鎖之後初始化表(初始大小爲2);
  • 如果Cells表非空,對應的Cell爲空,自旋鎖未被佔用,嘗試獲取鎖,添加新的Cell;
  • 如果Cells表非空,找到線程對應的Cell,嘗試通過CAS更新該值;
  • 如果Cells表非空,線程對應的Cell CAS更新失敗,說明存在競爭,嘗試獲取自旋鎖之後擴容,將cells數組擴大,降低每個cell的併發量後再試
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章