【原理/Java容器】简单理解ConcurrentHashMap源码

1 putVal(K, V, boolean)

向ConcurrentHashMap中放值都会走这个方法。

final V putVal(K key, V value, boolean onlyIfAbsent) {
		> ConcurrentHashMap中的key和value不允许为null
        if (key == null || value == null) throw new NullPointerException();
        
        > 根据key计算要插入的hash(spread方法见第2节)
		int hash = spread(key.hashCode());

		> 用于统计桶内的结点数量
        int binCount = 0;

		> 在这里自旋,获取当前的桶数组
        for (Node<K,V>[] tab = table;;) {

			> n -> 数组长度,i -> 计算出的要插入的桶的索引,fh -> 桶头结点哈希值
            Node<K,V> f; int n, i, fh;

			> 如果桶数组为空或者长度为0,初始化桶数组,见第3if (tab == null || (n = tab.length) == 0)
                tab = initTable();

			> {i = (n - 1) & hash} -> {hash % n},计算桶索引。f获取这个位置的Node
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {

				> 如果这个位置的Node为空,创建新的NodeCAS进行替换
				> casTabAt(数组, i, 2, 3) ->CAS将数组中i位置的数据从2修改为3
                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 (f) {

					> 再次获取i位置的桶的头结点判断是否没有更换,更换就进入下次循环
                    if (tabAt(tab, i) == f) {

						> 【if0(方便对应下面else if)】头结点哈希值非负,说明是链表或者为空
                        if (fh >= 0) {

							> 桶结点数量设置为1
                            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;
                                    
                                    > 判断是否是缺失时才put,在putIfAbsent(..)方法调用
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                
                                > 判断当前遍历到的Node的next是不是null,如果是就挂一个新Node,否则继续遍历
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) {
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }

						> 【if0】或者是红黑树
                        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;
                            }
                        }
                    }
                }
                if (binCount != 0) {
					
					> 插入后桶内结点数量达到树化阈值8,判断是否要转红黑树,见第4if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                        
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }
... ...

2 spread(int)

用于二次哈希提高均匀性,传入了key.hashcode()。右移位16位让int类型的高16位与低16位异或,尽可能打散哈希值。
HASH_BITS是最大整型值,01111111 11111111 11111111 11111111,相与完保证hash为正,负数有特殊含义。

static final int spread(int h) {
    return (h ^ (h >>> 16)) & HASH_BITS;
}

3 initTable

用于初始化桶数组。

private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;

    > 自旋判断数组是否还未初始化
    while ((tab = table) == null || tab.length == 0) {

		> {sizeCtl < -1} -> 正在扩容,-2表示有1个线程正在扩容,-3表示2> {sizeCtl == -1} -> 数组正在初始化
		> {sizeCtl == 0} -> 还没有初始化
		> {sizeCtl > 0} -> 没初始化就是要初始化的长度,否则是扩容阈值

		> sizeCtl小于0表示正在扩容或者正在初始化,让出资源进入下一次循环。sc为当前sizeCtl
        if ((sc = sizeCtl) < 0) 
            Thread.yield(); // lost initialization race; just spin

		> sizeCtl大于等于0表示开始初始化过程,CAS替换SIZECTL-1,大写的SIZECTL表示sizeCtl在对象中的偏移量
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
            try {
				
				> 再次判断,防止sizeCtl修改为非负之后其他线程进来在此创建
                if ((tab = table) == null || tab.length == 0) {

					> 如果sc>0,数组初始化长度设置为sc;否则16
                    int n = (sc > 0) ? sc : DEFAULT_CAPACITY;

					> 创建桶数组
                    @SuppressWarnings("unchecked")
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    table = tab = nt;

					> 获取下一次扩容阈值,相当于{n - n/4} -> {0.75n}
                    sc = n - (n >>> 2);
                }
            } finally {
            	> 将sc赋值给成员变量sizeCtl
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

4 treeifyBin(Node<K, V>[], int)

private final void treeifyBin(Node<K,V>[] tab, int index) {
   Node<K,V> b; int n, sc;
    if (tab != null) {
    	> 获取桶数组长度是否小于64,是则先扩容。因为在数组中查找比红黑树更快,尽量先尝试打散
        if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
        	
        	> 扩容数组,见第5tryPresize(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));
                }
            }
        }
    }
}

5 tryPresize(int)

private final void tryPresize(int size) {
	> 传入值size为当前数组长度 * 2
	> 根据size计算扩容要求c。如果size达到最大容量2^30的一半,那就取最大容量;
	> 否则计算新容量tableSizeFor(1.5*size+1),找到大于等于{1.5倍size+1}的最小的2的幂
    int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
        tableSizeFor(size + (size >>> 1) + 1);
    
    int sc;

	> 桶数组不一定已经初始化,putAll(..)会直接先执行tryPresize(..)
    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;
                }
            }
        }

		> c小于等于扩容阈值,或者已经数组长度已经最大了,表明不需要扩容,直接break
        else if (c <= sc || n >= MAXIMUM_CAPACITY)
            break;
            
        > 开始扩容
        else if (tab == table) {
        	> rs为扩容戳,记录本次扩容的标识。如果开始扩容会用于替换sizeCtl的高16位,后16位表示扩容线程数
            int rs = resizeStamp(n);
            
            > 已经开始扩容了,判断是否可以帮助扩容
            if (sc < 0) {
                Node<K,V>[] nt;

				> 如果sc右移16位后不等于rs,说明当前的扩容状态已经改变,不是同一次扩容,那么当前线程就不能参与扩容;
				> 如果sc等于rs+1,说明已经扩容完成,那么当前线程就不能参与扩容;
				> 如果sc等于rs+MAX_RESIZERS,说明已经达到了最大的扩容线程数,那么当前线程就不能参与扩容;
				> 如果nt为空,说明还没有初始化nextTable,那么当前线程就不能参与扩容;
				> 如果transferIndex小于等于0,说明已经没有剩余的数组元素需要迁移,那么当前线程就不能参与扩容。
                if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                    sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
                    transferIndex <= 0)
                    break;
                
                > 否则就帮助扩容,增加sc表示多了一个扩容线程
                if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
                    transfer(tab, nt);
            }

			> 没有线程扩容,先设置sizeCtl标记,开始扩容
            else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                         (rs << RESIZE_STAMP_SHIFT) + 2))
                transfer(tab, null);
        }
    }
}

附录

要想调试测试扩容建议key自己写一个类,比如这样:

public class ConcurrentHashMapTest {
    static class Key {

        int hashcode;
        public Key(int hashcode) {
            this.hashcode = hashcode;
        }

        @Override
        public int hashCode() {
            return hashcode;
        }
    }

    public static void main(String[] args) {
        ConcurrentHashMap<Key, Integer> map = new ConcurrentHashMap<>();
        map.put(new Key(1), 1);
        map.put(new Key(1), 2);
        map.put(new Key(1), 3);
        map.put(new Key(1), 4);
        map.put(new Key(1), 5);
        map.put(new Key(1), 6);
        map.put(new Key(1), 7);
        map.put(new Key(1), 8);
        map.put(new Key(1), 9);
    }
}

这样它们就都会加在table[1]的位置上,方便看扩容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值