JUC 一 ConcurrentHashMap

java.util.concurrentjava

ConcurrentHashMap是一個支持併發檢索和併發更新的線程安全的HashMap(但不容許空key或value)。
JDK8以CAS+synchronized來保證併發安全。安全

ConcurrentHashMap、HashMap和HashTable

效率:多線程

  1. 當指望許多線程訪問一個給定collection時,ConcurrentHashMap一般優於同步的HashMapConcurrentSkipListMap一般優於同步的TreeMap
  2. 當指望的讀數和遍歷遠遠大於列表的更新數時,CopyOnWriteArrayList優於同步的ArrayList

ConcurrentHashMap、HashMap和HashTable的區別:併發

  1. HashMap 是非線程安全的哈希表,經常使用於單線程程序中。
  2. Hashtable 是線程安全的哈希表,因爲是經過內置鎖 synchronized 來保證線程安全,在資源爭用比較高的環境下,Hashtable 的效率比較低。
  3. ConcurrentHashMap 是一個支持併發操做的線程安全的HashMap,可是他不容許存儲空key或value。使用CAS+synchronized來保證併發安全(在JDK 7以前是經過LockSegment(分段鎖)實現併發安全),在併發訪問時不須要阻塞線程,因此效率是比Hashtable 要高的。

結構線程

put(K, V)

public V put(K key, V value) {
    return putVal(key, value, false);
}

/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
    //計算hash值
    int hash = spread(key.hashCode());
    int binCount = 0;
    for (Node<K,V>[] tab = table;;) {//自旋
        //f:索引節點; n:tab.length; i:新節點索引 (n - 1) & hash; fh:f.hash
        Node<K,V> f; int n, i, fh;
        if (tab == null || (n = tab.length) == 0)
            //初始化
            tab = initTable();
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {//索引i節點爲空,直接插入
            //cas插入節點,成功則跳出循環
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
        //當前節點處於移動狀態-其餘線程正在進行節點轉移操做
        else if ((fh = f.hash) == MOVED)
            //幫助轉移
            tab = helpTransfer(tab, f);
        else {
            V oldVal = null;
            synchronized (f) {
                if (tabAt(tab, i) == f) {//check stable
                    //f.hash>=0,說明f是鏈表的頭結點
                    if (fh >= 0) {
                        binCount = 1;//記錄鏈表節點數,用於後面是否轉換爲紅黑樹作判斷
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            //key相同 修改
                            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) {
                //若是鏈表中節點數binCount >= TREEIFY_THRESHOLD(默認是8),則把鏈表轉化爲紅黑樹結構
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    //更新新元素個數
    addCount(1L, binCount);
    return null;
}

get(Object key)

public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }

remove(Object key)

public V remove(Object key) {
        return replaceNode(key, null, null);
    }


    final V replaceNode(Object key, V value, Object cv) {
        int hash = spread(key.hashCode());
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0 ||
                (f = tabAt(tab, i = (n - 1) & hash)) == null)
                break;
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                boolean validated = false;
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            validated = true;
                            for (Node<K,V> e = f, pred = null;;) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    V ev = e.val;
                                    if (cv == null || cv == ev ||
                                        (ev != null && cv.equals(ev))) {
                                        oldVal = ev;
                                        if (value != null)
                                            e.val = value;
                                        else if (pred != null)
                                            pred.next = e.next;
                                        else
                                            setTabAt(tab, i, e.next);
                                    }
                                    break;
                                }
                                pred = e;
                                if ((e = e.next) == null)
                                    break;
                            }
                        }
                        else if (f instanceof TreeBin) {
                            validated = true;
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> r, p;
                            if ((r = t.root) != null &&
                                (p = r.findTreeNode(hash, key, null)) != null) {
                                V pv = p.val;
                                if (cv == null || cv == pv ||
                                    (pv != null && cv.equals(pv))) {
                                    oldVal = pv;
                                    if (value != null)
                                        p.val = value;
                                    else if (t.removeTreeNode(p))
                                        setTabAt(tab, i, untreeify(t.first));
                                }
                            }
                        }
                        else if (f instanceof ReservationNode)
                            throw new IllegalStateException("Recursive update");
                    }
                }
                if (validated) {
                    if (oldVal != null) {
                        if (value == null)
                            addCount(-1L, -1);
                        return oldVal;
                    }
                    break;
                }
            }
        }
        return null;
    }
相關文章
相關標籤/搜索