ConcurrentHashMap源码级解析及知识点总结

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

计算hash的方法变成了这个,hash与左移16位后的hash进行异或操作,是为了参与高位hash的参与感,因为这个spread的返回值会与table的长度进行&操作,table的长度很多时候较小,因此只在低位有。后面与HASH_BITS按位与操作,是为了让最高位为0,保证是正数。HASH_BITS是最大的正数,首位为0.HashMap的hash() - Black_Knight - 博客园

sizeCtl:Table initialization and resizing control. When negative, the table is being initialized or resized: -1 for initialization, else -(1 + the number of active resizing threads). Otherwise, when table is null, holds the initial table size to use upon creation, or 0 for default. After initialization, holds the next element count value upon which to resize the table.

意思就是如果为负值,则表正在初始化或调整大小:-1用于初始化,否则-(1+活动调整大小线程的数量)。初始化后,保存下一个要调整表大小的元素计数值。

说一下最重要的putval()方法:

首先判断key与value是否为null,是的话直接抛出空指针异常。

final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
    int hash = spread(key.hashCode());
    int binCount = 0;
    for (Node<K,V>[] tab = table;;) {
        Node<K,V> f; int n, i, fh;
        //如果tab是空的,则会初始化数组,这里的初始化数组只允许一个线程去初始化。具体在下方解释
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
        //如果tab数组的该位置为null,则可以直接进行cas的put操作,不用加锁,因为如果失败会去到外层再次循环
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            //cas操作
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
        //hash值为-1,说明此节点正在迁移,helpTransfer即帮助迁移。
        else if ((fh = f.hash) == MOVED)
//https://blog.csdn.net/lxsxkf/article/details/109161528//https://blog.csdn.net/u010285974/article/details/106301101
            tab = helpTransfer(tab, f);
        else {
            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;
                        }
                    }
                }
            }
            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) {
            //发现为-1时,说明其他线程正在进行扩容,等待即可
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
               //这里通过cas的方法设置SIZECTL为-1,这样其他线程在上一个if就会进入循环等待数组创建完成。
            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;
    }

先写到这

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值