LongAdder及AtomicLong

AtomicLong原理
  就像我們所知道的那樣,AtomicLong的原理是依靠底層的cas來保障原子性的更新數據,在要添加或者減少的時候,會使用死循環不斷地cas到特定的值,從而達到更新數據的目的。那麼LongAdder又是使用到了什麼原理?難道有比cas更加快速的方式?
LongAdder原理
這裏讓我困惑的一個問題是LongAdder中沒有類似於AtomicLong中getAndIncrement()或者incrementAndGet()這樣的原子操作,所以只能通過increment()方法和longValue()方法的組合來實現更新和獲取的動作,然而這樣不能保證這個組合操作的原子性,猜想也許LongAdder就是不具備這樣的機制吧。那麼就主要看一下increment()和longValue()方法。
increment方法:
分析increment()方法,可以看到該方法就是對add(long x)的封裝,那麼具體來分析一下這個方法

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

這裏重點是casBase(b = base, b + x),來看一下它做了什麼

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

這裏的四個條件其實並不是並列的,而是遞進式的,1和2判斷cells數組是否爲空,3取cells數組中的任意一個元素a判斷是否爲空,4是對a進行cas操作並將執行結果賦值標誌位uncontended。從這裏可以給出第二個結論,當競爭激烈到一定程度無法對base進行累加操作時,會對cells數組中某個元素進行更新。
最後來看一下當上述條件無法全部滿足時調用的longAccumulate(x, null, uncontended)方法

final void longAccumulate(long x, LongBinaryOperator fn,
                              boolean wasUncontended) {
        int h;
        if ((h = getProbe()) == 0) {
            ThreadLocalRandom.current(); // force initialization
            h = getProbe();  //返回當前線程的threadLocalRandomProbe值
            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) {       // cells數組中對應位置沒有數據則插入新對象
                        Cell r = new 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;
                            }
                            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))))         //對該位置的cell元素進行累加
                    break;
                else if (n >= NCPU || cells != as)
                    collide = false;            // At max size or stale   //判斷數組大小是否大於核數
                else if (!collide)
                    collide = true;
                else if (cellsBusy == 0 && casCellsBusy()) {         //對cells數組進行擴容,直接擴容爲2倍
                    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()) {  //cellsBusy這裏是做爲一個自旋鎖來使用的
                boolean init = false;
                try {                           // 初始化cells數組大小爲2
                    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))))      //對base進行CAS操作
                break;                          // Fall back on using base
        }
    }

這個方法比較長,大致對幾個關鍵點做了註釋,該方法主要是用一個死循環對cells數組中的元素進行操作,當要更新的位置的元素爲空時插入新的cell元素,否則在該位置進行CAS的累加操作,如果CAS操作失敗並且數組大小沒有超過核數就擴容cells數組。

總結
LongAdder類與AtomicLong類的區別在於高併發時前者將對單一變量的CAS操作分散爲對數組cells中多個元素的CAS操作,取值時進行求和;而在併發較低時僅對base變量進行CAS操作,與AtomicLong類原理相同。不得不說這種分佈式的設計還是很巧妙的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章