天天看点

Jdk1.8下ConcurrentHashMap常用方法的源码分析

1.首先从下面这段代码开始分析

ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
 map.put("123", "1");
 map.put("234", "2");
 System.out.println(map.get("123"));
 System.out.println(map.size());
           

2.我们先从put方法看起

public V put(K key, V value) {
        return putVal(key, value, false);
}
           
final V putVal(K key, V value, boolean onlyIfAbsent) {
		// 首先判断key和value都不能为null
        if (key == null || value == null) throw new NullPointerException();
        // 获取key对应的hash值
        int hash = spread(key.hashCode());
        int binCount = 0;
        // 开始自旋遍历元素
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            // 如果数组为空,则进行初始化操作
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            // 先通过unsafe操作获取i位置的元素,并判断是否为空
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            	// 通过cas操作在数组的i位置上创建一个Node元素
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            // 如果当前key的hash值为-1,表示当前数组i位置上有线程正在扩容,那么这个时间就要帮忙要转移元素
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            // 如果数组i位置上有元素,则走到下面代码逻辑
            else {
                V oldVal = null;
                // 这里使用synchronized 对数组的i位置的f元素进行加锁
                synchronized (f) {
                	// 再次判断第i位置上的元素是否还是等于f
                    if (tabAt(tab, i) == f) {
                    	// 判断key的hash是否大于0
                        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;
                                }
                            }
                        }
                        // 如果数组i位置的f元素是红黑树,则进行树插入操作,这里有比较和自旋操作
                        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;
                            }
                        }
                    }
                }
                // 如果f位置上链表长度大于8,则进行树化
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        // 插入之后,对Map的容量进行加1操作
        addCount(1L, binCount);
        return null;
}
           

3.其中看一下上面的treeifyBin(tab, i);这个方法

private final void treeifyBin(Node<K,V>[] tab, int index) {
        Node<K,V> b; int n, sc;
        if (tab != null) {
            if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
                tryPresize(n << 1);
            else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
            	// 这里再次获取数组i位置的元素b,然后锁住这个对象
                synchronized (b) {
                	// 再次判断i位置元素是否等于b
                    if (tabAt(tab, index) == b) {
                        TreeNode<K,V> hd = null, tl = null;
                        // 遍历链表
                        for (Node<K,V> e = b; e != null; e = e.next) {
                            TreeNode<K,V> p =
                                new TreeNode<K,V>(e.hash, e.key, e.val,
                                                  null, null);
                            if ((p.prev = tl) == null)
                                hd = p;
                            else
                                tl.next = p;
                            tl = p;
                        }
                        // 找到树的根节点hd,并进行树化new TreeBin<K,V>(hd),其中TreeBin是包含红黑数根节点的一个对象
                        // 然后在数组i位置设置创建出来的new TreeBin<K,V>(hd)元素
                        setTabAt(tab, index, new TreeBin<K,V>(hd));
                    }
                }
            }
        }
}
           

4.然后在看一下数组初始化的initTable方法

private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        // 循环过程
        while ((tab = table) == null || tab.length == 0) {
        	// 如果sc小于0,则进行放弃当前cpu操作,再去和其他线程进行cpu竞争
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            // 一个cas操作判断是否相等,并-1操作
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                	// 进行数组初始化操作
                    if ((tab = table) == null || tab.length == 0) {
                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                        @SuppressWarnings("unchecked")
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = tab = nt;
                        sc = n - (n >>> 2);
                    }
                } finally {
                	// 计算出阈值
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
}
           

5.再看一下putVal方法中最后一段代码中的addCount方法

private final void addCount(long x, int check) {
        CounterCell[] as; long b, s;
        // 下面这个判断是,如果counterCells数组为null,那么就会走在数组的baseCount基础上去加1,如果失败则进入判断内
        if ((as = counterCells) != null ||
            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
            CounterCell a; long v; int m;
            boolean uncontended = true;
            // 下面一段代码的逻辑是对CounterCell数组,根据不同线程取一个随机数&数组长度,之后再数组对应位置赋值(在basecount的基础上+1),如果存在则在之前的基础上加1,最后在遍历CounterCell数组算出每个数组value之和算出map的size
            if (as == null || (m = as.length - 1) < 0 ||
                (a = as[ThreadLocalRandom.getProbe() & m]) == null ||
                !(uncontended =
                  U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
                fullAddCount(x, uncontended);
                return;
            }
            if (check <= 1)
                return;
            s = sumCount();
        }

		// 下面就是扩容情况
        if (check >= 0) {
            Node<K,V>[] tab, nt; int n, sc;
            // 如果数组容量大于阈值,并且数组不为null,数组长度小于MAXIMUM_CAPACITY,并且会再次判断
            while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
                   (n = tab.length) < MAXIMUM_CAPACITY) {
                // 这里会计算出一个很大的负数
                int rs = resizeStamp(n);
                // 下面的判断是防止两个线程同时进行扩容
                if (sc < 0) {
                    if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                        sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                        transferIndex <= 0)
                        break;
                    if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                        transfer(tab, nt);
                }
                else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                             (rs << RESIZE_STAMP_SHIFT) + 2))
                    transfer(tab, null);
                // 重新计算map的大小
                s = sumCount();
            }
        }
 }
           

6.再继续点击transfer方法查看扩容逻辑

private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        // 下面会计算出扩容的步长stride,这在多线程下计算的值使固定的
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
        // 初始化新数组,大小翻倍
        if (nextTab == null) {            // initiating
            try {
                @SuppressWarnings("unchecked")
                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                nextTab = nt;
            } catch (Throwable ex) {      // try to cope with OOME
                sizeCtl = Integer.MAX_VALUE;
                return;
            }
            nextTable = nextTab;
            transferIndex = n;
        }
        int nextn = nextTab.length;
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        // 是否允许前进
        boolean advance = true;
        // 当前线程是否完成任务
        boolean finishing = false; // to ensure sweep before committing nextTab
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            // 判断是否还可以继续前进
            while (advance) {
                int nextIndex, nextBound;
                if (--i >= bound || finishing)
                    advance = false;
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    bound = nextBound;
                    i = nextIndex - 1;
                    advance = false;
                }
            }
            if (i < 0 || i >= n || i + n >= nextn) {
                int sc;
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                        return;
                    finishing = advance = true;
                    i = n; // recheck before commit
                }
            }
            // 如果当前数组i位置元素为空,则创建一个fwd元素,那么则扩容前进
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            // 如果i位置上的hash等于MOVED表示有其他线程正在扩容,那么则扩容前进
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
            	// 如果i位置上有元素,那么先锁住这个位置,然后进行扩容
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        // 一种是链表的扩容转移
                        if (fh >= 0) {
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                            for (Node<K,V> p = f.next; p != null; p = p.next) {
                                int b = p.hash & n;
                                if (b != runBit) {
                                    runBit = b;
                                    lastRun = p;
                                }
                            }
                            if (runBit == 0) {
                                ln = lastRun;
                                hn = null;
                            }
                            else {
                                hn = lastRun;
                                ln = null;
                            }
                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
                                int ph = p.hash; K pk = p.key; V pv = p.val;
                                if ((ph & n) == 0)
                                    ln = new Node<K,V>(ph, pk, pv, ln);
                                else
                                    hn = new Node<K,V>(ph, pk, pv, hn);
                            }
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            // 转移完之后将i位置元素设置为fwd
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                        // 另外一种是树下面的扩容
                        else if (f instanceof TreeBin) {
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> lo = null, loTail = null;
                            TreeNode<K,V> hi = null, hiTail = null;
                            int lc = 0, hc = 0;
                            for (Node<K,V> e = t.first; e != null; e = e.next) {
                                int h = e.hash;
                                TreeNode<K,V> p = new TreeNode<K,V>
                                    (h, e.key, e.val, null, null);
                                if ((h & n) == 0) {
                                    if ((p.prev = loTail) == null)
                                        lo = p;
                                    else
                                        loTail.next = p;
                                    loTail = p;
                                    ++lc;
                                }
                                else {
                                    if ((p.prev = hiTail) == null)
                                        hi = p;
                                    else
                                        hiTail.next = p;
                                    hiTail = p;
                                    ++hc;
                                }
                            }
                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            // 转移完之后将i位置元素设置为fwd
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                    }
                }
            }
        }
}
           

7.继续看一下get方法

public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        // 计算key的hash值
        int h = spread(key.hashCode());
        // 根据hash值算出数组对应的下标,然后获取对应位置的值是否为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            // 如果是当前数组i位置的元素,则直接返回
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
             //hash值为负值表示正在扩容,这个时候查的是ForwardingNode的find方法来定位到nextTable来
            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;
}
           

8.在继续查看一下remove方法

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;
            // 如果数组为空,或者数组长度为0,或者key对应位置的元素为空,则跳出循环
            if (tab == null || (n = tab.length) == 0 ||
                (f = tabAt(tab, i = (n - 1) & hash)) == null)
                break;
            // 如果key对应位置的元素正在扩容,则帮助扩容
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                boolean validated = false;
                // 然后锁住数组上的f元素,进行删除操作
                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));
                                }
                            }
                        }
                    }
                }
                // 返回旧值,并进行减1操作
                if (validated) {
                    if (oldVal != null) {
                        if (value == null)
                            addCount(-1L, -1);
                        return oldVal;
                    }
                    break;
                }
            }
  }
  return null;
}
           

9.再继续看一下size方法

public int size() {
        long n = sumCount();
        return ((n < 0L) ? 0 :
                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
                (int)n);
}
           
//计算表中的元素总个数
final long sumCount() {
 CounterCell[] as = counterCells; CounterCell a;
 //baseCount,以这个值作为累加基准
 long sum = baseCount;
 if (as != null) {
  //遍历 counterCells 数组,得到每个对象中的value值
  for (int i = 0; i < as.length; ++i) {
   if ((a = as[i]) != null)
    //累加 value 值
    sum += a.value;
  }
 }
 //此时得到的就是元素总个数
 return sum;
} 
           

继续阅读