https://www.cnblogs.com/shihaiming/p/11399472.html
https://blog.csdn.net/programmer_at/article/details/79715177
数据结构
JDK1.8
结构与HashMap类似
transient volatile Node<K,V>[] table;private transient volatile Node<K,V>[] nextTable; // 扩容时新的数组static class Node<K,V> implements Map.Entry<K,V> {final int hash;final K key;volatile V val;volatile Node<K,V> next;}
核心方法
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();
// 计算hash槽位,为空则直接使用CAS插入
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
// 如果在扩容,当前线程协助迁移一个桶的数据
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
// 存在hash碰撞
V oldVal = null;
// 同步锁对象为桶的第一个元素
synchronized (f) {
// 再次检查首元素是否有被修改,如果有则继续自旋
if (tabAt(tab, i) == f) {
// firstHash>=0, 判断为链表
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)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
// 尝试扩容
addCount(1L, binCount);
return null;
}
get()
与HashMap类似
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
扩容
- 当链表超过8个时,会尝试树化
- 转换红黑树前,会检查table长度是否大于64
- 如果不是先扩容到table的两倍
- 创建新的数组,扩容时会尝试给原节点添加ForwardingNode代表已经处理过了
