1.內(nèi)部結(jié)構(gòu)
2. 寫操作 put
// 如果put更新了value媒至,則將返回舊的值;如果沒有更新(之前沒有該key斗忌,那么返回null)
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();
// i = hash % n
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// f是一個null pointer的話二拐,Node對象不存在,更談不上對象頭和鎖信息, 因此不能用synchronized, 而是嘗試cas修改提完。
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
// f.hash == MOVED意味著f是一個fwd節(jié)點,其對應bin內(nèi)的數(shù)據(jù)已經(jīng)被遷移到了nextTable中丘侠,當前線程應該去幫助遷移數(shù)據(jù)徒欣。
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
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)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
// 總計數(shù)+1,觸發(fā)擴容
addCount(1L, binCount);
return null;
}
put流程
3. 讀操作 get
4.擴容
-
4.1 addCount
將總節(jié)點計數(shù)+1蜗字,并觸發(fā)擴容
/**
* Adds to count, and if table is too small and not already
* resizing, initiates transfer. If already resizing, helps
* perform transfer if work is available. Rechecks occupancy
* after a transfer to see if another resize is already needed
* because resizings are lagging additions.
*
* @param x the count to add
* @param check if <0, don't check resize, if <= 1 only check if uncontended
*/
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
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();
}
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
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();
}
}
}
addCount流程
-
4.2 transfer(tab, nextTab)
/**
* Moves and/or copies the nodes in each bin to new table. See
* above for explanation.
*/
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
// stride: 步長打肝,表示當前線程可以處理數(shù)組中多少個bin的數(shù)據(jù)遷移工作脂新,最小取16
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { // initiating
try {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
// transferIndex為volatile變量,它表示為當前Map transfer時粗梭,下一個線程應該從哪里開始向前遍歷
// 每個線程在遷移時争便,都要獲取它在一次遷移過程中能遷移的數(shù)組位置上下限,然后將transferIndex修改,保證不同線程間不會相互干擾
transferIndex = n;
}
int nextn = nextTab.length;
// 當數(shù)組中某個bin的頭節(jié)點為fwd時断医,該bin內(nèi)的節(jié)點已經(jīng)遷移完成了
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
// advance:在遷移過程中滞乙,通過advance來標記當前bin是否遷移完成,遷移完成則將advance置為true鉴嗤,表示可以向前去處理i-1處的節(jié)點遷移了
boolean advance = true;
// finishing為true表示所有bin內(nèi)的節(jié)點都遷移完成了斩启,此時可以考慮該如何退出了。
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
while (advance) { // advance為true躬窜,需要去處理 i-1 處的節(jié)點遷移
int nextIndex, nextBound;
//若 i-1 仍在當前線程處理區(qū)間內(nèi)浇垦,那么將advance置位false,然后去做i-1處的遷移荣挨;
//若 finishing 被置為true男韧, 遷移完成了,需要更新this.table和sizeCtl
if (--i >= bound || finishing)
advance = false;
// i- 1 < bound默垄, 說明當前線程該處理的【bound, maxi)區(qū)間都處理完了此虑,接下來就是看看它還能不能繼續(xù)找下一個區(qū)間然后去遷移該區(qū)間的數(shù)據(jù)
// transferIndex已經(jīng)被更新到<=0了,說明其他線程已經(jīng)將剩余區(qū)間占完了口锭,當前線程該準備更新sizeCtl然后退出了
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
// 當前線程還可以占到區(qū)間
// 更新成功的話朦前,說明當前線程又要準備另一個區(qū)間內(nèi)的擴容了,確定其上下限鹃操,更新i和advance韭寸,然后開始在該區(qū)間內(nèi)開始遷移
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
}
}
// f == null ,沒辦法用synchronized來鎖荆隘,因此使用原子更新恩伺,更新失敗(false)則重試,成功則進行i-1處的遷移(true)
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {
// 鎖住鏈表頭節(jié)點椰拒,防止其他線程向該bin putVal
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
if (fh >= 0) {
int runBit = fh & n;
Node<K,V> lastRun = f;
// 針對鏈表晶渠,遍歷每個節(jié)點,根據(jù)節(jié)點hash將其拍不到兩個鏈表內(nèi)燃观,ln對應nextTable的位置i褒脯, hn對應nextTab的位置 i+ n
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;
}
// 針對紅黑樹,根據(jù)每個節(jié)點的hash拆成兩棵樹缆毁,根據(jù)非樹化閾值來將紅黑樹轉(zhuǎn)鏈表
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;
}
}
}
}
}
}
線程內(nèi)transfer流程
多線程參與擴容的情況