1. 程式人生 > >ConcurrentHashMap 1.8原始碼解析

ConcurrentHashMap 1.8原始碼解析

網上介紹ConcurrentHashMap的文章很多,我就只講我閱讀的部分筆記記錄一下。

public class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
        implements ConcurrentMap<K, V>, Serializable {

//put方法
final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        //計算當前key的hash值
int hash = spread(key.hashCode()); int binCount = 0; for (Node<K, V>[] tab = table; ; ) { Node<K, V> f; int n, i, fh; // 1. 如果table為空,初始化; if (tab == null || (n = tab.length) == 0) tab = initTable(); else
if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { //2.根據hash值計算得到陣列索引i,如果tab[i]為空,直接新建節點Node即可。 if (casTabAt(tab, i, null, new Node<K, V>(hash, key, value, null))) break; // no lock when adding to empty bin } //3.如果tab[i]不為空並且hash值為MOVED,說明該連結串列正在進行transfer操作,返回擴容完成後的table
else if ((fh = f.hash) == MOVED) //幫助執行Transfer操作,並返回transfer後的table tab = helpTransfer(tab, f); else { //4.tab[i]不為空,可能是連結串列首節點 也可能是紅黑樹首節點 V oldVal = null; //對首個節點進行加鎖操作 synchronized (f) { if (tabAt(tab, i) == f) { //再次校驗節點是否發生變更,防止併發操作 //4.1 連結串列首節點 if (fh >= 0) { binCount = 1; for (Node<K, V> e = f; ; ++binCount) { K ek; // 4.1.1 當前節點為所需節點,直接設定e.val = value即可。 if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) //對onlyIfAbsent支援 e.val = value; break; } Node<K, V> pred = e; //4.1.2 遍歷連結串列 if ((e = e.next) == null) { //未找到值為key的節點,直接新建Node並加入連結串列即可。 pred.next = new Node<K, V>(hash, key, value, null); break; } } } //4.2 如果首節點為TreeBin型別,說明為紅黑樹結構,執行putTreeVal操作。 else if (f instanceof TreeBin) { Node<K, V> p; binCount = 2; //如果當前位置已經為紅黑樹,則 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) //1.如果tab陣列長度長度小於64,直接擴容陣列,不再轉紅黑樹。 //2.連結串列需轉成紅黑樹, treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } //檢查當前容量是否需要進行擴容。 addCount(1L, binCount); return null; } //初始化table private final Node<K, V>[] initTable() { Node<K, V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { //其他執行緒已經在進行初始化,當前執行緒只需要讓出cpu片刻 if ((sc = sizeCtl) < 0) Thread.yield(); // lost initialization race; just spin else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { {//利用CAS方法把sizectl的值置為-1 表示本執行緒正在進行初始化 try { if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; //sizeCtl預設為0 @SuppressWarnings("unchecked") Node<K, V>[] nt = (Node<K, V>[]) new Node<?, ?>[n]; //初始化tab table = tab = nt; //下一次擴容的大小 sc = n - (n >>> 2);//相當於0.75*n 設定一個擴容的閾值 } } finally { sizeCtl = sc; } break; } } //返回tab return tab; } //幫助執行Transfer操作 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; if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nextTab);//呼叫擴容方法,直接進入複製階段 break; } } return nextTab; } return table; } private final void addCount(long x, int check) { CounterCell[] as; long b, s; //利用CAS方法更新baseCount的值 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 && //tab陣列不為空 (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)) //這裡sizeCtl的初始值是一個負值=(rs<<RESIZE_STAMP_SHIFT)+2, //每當一個執行緒參與進來執行遷移工作時,則該值進行CAS自增, //該執行緒的任務執行完畢要退出時對該值進行CAS自減操作, //所以當sizeCtl的值等於上述初值則說明了此時未有其他執行緒還在執行遷移工作,可以去執行收尾工作了 //Demo: //int rs = resizeStamp(16); => rs =32795 //int sc = (rs << RESIZE_STAMP_SHIFT) + 2; => rs =-2145714174 //int sc2 = sc >>> RESIZE_STAMP_SHIFT; => sc2 =32795 transfer(tab, null); //實際擴容*2 s = sumCount(); //獲取實際容量 } } } private final void tryPresize(int size) { //計算需擴容容量 int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(size + (size >>> 1) + 1); int sc; while ((sc = sizeCtl) >= 0) { Node<K, V>[] tab = table; int n; if (tab == null || (n = tab.length) == 0) { //初始化tab n = (sc > c) ? sc : c; //確定容量 if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { //標示位:正在初始化 try { if (table == tab) { @SuppressWarnings("unchecked") Node<K, V>[] nt = (Node<K, V>[]) new Node<?, ?>[n]; table = nt; sc = n - (n >>> 2);//下次擴容的閥值 } } finally { sizeCtl = sc; } } } else if (c <= sc || n >= MAXIMUM_CAPACITY) //未超過閥值,或 超出最大長度 break; else if (tab == table) { int rs = resizeStamp(n); if (sc < 0) { Node<K, V>[] nt; 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); } } } 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; // subdivide range //初始化nextTab if (nextTab == null) { // initiating try { //構造一個nextTable物件 它的容量是原來的兩倍 @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 = n; //老table長度 } int nextn = nextTab.length; //構造一個連節點指標 用於標誌位 ForwardingNode<K, V> fwd = new ForwardingNode<K, V>(nextTab); //併發擴容的關鍵屬性 如果等於true 說明這個節點已經處理過 boolean advance = true; boolean finishing = false; // to ensure sweep before committing nextTab //i表示當前處理位置 //bound表示本次處理界限 for (int i = 0, bound = 0; ; ) { Node<K, V> f; int fh; //這個while迴圈體的作用就是在控制i-- 通過i--可以依次遍歷原hash表中的節點 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; //如果所有的節點都已經完成複製工作 就把nextTable賦值給table 清空臨時物件nextTable if (finishing) { nextTable = null; table = nextTab; //擴容閾值設定為原來容量的1.5倍 依然相當於現在容量的0.75倍 sizeCtl = (n << 1) - (n >>> 1); return; } //利用CAS方法更新這個擴容閾值,在這裡面sizectl值減一,說明當前執行緒參與擴容結束 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 } //如果遍歷到的節點為空 則放入ForwardingNode指標 } else if ((f = tabAt(tab, i)) == null) advance = casTabAt(tab, i, null, fwd); //如果遍歷到ForwardingNode節點 說明這個點已經被處理過了 直接跳過 這裡是控制併發擴容的核心 else if ((fh = f.hash) == MOVED) advance = true; // already processed else { //節點上鎖 synchronized (f) { if (tabAt(tab, i) == f) { Node<K, V> ln, hn; if (fh >= 0) { //如果fh>=0 證明這是一個Node節點 int runBit = fh & n; //n為原陣列的長度。runBit=0 或 runBit=n(n=2^x) //以下的部分在完成的工作是構造兩個連結串列:一個順序連結串列,一個開頭反序結尾順序的列表 Node<K, V> lastRun = f; 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); } //在nextTable的i位置上插入一個連結串列 setTabAt(nextTab, i, ln); //在nextTable的i+n的位置上插入另一個連結串列 setTabAt(nextTab, i + n, hn); //在table的i位置上插入forwardNode節點 表示已經處理過該節點 setTabAt(tab, i, fwd); //設定advance為true 返回到上面的while迴圈中 就可以執行i--操作 advance = true; } else if (f instanceof TreeBin) {//對TreeBin物件進行處理 與上面的過程類似 TreeBin<K, V> t = (TreeBin<K, V>) f; TreeNode<K, V> lo = null, loTail = null; //第x為0 TreeNode<K, V> hi = null, hiTail = null; //第x為1 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; } } //如果擴容後已經不再需要tree的結構 反向轉換為連結串列結構 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; //在nextTable的i位置上插入一個連結串列 setTabAt(nextTab, i, ln); //在nextTable的i+n的位置上插入另一個連結串列 setTabAt(nextTab, i + n, hn); //在table的i位置上插入forwardNode節點 表示已經處理過該節點 setTabAt(tab, i, fwd); //設定advance為true 返回到上面的while迴圈中 就可以執行i--操作 advance = true; } } } } } } //當前方法主要是判斷連結串列是否需要轉成紅黑樹。及構造紅黑樹 private final void treeifyBin(Node<K, V>[] tab, int index) { Node<K, V> b; int n, sc; if (tab != null) { //1.如果tab陣列長度長度小於64,直接擴容陣列,不再轉紅黑樹。 if ((n = tab.length) < MIN_TREEIFY_CAPACITY) tryPresize(n << 1); //2.連結串列需轉成紅黑樹 else if ((b = tabAt(tab, index)) != null && b.hash >= 0) { synchronized (b) { if (tabAt(tab, index) == b) { //防止併發,判斷當前節點是否發生改變 TreeNode<K, V> hd = null, tl = null; //遍歷連結串列,得到一個由樹節點組成的連結串列 for (Node<K, V> e = b; e != null; e = e.next) { TreeNode<K, V> p = new TreeNode<K, V>(e.hash, e.key, e.val, null, null); if ((p.prev = tl) == null) hd = p; else tl.next = p; tl = p; } //將當前連結串列轉成紅黑樹物件TreeBin,存放在tab的位置i上 setTabAt(tab, index, new TreeBin<K, V>(hd)); //樹的根節點 } } } } } //查詢方法,比較簡單 public V get(Object key) { Node<K, V>[] tab; Node<K, V> e, p; int n, eh; K ek; int h = spread(key.hashCode()); //計算h 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) {//遍歷連結串列,查詢所需key if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) return e.val; } } return null; } }