table初始化方法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(); // 讓出處理器的使用權
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
//CAS成功,進行table初始化
try {
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
總結
- 默認table大小爲16,如容量自定義,則table大小固定爲2的n次方,比如自定義容量15,16,17,實際容量32,32,64;
- 擴容閾值爲容量的3/4,sizeCtl設置爲容量的3/4;
擴容
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
//size計數部分,原理類似LongAdder
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
//CAS更新baseCount不成功,轉爲採用CounterCell進行計數
CounterCell a; long v; int m;
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
s = sumCount();
}
//擴容檢查及擴容,如putVal放入的hash槽位無值,不會觸發擴容檢查
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
//檢查當前size是否大於sizeCtl
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n);
if (sc < 0) {
//處於擴容狀態,檢查擴容完畢與否等
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
//當前線程加入擴容處理流程
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
//擴容
transfer(tab, nt);
}
//當前線程首先觸發擴容
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
總結
- 向table中放入元素,如果counterCells爲空且對baseCount進行CAS更新失敗,啓用CounterCell進行計數,大致原理即每個實際的線程啓用一個計數單位,每執行put操作則該計數單位增加1;
- Map put元素只有當該槽位已形成鏈表或者二叉樹(即hash槽位不爲空),纔會進行擴容檢查;
擴容方法
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE;
//觸發擴容,初始化nextTable
if (nextTab == null) {
try {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];//擴容大小爲table的2倍
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
transferIndex = n;//從table末槽位開始操作
}
//擴容進行時
int nextn = nextTab.length;
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);//標記節點,標記table的槽位,槽位轉移結束的標記
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
//自旋替換transferIndex,操作下一個槽位
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
//循環結束條件判定,擴容線程必運行
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);//hash槽位爲空,放入標記節點
else if ((fh = f.hash) == MOVED)
advance = true; //空槽位或者擴容已完成無需轉移
else {
//非空槽位,頭節點加鎖,逐步進行節點轉移,table->nextTable
//hash槽位對應的節點進行擴容,即元素轉移至nextTable
synchronized (f) {
if (tabAt(tab, i) == f) {
//同一個槽位擴容後可拆分成兩條鏈表,存放於不同位置(i,i+n)
Node<K,V> ln, hn;
if (fh >= 0) {
//這個槽位存放的爲鏈表
int runBit = fh & n;//n是2的倍數,runBit只存在兩個值0或n
Node<K,V> lastRun = f;
//這段代碼有點費解,其實主要爲處理一些特殊情況而不用重新new新節點,從而複用以前的節點
//比如該槽位節點在nextTable的槽位都爲i,那麼不需要生成新鏈表,只需將原來槽位頭節點替換即可
//比如該槽位前半段在nextTable的新槽位爲i,後半段在nextTable的槽位爲i+n,則後半段不需要new新節點了
//感覺是爲了節省內存空間,減輕GC的壓力
for (Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
if (runBit == 0) {
ln = lastRun;
hn = null;
}
else {
hn = lastRun;
ln = null;
}
for (Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);//將該槽位標記爲轉移完成的狀態
advance = true;
}
else if (f instanceof TreeBin) {
//該槽位形成紅黑樹的結構
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> lo = null, loTail = null;
TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);//將該槽位標記爲轉移完成的狀態
advance = true;
}
}
}
}
}
}
總結
- 擴容過程中,空槽位會放入標記節點;
- 擴容主要操作的是nextTable這個屬性,對於讀操作不影響,讀操作讀的是table的值;
- 對槽位擴容會對頭節點加鎖,這樣該槽位無論是讀(擴容進行時)還是寫(map put值),都是線程安全的,且map putVal操作在同步代碼塊添加了判斷 if (tabAt(tab, i) == f),假設A線程先對該槽位擴容,B線程向該槽位放元素,則該判斷不成立,不會再對該槽位的節點進行操作;
- 槽位擴容完成會在table相應的槽位添加標記節點;