这么回答面试官之--ConcurrentHashMap如何put?

ConCurrentHashMap的put操作主要由putVal()方法实现,该方法中对value的插入,采用了CAS操作和synchronized的操作,从而保证了并发环境下的安全性。

put步骤大致如下:

  • 判断key和value是否为null,如果是的话抛出NullPointerException并结束(ConCurrentHashMap不允许存放null型的key和value,这点和HashMap也不同)
  • 通过key计算得到hashcode
  • 判断是否需要进行初始化(初始化的时候没有插入key和value,而是在CAS第2次自旋的时候插入的)(采用了延迟初始化的策略Lazy table initialization minimizes footprint until first use)
  • 利用hash值定位Node,如果当前位置没有Node,则依据CAS机制尝试插入。如果插入失败,则通过自旋保证插入成功
  • 判断是否正在进行扩容,如果需要进行扩容,则执行helpTransfer方法(如果头节点是ForwardingNode类型,则表明正在扩容)
  • 如果是在无需进行初始化,hash值计算得到的位置存在Node,并且无需扩容的情况下,则利用synchronized锁来写入数据(这个过程又会分为在普通链表中put和在红黑树中put)
  • 上述操作后,如果当前数量超过了TREEIFY_THRESHOLD(8,跟HashMap中的值大小相同),则转化为红黑树结构。(注意,上述标蓝的4步,只会执行其中一步)

下面给出了ConCurrentHashMap的初始化的代码,并做了解释,大家需要理解以下sizeCtl字段的含义

《这么回答面试官之--ConcurrentHashMap如何get?为何无需加锁》

探索为什么get操作无需加锁:

https://blog.csdn.net/Elliot_Elliot/article/details/115586562

 

ConCurrentHashMap的put操作的源码如下(含注释):

final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        // 根据key计算出hash code
        int hash = spread(key.hashCode());
        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) {
                // 根据计算得出的hash定位Node的位置,如果为空,则依据CAS机制尝试插入,如果失败,则通过自旋保证成功
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            // 判断是否正在扩容,其它的一些字段如下:
            /*
            MOVED     = -1; // hash for forwarding nodes
            TREEBIN   = -2; // hash for roots of trees
            RESERVED  = -3; // hash for transient reservations
            HASH_BITS = 0x7fffffff; // usable bits of normal node hash
            */
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                // 利用synchronized锁进行写入数据
                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;
                            }
                        }
                    }
                }
                //  如果数量大于TREEIFY_THRESHOLD,则转化为红黑树
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

更多细节:

put过程中,如果tab==null或者是第一次put,会调用initTable()方法 ,具体如下

private final Node<K,V>[] initTable() {
        Node<K,V>[] tab; int sc;
        // 自旋操作
        while ((tab = table) == null || tab.length == 0) {
            // sizeCtl控制table的初始化或者扩容操作
            // 发现正在进行初始化或者扩容操作时,当前线程就停止操作
            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) {
                        
                        // 如果创建的时候指定了容量大小,那么sc是根据指定容量大小得到的值。
                        // sc的大小可能是定义的最大的容量,或者是根据指定容量大小得到的与其最接近的一个2的指数次方的值(具体可以看下面贴的构造方法代码)
                        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;
}

对于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.

大体意思是说:

 sizeCtl控制着table的初始化和扩容。如果sizeCtl是一个负值,说明table正在被初始化或者扩容。其中,sizeCtl=-1表示正在初始化,而sizeCtl<-1时,表明正在进行扩容操作。否则,当table为null时,通过我们指定的大小来初始化,或者默认为0。 初始化后,保留下一个要调整表大小的元素计数值。

ConcurrentHashMap指定容量的构造函数如下:

public ConcurrentHashMap(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        // cap为MAXIMUM_CAPACITY或者为一个2的n次方的值
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
        this.sizeCtl = cap;
}

 

  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的Coder*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值