put方法
final V putVal(K key, V value, boolean onlyIfAbsent) {
//如果key与value为空,直接抛出异常
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
if (tab == null || (n = tab.length) == 0)
tab = initTable()
//如果要插入的元素所在的桶还没有元素,则把这个元素插入到桶中
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
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f)
else {
V oldVal = null
//利用分段锁的思想锁住桶
synchronized (f) {
if (tabAt(tab, i) == f) {
//fh>0表示利用链表的方式存储
if (fh >= 0) {
binCount = 1
for (Node<K,V> e = f
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) {
//如果某个桶中的元素大于8个,则尝试树化
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i)
if (oldVal != null)
return oldVal
break
}
}
}
//元素数量加1
addCount(1L, binCount)
return null
}
//初次放入元素,进行初始化table
private final Node<K,V>[] initTable() {
Node<K,V>[] tab
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)
//执行yield让出cpu资源
Thread.yield()
//如果把sizeCtl原子更新为-1成功,则当前线程进入初始化
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
//再次检查,双重检验机制
if ((tab = table) == null || tab.length == 0) {
//默认创建的数组大小为16
int n = (sc > 0) ? sc : DEFAULT_CAPACITY
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n]
table = tab = nt
//设置扩容因子为0.75n
sc = n - (n >>> 2)
}
} finally {
//将扩容门槛赋值为sizeCtl
sizeCtl = sc
}
break
}
}
return tab
}
```
~~~