面向java--ConcurrentHashMap

本文基于jdk1.8

1.简介

ConcurrentHashMap 是HashMap 的线程安全版本。底层跟HashMap类似,采用了数组+链表+红黑树的结构。其继承关系如下

在这里插入图片描述

二.源码解析

1.基本属性

主要列出与HashMap不同的属性

    // 最小转移分组大小
    private static final int MIN_TRANSFER_STRIDE = 16;

    private static int RESIZE_STAMP_BITS = 16;

   // 最大扩容量
    private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;

    // 扩容时邮戳
    private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;

	transient volatile Node<K,V>[] table;

    // 扩容时使用,正常时为nul
    private transient volatile Node<K,V>[] nextTable;

    //  基础数量,当前数量的一部分
    private transient volatile long baseCount;

    // 控制是否扩容,
    private transient volatile int sizeCtl;

    private transient volatile int transferIndex;
	// 表示counterCell是否在扩容或初始化,0表示默认未进行这些操作
    private transient volatile int cellsBusy;

    private transient volatile CounterCell[] counterCells;

2.构造函数

构造函数与HashMap类似,区别在于不在使用loadFactor,而使用sizeCtl 。

 	public ConcurrentHashMap() {
    }

    public ConcurrentHashMap(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
        this.sizeCtl = cap;
    }

    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
        this.sizeCtl = DEFAULT_CAPACITY;
        putAll(m);
    }
  
    public ConcurrentHashMap(int initialCapacity, float loadFactor) {
        this(initialCapacity, loadFactor, 1);
    }

    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
            throw new IllegalArgumentException();
        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
            initialCapacity = concurrencyLevel;   // as estimated threads
        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        this.sizeCtl = cap;
    }

3. put添加

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

    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;;) {
            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) {
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;               
            }
            // 头节点move状态,则帮助扩容
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                synchronized (f) {
                	// 找到桶
                    if (tabAt(tab, i) == f) {
                    	// 树的根节点为 -2,这里大于0表示链表
                        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;
                            // 这里设置2,避免影响后面binCount >= TREEIFY_THRESHOLD的判断 
                            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;
                }
            }
        }
        // 判断是否需要扩容
        addCount(1L, binCount);
        return null;
    }

	private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
        	// 当有其他线程先一步进行初始化,则当前线程等待
            if ((sc = sizeCtl) < 0)
                Thread.yield(); 
            // CAS比较成功,设置 sizeCtl =-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;
                        // 设置新的sizeCtrl 为新容量的0.75
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
                break;
            }
        }
	
		private final void addCount(long x, int check) {
	        CounterCell[] as; long b, s;
	        // counterCells不为空,或者 baseCount 设置失败,说明线程竞争比较激烈
	        if ((as = counterCells) != null ||
	            !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
	            CounterCell a; long v; int m;
	            // true表示无竞争
	            boolean uncontended = true;
	            // counterCells不存在或者分段长度<0,或分段不存在,或更新分段失败
	            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;
	            // 数量大于sizeCtl,小于最大值,则进行扩容
	            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;
	                    // 扩容线程+1,执行扩容    
	                    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);
	                s = sumCount();
	            }
	        }
	    }
       
       private final void fullAddCount(long x, boolean wasUncontended) {
	        int h;
	        // 随机值
	        if ((h = ThreadLocalRandom.getProbe()) == 0) {
	            ThreadLocalRandom.localInit();      
	            h = ThreadLocalRandom.getProbe();
	            wasUncontended = true;
	        }
	        // 是否碰撞
	        boolean collide = false;                
	        for (;;) {
	            CounterCell[] as; CounterCell a; int n; long v;
	            // 当前counterCells已经初始化过
	            if ((as = counterCells) != null && (n = as.length) > 0) {
	            	// 当前分区counterCell不存在
	                if ((a = as[(n - 1) & h]) == null) {
	                	// 其他线程没有进行扩容操作
	                    if (cellsBusy == 0) {          
	                    	// 创建新的分区
	                        CounterCell r = new CounterCell(x); 
	                        // 再次判断是否有其他分区进行扩容,设置当前线程进行扩容
	                        if (cellsBusy == 0 &&
	                            U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
	                            boolean created = false;
	                            try {             
	                                CounterCell[] rs; int m, j;
	                                // 再次检查
	                                if ((rs = counterCells) != null &&
	                                    (m = rs.length) > 0 &&
	                                    rs[j = (m - 1) & h] == null) {
	                                    rs[j] = r;
	                                    created = true;
	                                }
	                            } finally {
	                                cellsBusy = 0;
	                            }
	                            // 创建分区成功退出循环
	                            if (created)
	                                break;
	                            continue;          
	                        }
	                    }
	                    collide = false;
	                }
	                else if (!wasUncontended)       // CAS already known to fail
	                    wasUncontended = true;      // Continue after rehash
	                // CAS更新该分区的值   
	                else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
	                    break;
	                else if (counterCells != as || n >= NCPU)
	                    collide = false;            // At max size or stale
	                else if (!collide)
	                    collide = true;
	               	// counterCell未进行初始化或扩容,更新cellsBusy成功
	                else if (cellsBusy == 0 &&
	                         U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
	                    try {
	                    	// 扩容counterCells 
	                        if (counterCells == as) {
	                            CounterCell[] rs = new CounterCell[n << 1];
	                            for (int i = 0; i < n; ++i)
	                                rs[i] = as[i];
	                            counterCells = rs;
	                        }
	                    } finally {
	                        cellsBusy = 0;
	                    }
	                    collide = false;
	                    continue;                   // Retry with expanded table
	                }
	                h = ThreadLocalRandom.advanceProbe(h);
	            }
	            // counterCell未进行初始化或扩容,更新cellsBusy成功
	            else if (cellsBusy == 0 && counterCells == as &&
	                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
	                boolean init = false;
	                try {                           
	                	// 初始化counterCell0s,初始化完成退出循环 
	                    if (counterCells == as) {
	                        CounterCell[] rs = new CounterCell[2];
	                        rs[h & 1] = new CounterCell(x);
	                        counterCells = rs;
	                        init = true;
	                    }
	                } finally {
	                    cellsBusy = 0;
	                }
	                if (init)
	                    break;
	            }
	            // 竞争不激烈,直接更新BASECOUNT
	            else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
	                break;                          // Fall back on using base
	        }
	    }

4. helpTransfer和transfer扩容方法

		final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
	        Node<K,V>[] nextTab; int sc;
	        // 当前桶转移完成,总的扩容未完成
	        if (tab != null && (f instanceof ForwardingNode) &&
	            (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
	            // 获取扩容邮戳
	            int rs = resizeStamp(tab.length);
	            while (nextTab == nextTable && table == tab &&
	                   (sc = sizeCtl) < 0) {
	                // 校验扩容是否完成了   
	                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
	                    sc == rs + MAX_RESIZERS || transferIndex <= 0)
	                    break;
	                // 扩容线程+1,并进行扩容   
	                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
	                    transfer(tab, nextTab);
	                    break;
	                }
	            }
	            return nextTab;
	        }
	        return table;
	    }

		private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
	        int n = tab.length, stride;
	        // 计算转移分组长度
	        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
	            stride = MIN_TRANSFER_STRIDE;
	      	// 初始化新数组长度    
	        if (nextTab == null) {          
	            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;
	                }
	                // 当前线程扩容完成线程数-1
	                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
	                }
	            }
	            // 当前桶没有数据,设置当前处于完成状态
	            else if ((f = tabAt(tab, i)) == null)
	                advance = casTabAt(tab, i, null, fwd);
	           	//   当前已处于完成状态
	            else if ((fh = f.hash) == MOVED)
	                advance = true; // already processed
	            else {
	                synchronized (f) {
	                    if (tabAt(tab, i) == f) {
	                        Node<K,V> ln, hn;
	                        // 链表元素的转移
	                        if (fh >= 0) {
	                            int runBit = fh & n;
	                            Node<K,V> lastRun = f;
	                            // lastRun 是表示从该节点后面不需要特殊处理的首个节点
	                            for (Node<K,V> p = f.next; p != null; p = p.next) {
	                                int b = p.hash & n;
	                                if (b != runBit) {
	                                    runBit = b;
	                                    lastRun = p;
	                                }
	                            }
	                            // 判断lastRun是低位链表还是高位链表
	                            if (runBit == 0) {
	                                ln = lastRun;
	                                hn = null;
	                            }
	                            else {
	                                hn = lastRun;
	                                ln = null;
	                            }
	                            // 遍历链表,(ph & n) == 0放入低位链表
	                            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);
	                            // 设置当前链表迁移完成
	                            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);
	                            setTabAt(tab, i, fwd);
	                            advance = true;
	                        }
	                    }
	                }
	            }
	        }
	    }

5. remove移除

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

	final V replaceNode(Object key, V value, Object cv) {
		// 获取hash值
        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;
                                        // value不为null 替换值
                                        if (value != null)
                                            e.val = value;
                                        // 前置节点不为null,则删除当前节点    
                                        else if (pred != null)
                                            pred.next = e.next;
                                        else
                                        // 前置节点为null,则设置下一个节点首节点
                                            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;
                                     // value不为null 替换值
                                    if (value != null)
                                        p.val = value;
                                    // 移除节点    
                                    else if (t.removeTreeNode(p))
                                        setTabAt(tab, i, untreeify(t.first));
                                }
                            }
                        }
                    }
                }
                // 找到元素,移除,并减少数量
                if (validated) {
                    if (oldVal != null) {
                        if (value == null)
                            addCount(-1L, -1);
                        return oldVal;
                    }
                    break;
                }
            }
        }
        return null;
    }

6. get获取元素

	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;
            }
            // 小于0表示红黑树或者正在扩容
            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;
    }

7. size大小

ConcurrentHashMap的容量等于basecount+各个CounterCell之和。

	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;
        long sum = baseCount;
        if (as != null) {
            for (int i = 0; i < as.length; ++i) {
                if ((a = as[i]) != null)
                    sum += a.value;
            }
        }
        return sum;
    }

三.总结

ConcurrentHashMap 是HashMap 的线程安全版本,根据源码可知采用CAS+自旋来保证线程安全。
为了提高效率采用分段锁的思想,多线程协助扩容。

猜你喜欢

转载自blog.csdn.net/qq_34789577/article/details/107593972
今日推荐