分段鎖的應用(JUC Map,LongAdder)

分段鎖的應用

分段鎖顧名思義就是隻鎖一段而不是全局的加鎖,有效提高了在多線程情況下的速度

1.ConcurrentHashMap

ConcurrentHashMap之所以效率高又是線程安全的,主要是使用了分段鎖和cas,很多文章都有不細說了
使用了分段鎖的代碼段:

//這裏鎖的就是數組中的單向鏈表或紅黑樹的頭結點,put時hash到不同的數組中的鏈表鎖的對象是不同的可以實現並行put,只有被分配到同一個鏈表的時候需要阻塞
synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            binCount = 1;
                            //循環鏈表
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                //覆蓋
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                //添加到鏈表尾部(尾插法)
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) {
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        //添加到樹中
                        else if (f instanceof TreeBin) {
                            Node<K,V> p;
                            binCount = 2;
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                //轉爲樹
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }

2.LongAdder

LongAdder是在1.8之後才新加入juc裏的工具,裏面有一個cell數組,cell是在Striped64中的靜態內部類,每個cell維護自己的value,AtomicInteger中僅維護一個全局的value,調用sum將所有cell的value和base相加就是最終的值
先看一下Add方法

public void add(long x) {
        Cell[] as; long b, v; int m; Cell a;
        //如果cell是空未被初始化
        //就執行!casBase(b = base, b + x)
        //這裏的base就相當於AtomicInteger中全局的value
        //cas設置成功就結束,設置失敗說明有競爭,進入方法體
     
        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 ||
                //cas設置cell的value值,如果設置是失敗進入方法體
                //uncontended會變爲false
                !(uncontended = a.cas(v = a.value, v + x)))
                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();
            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) {
                //cellsBusy 0代表可以獲取鎖
                    if (cellsBusy == 0) {       // Try to attach new Cell
                    //把add的值放入cell的value中
                        Cell r = new Cell(x);   // Optimistically create
                        //cellsBusy 鎖標識位如果是0 並且cas將0改爲1成功的話
                        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) {									//一頓判斷之後把cell放入坑裏
                                    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				//擴容2倍
                            Cell[] rs = new Cell[n << 1];
                            //n是原始cell數組長度,按原始下表移動到新數組
                            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) {
                    //初始化爲2的整數倍
                        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
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章