JDK原始碼分析系列--ConcurrentHashMap(1.8)
阿新 • • 發佈:2018-12-17
定義變數
/** * node陣列最大容量 */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * 預設容量 */ private static final int DEFAULT_CAPACITY = 16; /** * 陣列可能最大值,需要與toArray()相關方法關聯 */ static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 併發級別,遺留下來的,相容以前的版本 */ private static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * 負載因子 */ private static final float LOAD_FACTOR = 0.75f; /** * 連結串列轉紅黑樹的閥值 */ static final int TREEIFY_THRESHOLD = 8; /** * 紅黑樹轉化為連結串列的閥值 */ static final int UNTREEIFY_THRESHOLD = 6; /** * 連結串列轉化紅黑樹最小的node陣列大小 */ static final int MIN_TREEIFY_CAPACITY = 64; private static final int MIN_TRANSFER_STRIDE = 16; private static int RESIZE_STAMP_BITS = 16; /** * help resize的最大執行緒數 */ private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1; /** * sizeCtl中記錄size大小的偏移量 */ private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS; static final int MOVED = -1; // forwarding nodes的hash值 static final int TREEBIN = -2; // 樹節點hash值 static final int RESERVED = -3; // ReservationNode 的hash值 /** * Node陣列 */ transient volatile Node<K,V>[] table; /** * 用來控制表初始化和擴容的,預設值為0,當在初始化的時候指定了大小,這會將這個大小儲存在sizeCtl中,大小為陣列的0.75 * 當為負的時候,說明表正在初始化或擴張, -1表示初始化,-(1+n) n:表示活動的擴張執行緒 */ private transient volatile int sizeCtl;
構造方法
/** * sizeCtl的值為初始容量的1.5倍initialCapacity+1後計算table的大小, * 如initialCapacity=10,向上取2的倍數是16, * initialCapacity=11,向上取2的倍數是32 */ 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; }
計算陣列容量
/** * 陣列容量計算,c向上取2點倍數,如果c的值為10,則返回16,如果c為17則返回32,以此類推 */ private static final int tableSizeFor(int c) { int n = c - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
PUT方法分析
public V put(K key, V value) {
return putVal(key, value, false);
}
/**
* put 核心
*/
final V putVal(K key, V value, boolean onlyIfAbsent) {
//當key或value為null丟擲空指向異常
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;
if (tab == null || (n = tab.length) == 0)//node陣列為空時初始化
tab = initTable();
//計算陣列下標,並把值賦給首節點f,當f為空時
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
//做cas操作,如果成功,put結束,如果不成功,說明有併發存在,進入下一輪迴圈
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break;
}
//f的hash值為MOVED,說明正在擴容
else if ((fh = f.hash) == MOVED)
//幫助資料遷移
tab = helpTransfer(tab, f);
else {//如果走在這裡,那說明首節點f不為空
V oldVal = null;
synchronized (f) {//獲取陣列下標首節點f的鎖
if (tabAt(tab, i) == f) {
//首節點的hash值大於0,說明是連結串列
if (fh >= 0) {
binCount = 1;//記錄連結串列的長度
for (Node<K,V> e = f;; ++binCount) {
K ek;
//key值相等時的操作
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) {//當f節點為紅黑樹
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;
}
}
}
addCount(1L, binCount);
return null;
}
初始化Node陣列
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說明被其他執行緒搶佔了鎖
Thread.yield();
//搶佔了鎖,cas操作一下,將SIZECTL設定為-1
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
//將n賦值為預設容量16
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);//sc為12
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
連結串列轉紅黑樹
private final void treeifyBin(Node<K,V>[] tab, int index) {
Node<K,V> b; int n, sc;
if (tab != null) {
//當node陣列長度小於64時,則進行陣列擴容操作
if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
tryPresize(n << 1);
//首節點b
else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
synchronized (b) {//對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;
}
//將紅黑樹放到陣列該下標位置
setTabAt(tab, index, new TreeBin<K,V>(hd));
}
}
}
}
}
資料遷移方法
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
// stride 在單核下直接等於 n,多核模式下為 (n>>>3)/NCPU,最小值是 16
// stride 可以理解為”步長“,有 n 個位置是需要進行遷移的
// 將這 n 個任務分為多個任務包,每個任務包有 stride 個任務
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE;
if (nextTab == null) {
try {
// 容量翻倍
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 也是 ConcurrentHashMap 的屬性,用於控制遷移的位置
transferIndex = n;
}
int nextn = nextTab.length;
//正在被遷移的 Node,hash值設定為MOVED
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
//advance 指的是做完了一個位置的遷移工作,可以準備做下一個位置的了
boolean advance = true;
boolean finishing = false;
//i是陣列的索引位置,bound是邊界
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
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;
}
//cas操作對sizeCtl-1,完成自己的任務
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n;
}
}
//如果索引位置為空,則放入剛剛初始化的ForwardingNode節點
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)//代表位置已經遷移過了
advance = true;
else {
synchronized (f) {//對資料首節點加鎖,處理該位置的遷移工作
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
if (fh >= 0) {//連結串列節點
int runBit = fh & n;
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);
}
//ln連結串列節點放到陣列i位置
setTabAt(nextTab, i, ln);
//hn連結串列節點放到陣列i+n位置
setTabAt(nextTab, i + n, hn);
//願陣列位置i上設定為fwd,說明已經遷移完
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;
}
}
}
}
}
}