一.put()方法
public V put(K key, V value) {
return putVal(key, value, false);
}
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;
//是不是null或length为0,是就初始化一个tab
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//Node<k,v>是volatile修饰,在保证原子性的前提下能拿到最新的节点
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; // no lock when adding to empty bin
}
//看看当前节点是不是正在被其他线程扩容
else if ((fh = f.hash) == MOVED)
//是的话当前线程就一起帮忙数据迁移
tab = helpTransfer(tab, f);
else {
V oldVal = null;
//当前数组下标下有链表,就synchronized加锁操作
synchronized (f) {
//剩余操作与HashMap操作相似
if (tabAt(tab, i) == f) {
...
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
static final int spread(int h) {
//计算Hash值,为啥&上HASH_BITS是防止Hash值超出0x7fffffff,大致与HashMap的hash计算相似
return (h ^ (h >>> 16)) & HASH_BITS;
}
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
//cas操作Node<K,V>
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
//synchronized下操作
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
//两倍扩容的操作在这里
int rs = resizeStamp(tab.length);
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
//记录扩容后的偏移量,cas操作成功则转移数据
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
//这个操作过程中会将当前链表的节点赋值为ForwardingNode<k,v>对象
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}