本文首發於一世流雲專欄: https://segmentfault.com/blog...
ConcurrentHashMap
是在JDK1.5時,J.U.C引入的一個同步集合工具類,顧名思義,這是一個線程安全的HashMap。不一樣版本的ConcurrentHashMap,內部實現機制千差萬別,本節全部的討論基於JDK1.8。java
ConcurrentHashMap的類繼承關係並不複雜:node
能夠看到ConcurrentHashMap繼承了AbstractMap,這是一個java.util
包下的抽象類,提供Map接口的骨幹實現,以最大限度地減小實現Map這類數據結構時所需的工做量,通常來說,若是須要重複造輪子——本身來實現一個Map,那通常就是繼承AbstractMap。算法
另外,ConcurrentHashMap實現了ConcurrentMap
這個接口,ConcurrentMap是在JDK1.5時隨着J.U.C包引入的,這個接口其實就是提供了一些針對Map的原子操做:segmentfault
ConcurrentMap接口提供的功能:數組
方法簽名 | 功能 |
---|---|
getOrDefault(Object key, V defaultValue) | 返回指定key對應的值;若是Map不存在該key,則返回defaultValue |
forEach(BiConsumer action) | 遍歷Map的全部Entry,並對其進行指定的aciton操做 |
putIfAbsent(K key, V value) | 若是Map不存在指定的key,則插入<K,V>;不然,直接返回該key對應的值 |
remove(Object key, Object value) | 刪除與<key,value>徹底匹配的Entry,並返回true;不然,返回false |
replace(K key, V oldValue, V newValue) | 若是存在key,且值和oldValue一致,則更新爲newValue,並返回true;不然,返回false |
replace(K key, V value) | 若是存在key,則更新爲value,返回舊value;不然,返回null |
replaceAll(BiFunction function) | 遍歷Map的全部Entry,並對其進行指定的funtion操做 |
computeIfAbsent(K key, Function mappingFunction) | 若是Map不存在指定的key,則經過mappingFunction計算value並插入 |
computeIfPresent(K key, BiFunction remappingFunction) | 若是Map存在指定的key,則經過mappingFunction計算value並替換舊值 |
compute(K key, BiFunction remappingFunction) | 根據指定的key,查找value;而後根據獲得的value和remappingFunction從新計算新值,並替換舊值 |
merge(K key, V value, BiFunction remappingFunction) | 若是key不存在,則插入value;不然,根據key對應的值和remappingFunction計算新值,並替換舊值 |
咱們先來看下ConcurrentHashMap
對象的內部結構究竟什麼樣的:安全
ConcurrentHashMap內部維護了一個Node
類型的數組,也就是table:數據結構
transient volatile Node<K, V>[] table;
多線程
數組的每個位置table[i]
表明了一個桶,當插入鍵值對時,會根據鍵的hash值映射到不一樣的桶位置,table一共能夠包含4種不一樣類型的桶:Node、TreeBin、ForwardingNode、ReservationNode。上圖中,不一樣的桶用不一樣顏色表示。能夠看到,有的桶連接着鏈表,有的桶連接着樹,這也是JDK1.8中ConcurrentHashMap的特殊之處,後面會詳細講到。併發
須要注意的是:TreeBin所連接的是一顆紅黑樹,紅黑樹的結點用TreeNode表示,因此ConcurrentHashMap中實際上一共有五種不一樣類型的Node結點。app
之因此用TreeBin而不是直接用TreeNode,是由於紅黑樹的操做比較複雜,包括構建、左旋、右旋、刪除,平衡等操做,用一個代理結點TreeBin來包含這些複雜操做,實際上是一種「職責分離」的思想。另外TreeBin中也包含了一些加/解鎖的操做。
在JDK1.8以前,ConcurrentHashMap採用了分段鎖的設計思路,以減小熱點域的衝突。JDK1.8時再也不延續,轉而直接對每一個桶加鎖,並用「紅黑樹」連接衝突結點。關於紅黑樹和通常HashMap的實現思路,讀者能夠參考《Algorithms 4th》,或我以前寫的博文: 紅黑樹 和 哈希表,本文不會對紅黑樹的相關操做具體分析。
上一節提到,ConcurrentHashMap一共包含5種結點,咱們來看下各個結點的定義和做用。
一、Node結點
Node結點的定義很是簡單,也是其它四種類型結點的父類。
默認連接到table[i]
——桶上的結點就是Node結點。
當出現hash衝突時,Node結點會首先以 鏈表的形式連接到table上,當結點數量超過必定數目時,鏈表會轉化爲紅黑樹。由於鏈表查找的平均時間複雜度爲O(n)
,而紅黑樹是一種平衡二叉樹,其平均時間複雜度爲O(logn)
。
/** * 普通的Entry結點, 以鏈表形式保存時纔會使用, 存儲實際的數據. */ static class Node<K, V> implements Map.Entry<K, V> { final int hash; final K key; volatile V val; volatile Node<K, V> next; // 鏈表指針 Node(int hash, K key, V val, Node<K, V> next) { this.hash = hash; this.key = key; this.val = val; this.next = next; } public final K getKey() { return key; } public final V getValue() { return val; } public final int hashCode() { return key.hashCode() ^ val.hashCode(); } public final String toString() { return key + "=" + val; } public final V setValue(V value) { throw new UnsupportedOperationException(); } public final boolean equals(Object o) { Object k, v, u; Map.Entry<?, ?> e; return ((o instanceof Map.Entry) && (k = (e = (Map.Entry<?, ?>) o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u))); } /** * 鏈表查找. */ Node<K, V> find(int h, Object k) { Node<K, V> e = this; if (k != null) { do { K ek; if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; } while ((e = e.next) != null); } return null; } }
二、TreeNode結點
TreeNode就是紅黑樹的結點,TreeNode不會直接連接到table[i]
——桶上面,而是由TreeBin連接,TreeBin會指向紅黑樹的根結點。
/** * 紅黑樹結點, 存儲實際的數據. */ static final class TreeNode<K, V> extends Node<K, V> { boolean red; TreeNode<K, V> parent; TreeNode<K, V> left; TreeNode<K, V> right; /** * prev指針是爲了方便刪除. * 刪除鏈表的非頭結點時,須要知道它的前驅結點才能刪除,因此直接提供一個prev指針 */ TreeNode<K, V> prev; TreeNode(int hash, K key, V val, Node<K, V> next, TreeNode<K, V> parent) { super(hash, key, val, next); this.parent = parent; } Node<K, V> find(int h, Object k) { return findTreeNode(h, k, null); } /** * 以當前結點(this)爲根結點,開始遍歷查找指定key. */ final TreeNode<K, V> findTreeNode(int h, Object k, Class<?> kc) { if (k != null) { TreeNode<K, V> p = this; do { int ph, dir; K pk; TreeNode<K, V> q; TreeNode<K, V> pl = p.left, pr = p.right; if ((ph = p.hash) > h) p = pl; else if (ph < h) p = pr; else if ((pk = p.key) == k || (pk != null && k.equals(pk))) return p; else if (pl == null) p = pr; else if (pr == null) p = pl; else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0) p = (dir < 0) ? pl : pr; else if ((q = pr.findTreeNode(h, k, kc)) != null) return q; else p = pl; } while (p != null); } return null; } }
三、TreeBin結點
TreeBin至關於TreeNode的代理結點。TreeBin會直接連接到table[i]
——桶上面,該結點提供了一系列紅黑樹相關的操做,以及加鎖、解鎖操做。
/** * TreeNode的代理結點(至關於封裝了TreeNode的容器,提供針對紅黑樹的轉換操做和鎖控制) * hash值固定爲-3 */ static final class TreeBin<K, V> extends Node<K, V> { TreeNode<K, V> root; // 紅黑樹結構的根結點 volatile TreeNode<K, V> first; // 鏈表結構的頭結點 volatile Thread waiter; // 最近的一個設置WAITER標識位的線程 volatile int lockState; // 總體的鎖狀態標識位 static final int WRITER = 1; // 二進制001,紅黑樹的寫鎖狀態 static final int WAITER = 2; // 二進制010,紅黑樹的等待獲取寫鎖狀態 static final int READER = 4; // 二進制100,紅黑樹的讀鎖狀態,讀能夠併發,每多一個讀線程,lockState都加上一個READER值 /** * 在hashCode相等而且不是Comparable類型時,用此方法判斷大小. */ static int tieBreakOrder(Object a, Object b) { int d; if (a == null || b == null || (d = a.getClass().getName(). compareTo(b.getClass().getName())) == 0) d = (System.identityHashCode(a) <= System.identityHashCode(b) ? -1 : 1); return d; } /** * 將以b爲頭結點的鏈表轉換爲紅黑樹. */ TreeBin(TreeNode<K, V> b) { super(TREEBIN, null, null, null); this.first = b; TreeNode<K, V> r = null; for (TreeNode<K, V> x = b, next; x != null; x = next) { next = (TreeNode<K, V>) x.next; x.left = x.right = null; if (r == null) { x.parent = null; x.red = false; r = x; } else { K k = x.key; int h = x.hash; Class<?> kc = null; for (TreeNode<K, V> p = r; ; ) { int dir, ph; K pk = p.key; if ((ph = p.hash) > h) dir = -1; else if (ph < h) dir = 1; else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) dir = tieBreakOrder(k, pk); TreeNode<K, V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { x.parent = xp; if (dir <= 0) xp.left = x; else xp.right = x; r = balanceInsertion(r, x); break; } } } } this.root = r; assert checkInvariants(root); } /** * 對紅黑樹的根結點加寫鎖. */ private final void lockRoot() { if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER)) contendedLock(); } /** * 釋放寫鎖. */ private final void unlockRoot() { lockState = 0; } /** * Possibly blocks awaiting root lock. */ private final void contendedLock() { boolean waiting = false; for (int s; ; ) { if (((s = lockState) & ~WAITER) == 0) { if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) { if (waiting) waiter = null; return; } } else if ((s & WAITER) == 0) { if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) { waiting = true; waiter = Thread.currentThread(); } } else if (waiting) LockSupport.park(this); } } /** * 從根結點開始遍歷查找,找到「相等」的結點就返回它,沒找到就返回null * 當存在寫鎖時,以鏈表方式進行查找 */ final Node<K, V> find(int h, Object k) { if (k != null) { for (Node<K, V> e = first; e != null; ) { int s; K ek; /** * 兩種特殊狀況下以鏈表的方式進行查找: * 1. 有線程正持有寫鎖,這樣作可以不阻塞讀線程 * 2. 有線程等待獲取寫鎖,再也不繼續加讀鎖,至關於「寫優先」模式 */ if (((s = lockState) & (WAITER | WRITER)) != 0) { if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; e = e.next; } else if (U.compareAndSwapInt(this, LOCKSTATE, s, s + READER)) { TreeNode<K, V> r, p; try { p = ((r = root) == null ? null : r.findTreeNode(h, k, null)); } finally { Thread w; if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null) LockSupport.unpark(w); } return p; } } } return null; } /** * 查找指定key對應的結點,若是未找到,則插入. * * @return 插入成功返回null, 不然返回找到的結點 */ final TreeNode<K, V> putTreeVal(int h, K k, V v) { Class<?> kc = null; boolean searched = false; for (TreeNode<K, V> p = root; ; ) { int dir, ph; K pk; if (p == null) { first = root = new TreeNode<K, V>(h, k, v, null, null); break; } else if ((ph = p.hash) > h) dir = -1; else if (ph < h) dir = 1; else if ((pk = p.key) == k || (pk != null && k.equals(pk))) return p; else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) { if (!searched) { TreeNode<K, V> q, ch; searched = true; if (((ch = p.left) != null && (q = ch.findTreeNode(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.findTreeNode(h, k, kc)) != null)) return q; } dir = tieBreakOrder(k, pk); } TreeNode<K, V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { TreeNode<K, V> x, f = first; first = x = new TreeNode<K, V>(h, k, v, f, xp); if (f != null) f.prev = x; if (dir <= 0) xp.left = x; else xp.right = x; if (!xp.red) x.red = true; else { lockRoot(); try { root = balanceInsertion(root, x); } finally { unlockRoot(); } } break; } } assert checkInvariants(root); return null; } /** * 刪除紅黑樹的結點: * 1. 紅黑樹規模過小時,返回true,而後進行 樹 -> 鏈表 的轉化; * 2. 紅黑樹規模足夠時,不用變換成鏈表,但刪除結點時須要加寫鎖. */ final boolean removeTreeNode(TreeNode<K, V> p) { TreeNode<K, V> next = (TreeNode<K, V>) p.next; TreeNode<K, V> pred = p.prev; // unlink traversal pointers TreeNode<K, V> r, rl; if (pred == null) first = next; else pred.next = next; if (next != null) next.prev = pred; if (first == null) { root = null; return true; } if ((r = root) == null || r.right == null || // too small (rl = r.left) == null || rl.left == null) return true; lockRoot(); try { TreeNode<K, V> replacement; TreeNode<K, V> pl = p.left; TreeNode<K, V> pr = p.right; if (pl != null && pr != null) { TreeNode<K, V> s = pr, sl; while ((sl = s.left) != null) // find successor s = sl; boolean c = s.red; s.red = p.red; p.red = c; // swap colors TreeNode<K, V> sr = s.right; TreeNode<K, V> pp = p.parent; if (s == pr) { // p was s's direct parent p.parent = s; s.right = p; } else { TreeNode<K, V> sp = s.parent; if ((p.parent = sp) != null) { if (s == sp.left) sp.left = p; else sp.right = p; } if ((s.right = pr) != null) pr.parent = s; } p.left = null; if ((p.right = sr) != null) sr.parent = p; if ((s.left = pl) != null) pl.parent = s; if ((s.parent = pp) == null) r = s; else if (p == pp.left) pp.left = s; else pp.right = s; if (sr != null) replacement = sr; else replacement = p; } else if (pl != null) replacement = pl; else if (pr != null) replacement = pr; else replacement = p; if (replacement != p) { TreeNode<K, V> pp = replacement.parent = p.parent; if (pp == null) r = replacement; else if (p == pp.left) pp.left = replacement; else pp.right = replacement; p.left = p.right = p.parent = null; } root = (p.red) ? r : balanceDeletion(r, replacement); if (p == replacement) { // detach pointers TreeNode<K, V> pp; if ((pp = p.parent) != null) { if (p == pp.left) pp.left = null; else if (p == pp.right) pp.right = null; p.parent = null; } } } finally { unlockRoot(); } assert checkInvariants(root); return false; } // 如下是紅黑樹的經典操做方法,改編自《算法導論》 static <K, V> TreeNode<K, V> rotateLeft(TreeNode<K, V> root, TreeNode<K, V> p) { TreeNode<K, V> r, pp, rl; if (p != null && (r = p.right) != null) { if ((rl = p.right = r.left) != null) rl.parent = p; if ((pp = r.parent = p.parent) == null) (root = r).red = false; else if (pp.left == p) pp.left = r; else pp.right = r; r.left = p; p.parent = r; } return root; } static <K, V> TreeNode<K, V> rotateRight(TreeNode<K, V> root, TreeNode<K, V> p) { TreeNode<K, V> l, pp, lr; if (p != null && (l = p.left) != null) { if ((lr = p.left = l.right) != null) lr.parent = p; if ((pp = l.parent = p.parent) == null) (root = l).red = false; else if (pp.right == p) pp.right = l; else pp.left = l; l.right = p; p.parent = l; } return root; } static <K, V> TreeNode<K, V> balanceInsertion(TreeNode<K, V> root, TreeNode<K, V> x) { x.red = true; for (TreeNode<K, V> xp, xpp, xppl, xppr; ; ) { if ((xp = x.parent) == null) { x.red = false; return x; } else if (!xp.red || (xpp = xp.parent) == null) return root; if (xp == (xppl = xpp.left)) { if ((xppr = xpp.right) != null && xppr.red) { xppr.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.right) { root = rotateLeft(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateRight(root, xpp); } } } } else { if (xppl != null && xppl.red) { xppl.red = false; xp.red = false; xpp.red = true; x = xpp; } else { if (x == xp.left) { root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null) { xp.red = false; if (xpp != null) { xpp.red = true; root = rotateLeft(root, xpp); } } } } } } static <K, V> TreeNode<K, V> balanceDeletion(TreeNode<K, V> root, TreeNode<K, V> x) { for (TreeNode<K, V> xp, xpl, xpr; ; ) { if (x == null || x == root) return root; else if ((xp = x.parent) == null) { x.red = false; return x; } else if (x.red) { x.red = false; return root; } else if ((xpl = xp.left) == x) { if ((xpr = xp.right) != null && xpr.red) { xpr.red = false; xp.red = true; root = rotateLeft(root, xp); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr == null) x = xp; else { TreeNode<K, V> sl = xpr.left, sr = xpr.right; if ((sr == null || !sr.red) && (sl == null || !sl.red)) { xpr.red = true; x = xp; } else { if (sr == null || !sr.red) { if (sl != null) sl.red = false; xpr.red = true; root = rotateRight(root, xpr); xpr = (xp = x.parent) == null ? null : xp.right; } if (xpr != null) { xpr.red = (xp == null) ? false : xp.red; if ((sr = xpr.right) != null) sr.red = false; } if (xp != null) { xp.red = false; root = rotateLeft(root, xp); } x = root; } } } else { // symmetric if (xpl != null && xpl.red) { xpl.red = false; xp.red = true; root = rotateRight(root, xp); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl == null) x = xp; else { TreeNode<K, V> sl = xpl.left, sr = xpl.right; if ((sl == null || !sl.red) && (sr == null || !sr.red)) { xpl.red = true; x = xp; } else { if (sl == null || !sl.red) { if (sr != null) sr.red = false; xpl.red = true; root = rotateLeft(root, xpl); xpl = (xp = x.parent) == null ? null : xp.left; } if (xpl != null) { xpl.red = (xp == null) ? false : xp.red; if ((sl = xpl.left) != null) sl.red = false; } if (xp != null) { xp.red = false; root = rotateRight(root, xp); } x = root; } } } } } /** * 遞歸檢查紅黑樹的正確性 */ static <K, V> boolean checkInvariants(TreeNode<K, V> t) { TreeNode<K, V> tp = t.parent, tl = t.left, tr = t.right, tb = t.prev, tn = (TreeNode<K, V>) t.next; if (tb != null && tb.next != t) return false; if (tn != null && tn.prev != t) return false; if (tp != null && t != tp.left && t != tp.right) return false; if (tl != null && (tl.parent != t || tl.hash > t.hash)) return false; if (tr != null && (tr.parent != t || tr.hash < t.hash)) return false; if (t.red && tl != null && tl.red && tr != null && tr.red) return false; if (tl != null && !checkInvariants(tl)) return false; if (tr != null && !checkInvariants(tr)) return false; return true; } private static final sun.misc.Unsafe U; private static final long LOCKSTATE; static { try { U = sun.misc.Unsafe.getUnsafe(); Class<?> k = TreeBin.class; LOCKSTATE = U.objectFieldOffset (k.getDeclaredField("lockState")); } catch (Exception e) { throw new Error(e); } } }
四、ForwardingNode結點
ForwardingNode結點僅僅在擴容時纔會使用——關於擴容,會在下一篇文章專門論述
/** * ForwardingNode是一種臨時結點,在擴容進行中才會出現,hash值固定爲-1,且不存儲實際數據。 * 若是舊table數組的一個hash桶中所有的結點都遷移到了新table中,則在這個桶中放置一個ForwardingNode。 * 讀操做碰到ForwardingNode時,將操做轉發到擴容後的新table數組上去執行;寫操做遇見它時,則嘗試幫助擴容。 */ static final class ForwardingNode<K, V> extends Node<K, V> { final Node<K, V>[] nextTable; ForwardingNode(Node<K, V>[] tab) { super(MOVED, null, null, null); this.nextTable = tab; } // 在新的數組nextTable上進行查找 Node<K, V> find(int h, Object k) { // loop to avoid arbitrarily deep recursion on forwarding nodes outer: for (Node<K, V>[] tab = nextTable; ; ) { Node<K, V> e; int n; if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null) return null; for (; ; ) { int eh; K ek; if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; if (eh < 0) { if (e instanceof ForwardingNode) { tab = ((ForwardingNode<K, V>) e).nextTable; continue outer; } else return e.find(h, k); } if ((e = e.next) == null) return null; } } } }
五、ReservationNode結點
保留結點,ConcurrentHashMap中的一些特殊方法會專門用到該類結點。
/** * 保留結點. * hash值固定爲-3, 不保存實際數據 * 只在computeIfAbsent和compute這兩個函數式API中充當佔位符加鎖使用 */ static final class ReservationNode<K, V> extends Node<K, V> { ReservationNode() { super(RESERVED, null, null, null); } Node<K, V> find(int h, Object k) { return null; } }
ConcurrentHashMap提供了五個構造器,這五個構造器內部最多也只是計算了下table的初始容量大小,並無進行實際的建立table數組的工做:
ConcurrentHashMap,採用了一種 「懶加載」的模式,只有到 首次插入鍵值對的時候,纔會真正的去初始化table數組。
空構造器
public ConcurrentHashMap() { }
指定table初始容量的構造器
/** * 指定table初始容量的構造器. * tableSizeFor會返回大於入參(initialCapacity + (initialCapacity >>> 1) + 1)的最小2次冪值 */ public ConcurrentHashMap(int initialCapacity) { if (initialCapacity < 0) throw new IllegalArgumentException(); int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY : tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)); this.sizeCtl = cap; }
根據已有的Map構造
/** * 根據已有的Map構造ConcurrentHashMap. */ public ConcurrentHashMap(Map<? extends K, ? extends V> m) { this.sizeCtl = DEFAULT_CAPACITY; putAll(m); }
指定table初始容量和負載因子的構造器
/** * 指定table初始容量和負載因子的構造器. */ public ConcurrentHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, 1); }
指定table初始容量、負載因子、併發級別的構造器
/** * 指定table初始容量、負載因子、併發級別的構造器. * <p> * 注意:concurrencyLevel只是爲了兼容JDK1.8之前的版本,並非實際的併發級別,loadFactor也不是實際的負載因子 * 這兩個都失去了原有的意義,僅僅對初始容量有必定的控制做用 */ public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) throw new IllegalArgumentException(); if (initialCapacity < concurrencyLevel) initialCapacity = concurrencyLevel; long size = (long) (1.0 + (long) initialCapacity / loadFactor); int cap = (size >= (long) MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int) size); this.sizeCtl = cap; }
咱們再看下ConcurrentHashMap內部定義了哪些常量/字段,先大體熟悉下這些常量/字段,後面結合具體的方法分析就能相對容易地理解這些常量/字段的含義了。
常量 :
/** * 最大容量. */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * 默認初始容量 */ private static final int DEFAULT_CAPACITY = 16; /** * The largest possible (non-power of two) array size. * Needed by toArray and related methods. */ static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 負載因子,爲了兼容JDK1.8之前的版本而保留。 * JDK1.8中的ConcurrentHashMap的負載因子恆定爲0.75 */ private static final float LOAD_FACTOR = 0.75f; /** * 鏈表轉樹的閾值,即連接結點數大於8時, 鏈表轉換爲樹. */ static final int TREEIFY_THRESHOLD = 8; /** * 樹轉鏈表的閾值,即樹結點樹小於6時,樹轉換爲鏈表. */ static final int UNTREEIFY_THRESHOLD = 6; /** * 在鏈表轉變成樹以前,還會有一次判斷: * 即只有鍵值對數量大於MIN_TREEIFY_CAPACITY,纔會發生轉換。 * 這是爲了不在Table創建初期,多個鍵值對剛好被放入了同一個鏈表中而致使沒必要要的轉化。 */ static final int MIN_TREEIFY_CAPACITY = 64; /** * 在樹轉變成鏈表以前,還會有一次判斷: * 即只有鍵值對數量小於MIN_TRANSFER_STRIDE,纔會發生轉換. */ private static final int MIN_TRANSFER_STRIDE = 16; /** * 用於在擴容時生成惟一的隨機數. */ private static int RESIZE_STAMP_BITS = 16; /** * 可同時進行擴容操做的最大線程數. */ private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1; /** * The bit shift for recording size stamp in sizeCtl. */ private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS; static final int MOVED = -1; // 標識ForwardingNode結點(在擴容時纔會出現,不存儲實際數據) static final int TREEBIN = -2; // 標識紅黑樹的根結點 static final int RESERVED = -3; // 標識ReservationNode結點() static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash /** * CPU核心數,擴容時使用 */ static final int NCPU = Runtime.getRuntime().availableProcessors();
字段 :
/** * Node數組,標識整個Map,首次插入元素時建立,大小老是2的冪次. */ transient volatile Node<K, V>[] table; /** * 擴容後的新Node數組,只有在擴容時才非空. */ private transient volatile Node<K, V>[] nextTable; /** * 控制table的初始化和擴容. * 0 : 初始默認值 * -1 : 有線程正在進行table的初始化 * >0 : table初始化時使用的容量,或初始化/擴容完成後的threshold * -(1 + nThreads) : 記錄正在執行擴容任務的線程數 */ private transient volatile int sizeCtl; /** * 擴容時須要用到的一個下標變量. */ private transient volatile int transferIndex; /** * 計數基值,當沒有線程競爭時,計數將加到該變量上。相似於LongAdder的base變量 */ private transient volatile long baseCount; /** * 計數數組,出現併發衝突時使用。相似於LongAdder的cells數組 */ private transient volatile CounterCell[] counterCells; /** * 自旋標識位,用於CounterCell[]擴容時使用。相似於LongAdder的cellsBusy變量 */ private transient volatile int cellsBusy; // 視圖相關字段 private transient KeySetView<K, V> keySet; private transient ValuesView<K, V> values; private transient EntrySetView<K, V> entrySet;
咱們來看下ConcurrentHashMap如何插入一個元素:
/** * 插入鍵值對,<K,V>均不能爲null. */ public V put(K key, V value) { return putVal(key, value, false); }
put方法內部調用了putVal
這個私有方法:
/** * 實際的插入操做 * * @param onlyIfAbsent true:僅當key不存在時,才插入 */ final V putVal(K key, V value, boolean onlyIfAbsent) { if (key == null || value == null) throw new NullPointerException(); int hash = spread(key.hashCode()); // 再次計算hash值 /** * 使用鏈表保存時,binCount記錄table[i]這個桶中所保存的結點數; * 使用紅黑樹保存時,binCount==2,保證put後更改計數值時可以進行擴容檢查,同時不觸發紅黑樹化操做 */ int binCount = 0; for (Node<K, V>[] tab = table; ; ) { // 自旋插入結點,直到成功 Node<K, V> f; int n, i, fh; if (tab == null || (n = tab.length) == 0) // CASE1: 首次初始化table —— 懶加載 tab = initTable(); else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { // CASE2: table[i]對應的桶爲null // 注意下上面table[i]的索引i的計算方式:[ key的hash值 & (table.length-1) ] // 這也是table容量必須爲2的冪次的緣由,讀者能夠本身看下當table.length爲2的冪次時,(table.length-1)的二進制形式的特色 —— 全是1 // 配合這種索引計算方式能夠實現key的均勻分佈,減小hash衝突 if (casTabAt(tab, i, null, new Node<K, V>(hash, key, value, null))) // 插入一個鏈表結點 break; } else if ((fh = f.hash) == MOVED) // CASE3: 發現ForwardingNode結點,說明此時table正在擴容,則嘗試協助數據遷移 tab = helpTransfer(tab, f); else { // CASE4: 出現hash衝突,也就是table[i]桶中已經有告終點 V oldVal = null; synchronized (f) { // 鎖住table[i]結點 if (tabAt(tab, i) == f) { // 再判斷一下table[i]是否是第一個結點, 防止其它線程的寫修改 if (fh >= 0) { // CASE4.1: table[i]是鏈表結點 binCount = 1; for (Node<K, V> e = f; ; ++binCount) { K ek; // 找到「相等」的結點,判斷是否須要更新value值 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) { // CASE4.2: table[i]是紅黑樹結點 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) // 代表本次put操做只是替換了舊值,不用更改計數值 return oldVal; break; } } } addCount(1L, binCount); // 計數值加1 return null; }
putVal
的邏輯仍是很清晰的,首先根據key計算hash值,而後經過hash值與table容量進行運算,計算獲得key所映射的索引——也就是對應到table中桶的位置。
這裏須要注意的是計算索引的方式:i = (n - 1) & hash
n - 1 == table.length - 1
,table.length
的大小必須爲2的冪次的緣由就在這裏。
讀者能夠本身計算下,當table.length
爲2的冪次時,(table.length-1)
的二進制形式的特色是除最高位外所有是1,配合這種索引計算方式能夠實現key在table中的均勻分佈,減小hash衝突——出現hash衝突時,結點就須要以鏈表或紅黑樹的形式連接到table[i],這樣不管是插入仍是查找都須要額外的時間。
putVal方法一共處理四種狀況:
以前講構造器的時候說了,ConcurrentHashMap在構造的時候並不會初始化table數組,首次初始化就在這裏經過initTable方法完成:
/** * 初始化table, 使用sizeCtl做爲初始化容量. */ private final Node<K, V>[] initTable() { Node<K, V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { //自旋直到初始化成功 if ((sc = sizeCtl) < 0) // sizeCtl<0 說明table已經正在初始化/擴容 Thread.yield(); else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { // 將sizeCtl更新成-1,表示正在初始化中 try { if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; Node<K, V>[] nt = (Node<K, V>[]) new Node<?, ?>[n]; table = tab = nt; sc = n - (n >>> 2); // n - (n >>> 2) = n - n/4 = 0.75n, 前面說了loadFactor已在JDK1.8廢棄 } } finally { sizeCtl = sc; // 設置threshold = 0.75 * table.length } break; } } return tab; }
initTable方法就是將sizeCtl字段的值(ConcurrentHashMap對象在構造時設置)做爲table的大小。
須要注意的是這裏的n - (n >>> 2)
,其實就是0.75 * n
,sizeCtl 的值最終須要變動爲0.75 * n
,至關於設置了threshold。
最簡單的狀況,直接CAS操做佔用桶table[i]
便可。
ForwardingNode結點是ConcurrentHashMap中的五類結點之一,至關於一個佔位結點,表示當前table正在進行擴容,當前線程能夠嘗試協助數據遷移。
擴容和數據遷移是ConcurrentHashMap中最複雜的部分,咱們會在下一章專門討論。
當兩個不一樣key映射到同一個table[i]
桶中時,就會出現這種狀況:
putVal方法的最後,涉及將鏈表轉換爲紅黑樹 —— treeifyBin ,但實際狀況並不是當即就會轉換,當table的容量小於64時,出於性能考慮,只是對table數組擴容1倍——tryPresize:
tryPresize方法涉及擴容和數據遷移,咱們會在下一章專門討論。
/** * 嘗試進行 鏈表 -> 紅黑樹 的轉換. */ private final void treeifyBin(Node<K, V>[] tab, int index) { Node<K, V> b; int n, sc; if (tab != null) { // CASE 1: table的容量 < MIN_TREEIFY_CAPACITY(64)時,直接進行table擴容,不進行紅黑樹轉換 if ((n = tab.length) < MIN_TREEIFY_CAPACITY) tryPresize(n << 1); // CASE 2: table的容量 ≥ MIN_TREEIFY_CAPACITY(64)時,進行鏈表 -> 紅黑樹的轉換 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類型包裝,並連接到table[index]中 setTabAt(tab, index, new TreeBin<K, V>(hd)); } } } } }
咱們來看下ConcurrentHashMap如何根據key來查找一個元素:
/** * 根據key查找對應的value值 * * @return 查找不到則返回null * @throws NullPointerException if the specified key is null */ public V get(Object key) { Node<K, V>[] tab; Node<K, V> e, p; int n, eh; K ek; int h = spread(key.hashCode()); // 從新計算key的hash值 if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) { if ((eh = e.hash) == h) { // table[i]就是待查找的項,直接返回 if ((ek = e.key) == key || (ek != null && key.equals(ek))) return e.val; } else if (eh < 0) // hash值<0, 說明遇到特殊結點(非鏈表結點), 調用find方法查找 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; }
get方法的邏輯很簡單,首先根據key的hash值計算映射到table的哪一個桶——table[i]
。
find
方法查找;關鍵是第二種狀況,不一樣結點的find查找方式有所不一樣,咱們來具體看下:
當槽table[i]
被普通Node結點佔用,說明是鏈表連接的形式,直接從鏈表頭開始查找:
/** * 鏈表查找. */ Node<K, V> find(int h, Object k) { Node<K, V> e = this; if (k != null) { do { K ek; if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; } while ((e = e.next) != null); } return null; }
TreeBin的查找比較特殊,咱們知道當槽table[i]
被TreeBin結點佔用時,說明連接的是一棵紅黑樹。因爲紅黑樹的插入、刪除會涉及整個結構的調整,因此一般存在讀寫併發操做的時候,是須要加鎖的。
ConcurrentHashMap採用了一種 相似讀寫鎖的方式:當線程持有寫鎖(修改紅黑樹)時,若是讀線程須要查找,不會像傳統的讀寫鎖那樣阻塞等待,而是轉而以鏈表的形式進行查找(TreeBin自己時Node類型的子類,全部擁有Node的全部字段)
/** * 從根結點開始遍歷查找,找到「相等」的結點就返回它,沒找到就返回null * 當存在寫鎖時,以鏈表方式進行查找 */ final Node<K, V> find(int h, Object k) { if (k != null) { for (Node<K, V> e = first; e != null; ) { int s; K ek; /** * 兩種特殊狀況下以鏈表的方式進行查找: * 1. 有線程正持有寫鎖,這樣作可以不阻塞讀線程 * 2. 有線程等待獲取寫鎖,再也不繼續加讀鎖,至關於「寫優先」模式 */ if (((s = lockState) & (WAITER | WRITER)) != 0) { if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; e = e.next; // 鏈表形式 } // 讀線程數量加1,讀狀態進行累加 else if (U.compareAndSwapInt(this, LOCKSTATE, s, s + READER)) { TreeNode<K, V> r, p; try { p = ((r = root) == null ? null : r.findTreeNode(h, k, null)); } finally { Thread w; // 若是當前線程是最後一個讀線程,且有寫線程由於讀鎖而阻塞,則寫線程,告訴它能夠嘗試獲取寫鎖了 if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER | WAITER) && (w = waiter) != null) LockSupport.unpark(w); } return p; } } } return null; }
ForwardingNode是一種臨時結點,在擴容進行中才會出現,因此查找也在擴容的table上進行:
/** * 在新的擴容table——nextTable上進行查找 */ Node<K, V> find(int h, Object k) { // loop to avoid arbitrarily deep recursion on forwarding nodes outer: for (Node<K, V>[] tab = nextTable; ; ) { Node<K, V> e; int n; if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null) return null; for (; ; ) { int eh; K ek; if ((eh = e.hash) == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; if (eh < 0) { if (e instanceof ForwardingNode) { tab = ((ForwardingNode<K, V>) e).nextTable; continue outer; } else return e.find(h, k); } if ((e = e.next) == null) return null; } } }
ReservationNode是保留結點,不保存實際數據,因此直接返回null:
Node<K, V> find(int h, Object k) { return null; }
咱們來看下ConcurrentHashMap是如何計算鍵值對的數目的:
public int size() { long n = sumCount(); return ((n < 0L) ? 0 : (n > (long) Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) n); }
size方法內部實際調用了sumCount方法:
final long sumCount() { CounterCell[] as = counterCells; CounterCell a; long sum = baseCount; if (as != null) { for (int i = 0; i < as.length; ++i) { if ((a = as[i]) != null) sum += a.value; } } return sum; }
能夠看到,最終鍵值對的數目實際上是經過下面這個公式計算的:
$$ sum = baseCount + \sum_{i=0}^nCounterCell[i] $$
若是讀者看過我以前的博文——LongAdder,這時應該已經猜到ConcurrentHashMap的計數思路了。
沒錯,ConcurrentHashMap的計數其實延用了LongAdder分段計數的思路,只不過ConcurrentHashMap並無在內部直接使用LongAdder,而是差很少copy了一份和LongAdder相似的代碼:
/** * 計數基值,當沒有線程競爭時,計數將加到該變量上。相似於LongAdder的base變量 */ private transient volatile long baseCount; /** * 計數數組,出現併發衝突時使用。相似於LongAdder的cells數組 */ private transient volatile CounterCell[] counterCells; /** * 自旋標識位,用於CounterCell[]擴容時使用。相似於LongAdder的cellsBusy變量 */ private transient volatile int cellsBusy;
咱們來看下CounterCell這個槽對象——出現併發衝突時,每一個線程會根據本身的hash值找到對應的槽位置:
/** * 計數槽. * 相似於LongAdder中的Cell內部類 */ static final class CounterCell { volatile long value; CounterCell(long x) { value = x; } }
回顧以前的putval方法的最後,當插入一對鍵值對後,經過addCount方法將計數值爲加1:
/** * 實際的插入操做 * * @param onlyIfAbsent true:僅當key不存在時,才插入 */ final V putVal(K key, V value, boolean onlyIfAbsent) { // … addCount(1L, binCount); // 計數值加1 return null; }
咱們來看下addCount的具體實現(後半部分涉及擴容,暫且不看):
首先,若是counterCells爲null,說明以前一直沒有出現過沖突,直接將值累加到baseCount上;
不然,嘗試更新counterCells[i]
中的值,更新成功就退出。失敗說明槽中也出現了併發衝突,可能涉及槽數組——counterCells的擴容,因此調用fullAddCount方法。
fullAddCount的邏輯和LongAdder中的longAccumulate幾乎徹底同樣,這裏再也不贅述,讀者能夠參考: Java多線程進階(十七)—— J.U.C之atomic框架:LongAdder
/** * 更改計數值 */ 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)) { // 首先嚐試更新baseCount // 更新失敗,說明出現併發衝突,則將計數值累加到Cell槽 CounterCell a; long v; int m; boolean uncontended = true; if (as == null || (m = as.length - 1) < 0 || (a = as[ThreadLocalRandom.getProbe() & m]) == null || // 根據線程hash值計算槽索引 !(uncontended = U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) { fullAddCount(x, uncontended); // 槽更新也失敗, 則會執行fullAddCount 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(); } } }
本文較爲詳細地分析了ConcurrentHashMap的內部結構和典型方法的實現,下一篇將分析ConcurrentHashMap最複雜的部分——擴容/數據轉移。