concurrentMap源码阅读

本文深入探讨了并发Map的特性和ConcurrentHashMap的实现细节,包括其线程安全性和原子性的保证,不允许null值的特性,以及使用Unsafe类进行同步的原理。通过源码阅读,解析了迭代器使用、集合状态检测、同步机制和调整table体积等关键操作。
摘要由CSDN通过智能技术生成

concurrentMap源码阅读理解

特性:

  • 保证了线程安全性和原子性
  • 线程加入对象的操作优先于线程获取和删除对象的操作
  • 不允许加入为null的value,因此其实现类若需要允许value为null的特性,需要重载方法

concurrentMap定义了Map的基本操作,但未实现线程安全性和原子性,交由其实现类实现;因此我们需要阅读其实现类的源码,典型的就是concurrentHashMap类。

concurrentHashMap源码阅读理解

特性:

  • 迭代器只能同时被一个线程使用
  • 集合状态检测方法如{@code size}, {@code isEmpty}, and {@code containsValue}只能在其他线程没有操作该集合的情况下才能用于程序控制
  • 不允许key或value为null

同步原理:使用了Unsafe类来实现同步。

Unsafe类在jdk 源码的多个类中用到,这个类的提供了一些绕开JVM的更底层功能,基于它的实现可以提高效率。但是,它是一把双刃剑:正如它的名字所预示的那样,它是Unsafe的,它所分配的内存需要手动free(不被GC回收)。Unsafe类,提供了JNI某些功能的简单替代:确保高效性的同时,使事情变得更简单。[参考链接:https://www.cnblogs.com/suxuan/p/4948608.html]

	//内置table元素具有volatile性质
    static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
    }

    static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
        U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
    }

	//使用CAS操作更新table元素
    static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
                                        Node<K,V> c, Node<K,V> v) {
        return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
    }

使用了Unsafe类方法的同步方法实现跟踪:

	//代码一
	/**
	 * Moves and/or copies the nodes in each bin to new table. See
	 * above for explanation.
	 */
	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; // 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;
	            }
		//使用了Unsafe的CAS操作方法
	            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;
	            }
				//使用了Unsafe的CAS操作方法
	            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
	            }
	        }
			使用了Unsafe中获取volatile元素的方法
	        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;
	                        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);
	                        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;
	                    }
	                }
	            }
	        }
	    }
	}

	//代码二
	public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
	    if (key == null || mappingFunction == null)
	        throw new NullPointerException();
	    int h = spread(key.hashCode());
	    V val = null;
	    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) & h)) == null) {
	            Node<K,V> r = new ReservationNode<K,V>();
				//同步锁
	            synchronized (r) {
	                if (casTabAt(tab, i, null, r)) {
	                    binCount = 1;
	                    Node<K,V> node = null;
	                    try {
	                        if ((val = mappingFunction.apply(key)) != null)//根据参数方法计算value
	                            node = new Node<K,V>(h, key, val, null);
	                    } finally {
	                        setTabAt(tab, i, node);
	                    }
	                }
	            }
	            if (binCount != 0)
	                break;
	        }
	        else if ((fh = f.hash) == MOVED)
	            tab = helpTransfer(tab, f);
	        else {
	            boolean added = false;
	            synchronized (f) {
	                if (tabAt(tab, i) == f) {
	                    if (fh >= 0) {
	                        binCount = 1;
	                        for (Node<K,V> e = f;; ++binCount) {
	                            K ek; V ev;
	                            if (e.hash == h &&
	                                ((ek = e.key) == key ||
	                                 (ek != null && key.equals(ek)))) {
	                                val = e.val;
	                                break;
	                            }
	                            Node<K,V> pred = e;
	                            if ((e = e.next) == null) {
	                                if ((val = mappingFunction.apply(key)) != null) {
	                                    added = true;
	                                    pred.next = new Node<K,V>(h, key, val, null);
	                                }
	                                break;
	                            }
	                        }
	                    }
	                    else if (f instanceof TreeBin) {
	                        binCount = 2;
	                        TreeBin<K,V> t = (TreeBin<K,V>)f;
	                        TreeNode<K,V> r, p;
	                        if ((r = t.root) != null &&
	                            (p = r.findTreeNode(h, key, null)) != null)
	                            val = p.val;
	                        else if ((val = mappingFunction.apply(key)) != null) {
	                            added = true;
	                            t.putTreeVal(h, key, val);
	                        }
	                    }
	                }
	            }
	            if (binCount != 0) {
	                if (binCount >= TREEIFY_THRESHOLD)
	                    treeifyBin(tab, i);
	                if (!added)
	                    return val;
	                break;
	            }
	        }
	    }
	    if (val != null)
	        addCount(1L, binCount);
	    return val;
	}

调整table体积:

	 private final void tryPresize(int size) {
        int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
            tableSizeFor(size + (size >>> 1) + 1);
        int sc;
        while ((sc = sizeCtl) >= 0) {
            Node<K,V>[] tab = table; int n;
            if (tab == null || (n = tab.length) == 0) {
                n = (sc > c) ? sc : c;
                if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                    try {
                        if (table == tab) {
                            @SuppressWarnings("unchecked")
                            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                            table = nt;
                            sc = n - (n >>> 2);
                        }
                    } finally {
                        sizeCtl = sc;
                    }
                }
            }
            else if (c <= sc || n >= MAXIMUM_CAPACITY)
                break;
            else if (tab == table) {
                int rs = resizeStamp(n);
                if (sc < 0) {
                    Node<K,V>[] nt;
                    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);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值