put操作
put操作采用CAS(没有hash冲突)+synchronized(hash冲突)实现并发插入或更新操作:
- 如果没有初始化先初始化
- 当前Segment/bucket(桶)为空时,使用CAS操作,将Node放入对应的bucket中。
- 如果当前map正在扩容f.hash == MOVED,先协助扩容,再更新值。
- .出现hash冲突,则采用synchronized关键字: 遍历链表,若找到对应的node节点,则修改node节点的val,否则在链表末尾添加node节点;倘若当前节点是红黑树的根节点,在树结构上遍历元素,更新或增加节点。
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode()); //1.计算kay的hash值,再根据hash通过位置的散列的方式计算出key对应Segment/bucket(桶)的位置
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(); // lazy Initialization
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 当前bucket为空,使用CAS的方式插入数据
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))//CAS的方式插入数据
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED) // 如果当前Map正在扩容,先协助扩容,再更新值。
tab = helpTransfer(tab, f);
else {
//当前bucket为空及发生 hash冲突时,使用 加锁的方式插入数据
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) //链表节点超过了8,链表转为红黑树
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount); // 统计节点个数,检查是否需要resize
return null;
}