ConcurrentHashMap的put方法

源码解析如下:

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

int hash = spread(key.hashCode()); //计算hash值

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(); //初始化数组

//通过hash值对应的数组下标得到第一个节点; 以volatile读的方式来读取table数组中的元素,保证每次拿到的数据都是最新的

else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {

//如果该下标返回的节点为空,则直接通过cas将新的值封装成node插入即可;如果cas失败,说明存在竞争,则进入下一次循环

if (casTabAt(tab, i, null,

new Node<K,V>(hash, key, value, null)))

break; // no lock when adding to empty bin

}

//...

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值