ConcurrentHashMap源码分析_1.8

1.重要成员变量

  • table:默认为null,初始化发生在第一次put操作,默认大小为16的数组,用来存储Node节点数据,扩容时大小总是2的幂次方。
  • sizeCtl:默认为0,用来控制table的初始化和扩容操作
              -1 代表table正在初始化
              -N 表示有N-1个线程正在进行扩容操作
          其余情况
          1)如果table未初始化,表示table需要初始化的大小。
          2)如果table初始化完成,表示table的容量,默认是table大小的0.75倍

2.put

  1. 第一次 put 的时候,进行 map 的初始化(initTable())
  2. 如果当前位桶为空,那么使用 cas 的方式,把元素放到槽位中
  3. 如果出现桶位冲突(参考博客原文叫 hash 冲突,其实不严谨,可能 hash 不冲突,但是 hash 值对 table.length 取余的值冲突,即这两个键值对要放到一个桶位当中),则使用 synchronized 保证并发安全。
  4. 如果当前map正在扩容f.hash == MOVED, 则跟其他线程一起进行扩容:helpTransfer,扩容完毕后再根据 for 循环回来再次执行2、3步

代码1

    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();
        }
        //获取到 key 的hash 值
        int hash = spread(key.hashCode());
        int binCount = 0;
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            //一、如果 table 是null,那么初始化 tab,初始化完之后继续自旋,去执行 else if或者 else 的逻辑,直到跳出
            if (tab == null || (n = tab.length) == 0){
            //代码2
                 tab = initTable();
            }
            
            //二、如果当前桶位是  null
            //1.tabAt(tab, i = (n - 1) & hash))  拿到 当前 key 的 hash 在 table 中对应位桶中第一个元素  使用 f 指向
            //2.判断当前位桶的第一个元素是 null
            //tabAt:代码3
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                //casTabAt:代码3 
                //通过 cas  方式把 new 出来的新的 node放到当前位桶的第一个元素上面。放完之后 跳出此次循环。
                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);
                
            //四、如果 hash 冲突    
            else {
                V oldVal = null;
                //synchronized 锁链表
                synchronized (f) {
                    //拿到当前位桶的第一个元素  和  上面 拿到的当前位桶的第一个元素做比较???这一步在预防什么  没看懂
                    if (tabAt(tab, i) == f) {
                    //如果 f 的 hash 值 >= 0。(当此位桶目前是单链表时。如果 f的)
                        if (fh >= 0) {
                            binCount = 1;
                            //执行了 e = f,e 就是当前位桶的头结点
                            for (Node<K,V> e = f;; ++binCount) {
                                //如果新 put 的 key  和 链表中的当前的元素是同一个 key,那么把以前的 val 替换
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                
                                //移动指针。再次循环,如果 key 和当前元素 key 相同那么走上面的逻辑。否则就走到链表末尾,尾插法把元素插进去
                                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;
                            }
                        }
                    }
                }
                //判断当前位桶 元素个数,如果超过8,那就考虑扩容了
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        // 统计节点个数,检查是否需要resize
        addCount(1L, binCount);
        return null;
    }

初始化 table

实例化ConcurrentHashMap时倘若声明了table的容量,在初始化时会根据参数调整table大小,确保table的大小总是2的幂次方。默认的table大小为16.
代码2

    private final Node<K,V>[] initTable() {
        //使用 sc 的好处。留住 sizeCtl 的值,sizeCtr 去做具体的控制 size 的作用
        Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {
            //当sizeCtl == -1时,说明正在做初始化的动作(见U.compareAndSwapInt(this, SIZECTL, sc, -1))。那么其他线程自旋
            if ((sc = sizeCtl) < 0){
                Thread.yield(); // lost initialization race; just spin(失去初始化的资格,只是自旋)
            }
            //通过 cas 替换sizeCtl的值从 sc --> -1,返回 true 替换成功,返回 false 说明已经有其他线程初始化了。那么此次初始化不生效
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                    //再加个判断更加严谨
                    if ((tab = table) == null || tab.length == 0) {
                        //sc 即sizeCtl。如果初始没有指定容量,那么sc == 0,使用默认的容量
                        int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                        @SuppressWarnings("unchecked")
                        //新建 node 数组
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = tab = nt;
                        //0.75*capacity
                        
                        sc = n - (n >>> 2);
                    }
                } finally {
                    //此时 sizeCtl 又变成 扩容阈值
                    sizeCtl = sc;
                }
                break;
            }
        }
        return tab;
    }

设置 compareAndSwapInt 的偏移量

    // Unsafe mechanics
    private static final sun.misc.Unsafe U;
    private static final long SIZECTL;
    private static final long TRANSFERINDEX;
    private static final long BASECOUNT;
    private static final long CELLSBUSY;
    private static final long CELLVALUE;
    private static final long ABASE;
    private static final int ASHIFT;

    static {
        try {
            U = sun.misc.Unsafe.getUnsafe();
            Class<?> k = ConcurrentHashMap.class;
            SIZECTL = U.objectFieldOffset
                (k.getDeclaredField("sizeCtl"));
            TRANSFERINDEX = U.objectFieldOffset
                (k.getDeclaredField("transferIndex"));
            BASECOUNT = U.objectFieldOffset
                (k.getDeclaredField("baseCount"));
            CELLSBUSY = U.objectFieldOffset
                (k.getDeclaredField("cellsBusy"));
            Class<?> ck = CounterCell.class;
            CELLVALUE = U.objectFieldOffset
                (ck.getDeclaredField("value"));
            Class<?> ak = Node[].class;
            ABASE = U.arrayBaseOffset(ak);
            int scale = U.arrayIndexScale(ak);
            if ((scale & (scale - 1)) != 0)
                throw new Error("data type scale not a power of two");
            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
        } catch (Exception e) {
            throw new Error(e);
        }
    }

三个核心方法

ConcurrentHashMap定义了三个原子操作,用于对指定位置的节点进行操作。正是这些原子操作保证了ConcurrentHashMap的线程安全。
代码3

@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);
    }

    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);
    }

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

3.扩容 or 变红黑树

  1. 如果有一个位桶元素个数超过8,那么就要考虑进行扩容。
  • table 元素 < 64就进行扩容,且容量一次性扩容到 (table.length) << 3 ,会扩容到原容量的8倍,此处和 hashmap 是不一样的;
  • table 元素 >= 64 转为红黑树
private final void treeifyBin(Node<K,V>[] tab, int index) {
    Node<K,V> b; int n, sc;
    if (tab != null) {
        // n:当前 tab 的长度
        //一、如果当前元素是小于 MIN_TREEIFY_CAPACITY(64),那么 容量会扩展到  128
        if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
            //p2322
            //size 先扩大 1 倍
            tryPresize(n << 1);
            
        //二、否则 变红黑树    
        else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
            synchronized (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;
                    }
                    setTabAt(tab, index, new TreeBin<K,V>(hd));
                }
            }
        }
    }
}


//p2322
//尝试调整表的大小,以容纳给定的元素数量
private final void tryPresize(int size) {
    //如果当前的容量超过了 最大容量的一半,那么此次扩容就扩到最大容量。否则容量就扩大一倍
    // c :这个变量的值控制使得transfer(tab, null);执行了三次,所以就把容量扩大了 8倍。博客评论说 jdk11有改进,改为了 tableSizeFor(size + (size >>> 1) + 1)*0.75
    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;
        //n 为 table 的当前的容量,sc 为 sizeCtl,c 为table扩容后的容量
        
        //一、当是 table 初始化
        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;
                }
            }
        }
        //二、当表的容量 达到最大值 跳出循环不再扩容
        //****** 就是因为在这里根据 c 控制的,使得 transfer(tab, null) 会执行两次。影响就是扩容不是 table.length < 1  而是  table.length < 2;
        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);
            }
            //把 sizectl 变为 一个绝对值很大的负数,不明白
            else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                         (rs << RESIZE_STAMP_SHIFT) + 2))
                //p2367
                transfer(tab, null);
        }
    }
}

//p2367
//跟代码得知,此一步 对 table 扩容了两倍,但是对于元素超过 8 的位桶未进行转化 红黑树
    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        //n 是老 tab的长度
        //stride根据 cpu 取出来的什么玩意。一般是 默认 16
        // nextTable = nextTab = nt 为扩容后的 table
        //nextn:nextTab.length
    
        int n = tab.length, stride;
        //根据 cpu 数什么玩意做判断,本机最后取的是 stride = MIN_TRANSFER_STRIDE; stride = 16;
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
            //创建一个比以前容量大一倍的 table  赋值给nextTable,transferIndex 为原容量大小
        //如果传进来的 nextTab 是 null。新 new 的nextTab 默认 是 table 的2倍
        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 循环  会把 tab 循环两次。
        //第一次 操作数据
        //第二次 检查 tab 中是否还有数据
        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;
                }
                //第一次进来 寻找边界,并把需要循环的 位桶下标拿出来: i = nextIndex - 1;   
                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 = true。使得第二次检查 table 后就进入第一个 if 中设置好 table  sizeCtl  来 返回。第二个  if 使用了 cas 来保证多线程安全
                
                
                //第二次检查完数据  把 table 指向新 table,sizeCtl 设置好
                //第一个 if
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                // 第二个 if
                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                        return;
                    finishing = advance = true;
                    // 重新给 i 赋值,使程序再一次对 table 检查一遍
                    i = n; // recheck before commit
                }
            }
            //二、   如果遍历到的节点为空 则放入ForwardingNode指针 
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
             //三、   如果遍历到ForwardingNode节点  说明这个点已经被处理过(可能是其他线程已经处理过)了 直接跳过  这里是控制并发扩容的核心  
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
                
            //四、    如果当前位桶有元素,那么加 synchronized 锁 来倒腾元素    
            else {
                synchronized (f) {
                    //做此判断 是为了 在多线程时做判断
                    //如果 tabAt(tab, i) == f   true 说明 其他线程没处理过这个桶的数据。如果false  说明其他线程处理过了, 当前线程就无需再处理了
                    
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        //链表的处理方法
                        if (fh >= 0) {
                            //****此if 中大段的代码主要作用是把原当前位桶中的链表元素按照 hash&tab.length 是否是0,来分成两个链表(链表顺序大部分是按之前链表的倒排序,为什么是大部分?因为使用了头插法所以是倒排序,但是lastRun会直接插在最后)
                                //1.第一个 for 循环 是找到原链表末尾hash&tab.length 值相同的几个元素的开始点。如:某个位桶中的元素 hash&tab.length 值如下(上面一组是 元素的序号,下面是一组是hash&tab.length 的值)
                                //     1,2, 3,4,5, 6, 7,8,9,10
                                //     0,0,16,0,16,16,0,0,0,0
                                //     那么这个 for 要寻找的就是 序号为 7 的这个元素
                                
                                //2.第二 for 循环作用是拼链表,如第一个 for 举例的数据最后会拼装成如下两个链表
                                //  hash&tab.length == 0:
                                //      4,2,1,7,8,9,10
                                //  hash&tab.length != 0:    
                                //      6,5,3
                            //加第一个 for 循环的目的好处就是 如果 7号元素后面有大量的元素都是hash&tab.length == 0 的元素,那么第二个 for 循环会大大的减少循环次数
                        
                            //当前元素的  hash & table 长度。为0则放到原位桶,不为0则向下移动  原 table.length 的位桶中
                            //第一个元素的 与值判零 
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                            //第一个 for 循环
                            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 循环
                            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);
                            }
                            //cas 方式 把两个链表放到 nextTab 中
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            //原 tab 的位桶用 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);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                    }
                }
            }
        }
    }

知识点补充

sun.misc.Unsafe.compareAndSwapInt的用法

import sun.misc.Unsafe;
import java.lang.reflect.Field;

public class UnsafeExample {
    static Unsafe U;
    int x = 2;
    int y = 8;

    static {
        Field f = null;
        try {
            /* 我所使用的jdk8上是theUnsafe */
            f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            U = (Unsafe) f.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Throwable{
        long offset = U.objectFieldOffset(UnsafeExample.class.getDeclaredField("x"));

        UnsafeExample example = new UnsafeExample();
        boolean ret;
        //如果x==2, 则执行x=3, 返回true
        ret = U.compareAndSwapInt(example, offset, 2, 3);
        System.out.println("offset: "+offset+", ret: "+ret+", x: "+example.x);

        //如果x==4, 则执行x=5.  实际上x==3, 不成立, 赋值失败, 返回false
        ret = U.compareAndSwapInt(example, offset, 4, 5);
        System.out.println("offset: "+offset+", ret: "+ret+", x: "+example.x);
    }
}

sun.misc.Unsafe.putObjectVolatile 等方法

public class UnsafePlayerCAS {
    public static void main(String[] args) throws Exception{
        //通过反射实例化Unsafe
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);

        //实例化私有的构造函数
        Player player = (Player) unsafe.allocateInstance(Player.class);
        String name = "jack";
        int age = 19;
        player.setName(name);
        player.setAge(age);
        for (Field field : Player.class.getDeclaredFields()) {
            System.out.println(field.getName() + ":对应的内存偏移地址:"
                    + unsafe.objectFieldOffset(field));
        }
        //上面的输出为 name:对应的内存偏移地址:16
        //age:对应的内存偏移地址:12
        //修改内存偏移地址为12的值(age),返回true,说明通过内存偏移地址修改age的值成功
        System.out.println(unsafe.compareAndSwapInt(player, 12, age, age + 1));
        System.out.println("age修改后的值:" + player.getAge());

        //修改内存偏移地址为12的值,但是修改后不保证立马能被其他的线程看到。
        unsafe.putOrderedInt(player, 12, age + 2);
        System.out.println("age修改后的值:" + player.getAge());

        //修改内存偏移地址为16的值,volatile修饰,修改能立马对其他线程可见
        unsafe.putObjectVolatile(player, 16, "tom");
        System.out.println("name:" + player.getName());
        System.out.println(unsafe.getObjectVolatile(player,16));
    }

    public static class Player{
        @Getter @Setter private String name;
        @Getter @Setter private int age;
        private Player(){}
    }
}

参考:
https://blog.csdn.net/programmer_at/article/details/79715177
https://blog.csdn.net/u010723709/article/details/48007881

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值