zoukankan      html  css  js  c++  java
  • 源码分析(4)-ConcurrentHashMap(JDK1.8)

    一、UML类图

     ConcurrentHashMap键值不能为null;

    底层数据结构是数组+链表/红黑树;

    采用CAS和synchronized来保证并发线程安全。

    参考文章:

    CAS文章:https://blog.csdn.net/v123411739/article/details/79561458

    JDK1.7ConcurrentHashMap源码:https://www.cnblogs.com/chengxiao/p/6842045.html

    JDK7采用分段式锁

    二、源码分析

    重要的成员变量: 

    //数组,类似HashMap的table
    transient volatile Node<K,V>[] table;
    //扩容时使用,完成后置空
    private transient volatile Node<K,V>[] nextTable;
    //节点数,类似HashMap的size
    private transient volatile long baseCount;

      2.1、插入

        final V putVal(K key, V value, boolean onlyIfAbsent) {
            if (key == null || value == null) throw new NullPointerException();
            int hash = spread(key.hashCode());//①计算(h ^ (h >>> 16)) & HASH_BITS;
            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) {//Java并发
                    if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null)))//CAS机制,添加节点
                        break;                   // no lock when adding to empty bin
                }
                else if ((fh = f.hash) == MOVED)//元素不为空;检测到桶结点是ForwardingNode类型,协助扩容
                    tab = helpTransfer(tab, f);
                else {//hash桶结点,锁定该桶头结点并在该链表尾部添加一个节点
                    V oldVal = null;
                    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;
                                }
                            }
                        }
                    }
              //binCount==0:新节点成为hash桶头节点
              //binCount!=0:链表或红黑树成功添加或修改一个节点
    if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD)//hash桶节点数量大于8,链表转化为红黑树 treeifyBin(tab, i);//转换红黑树 if (oldVal != null) return oldVal; break; } } } addCount(1L, binCount);//CAS机制更新baseCount并判断是否需要扩容 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(); // lost initialization race; just spin 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; }
    //U是sun.misc.Unsafe类实例对象,Java并发操作底层实现核心类
    //可以参考网上的博客进行了解
    @SuppressWarnings("unchecked") 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);//getObjectVolatile方法强制从主存中获取属性值;红色标记代码:计算偏移量 }
    //查找节点位置
    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); }
    //扩容
    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; if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nextTab); break; } } return nextTab; } return table; }
    //CAS机制更新baseCount并判断是否需要扩容
    private final void addCount(long x, int check) { CounterCell[] as; long b, s; if ((as = counterCells) != null || !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) { CounterCell a; long v; int m; boolean uncontended = true; 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; 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); s = sumCount(); } } }

    2.2、查询 

    //
    public V get(Object key) { Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek; int h = spread(key.hashCode());//(h ^ (h >>> 16)) & HASH_BITS if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) { if ((eh = e.hash) == h) {//hash桶首节点 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; }

    三、总结

    ConcurrentHashMap线程安全实现使用CAS,关于CAS内容需要深入了解(是Java并发实现核心内容)。

  • 相关阅读:
    dir 函数
    模块的 __name__
    from..import 语句
    pass
    可变参数
    python 中的一点新知识
    Numpy中的一点小知识
    使用ipython %matplotlib inline
    numpy.random.rand
    Python:numpy中shape和reshape的用法
  • 原文地址:https://www.cnblogs.com/wangymd/p/12918512.html
Copyright © 2011-2022 走看看