Hash冲突
- 线性探索(开放寻址法,i->i+1->i+2,比如ThreadLocal
- 链式地址法
- 再Hash法
- 公共溢出区
put()
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;
if (tab == null || (n = tab.length) == 0)
tab = initTable(); //初始化table
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))//尝试CAS直接存值,注意底层是volatile的取
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED) //注意这里fh已被赋值,即使if条件不满足
tab = helpTransfer(tab, f); //多线程并发扩容,f作为分界点。fh是标志
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) //如果链表大于等于8,且当前table表的容量大于等于64
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount); //统计个数
return null;
}
initTable()
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) { //把成员变量赋给局部变量,操作局部变量更快,因为成员变量在堆中,局部变量在栈中
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { //SIZECTL作为标志位,-1表示正在初始化表。CAS保证了只有一条线程进来
try {
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;