jdk1.8我認為有幾個主要的難點:
- 同步機制
- 紅黑樹的操作
- 數學原理(重要是基於統計值的算法選取和變量設定)
其中這里只分析同步機制中比較重要的部分。
這篇東西和上一篇文章LongAdder的原理關聯性比較大,如果懂LongAdder的則忽略。
全文主要從以下幾方面來講:
- 為什么1.8 concurrentHashMap要重構
- 1.8 concurrentHashMap的基本設計
- 1.8concurrentHashMap的難點方法解析
- 個人存在的疑惑點
這個類是寫博客至今研究過的難度最大的類,前前后后看了很久才大致有點感覺。所以在寫的時候只能通過先寫第二第三點來溫習知識才能寫第一點(所以一些語言的順序性可能會很奇怪)。
為什么1.8 concurrentHashMap要重構
我們記得jdk1.7中concurrentHashMap是用了分段鎖的設計原理,segment的數量取決於concurrencyLevel;
然后rehash的時候是在segment(分段鎖)里面操作的,雖然說是沒有阻塞整個哈希表,但是是會阻塞某個分段鎖。
1.8 concurrentHashMap中拋棄了分段鎖,並且把put流程的控制粒度更加細化,細化的粒度降低到當前哈希表中的一個HashEntry。
而且整個表需要resize的時候不會阻塞任何一個線程,當容量大並且需要resize的時候,可能並發量越高resize的速度還會越快。
因此可以說1.8的concurrentHashMap提升了並發吞吐量和減少了resize的時候的阻塞時間,究竟他是怎么做到的呢?
1.8 concurrentHashMap的基本設計
類繼承體系和之前的1.7 concurrentHashMap類似。
但是這里沒有通過分段鎖來保證並發的吞吐量。
先看看基本的類成員變量
/**
* Minimum number of rebinnings per transfer step. Ranges are
* subdivided to allow multiple resizer threads. This value
* serves as a lower bound to avoid resizers encountering
* excessive memory contention. The value should be at least
* DEFAULT_CAPACITY.
*/
private static final int MIN_TRANSFER_STRIDE = 16;
/**
* The number of bits used for generation stamp in sizeCtl.
* Must be at least 6 for 32bit arrays.
*/
private static int RESIZE_STAMP_BITS = 16;
/**
* The maximum number of threads that can help resize.
* Must fit in 32 - RESIZE_STAMP_BITS bits.
*/
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;
MIN_TRANSFER_STRIDE: 意思是resize時候每個線程每次最小的搬運量(搬運多少個entry),范圍會繼續細分以便可以允許多個resize線程。
RESIZE_STAMP_BITS :位的個數來用來生成戳,用在sizeCtrl里面;
MAX_RESIZERS:最大參與resize的線程數量;
RESIZE_STAMP_SHIFT:用來記錄在sizeCtrl中size戳的位偏移數。
/*
* Encodings for Node hash fields. See above for explanation.
*/
static final int MOVED = -1; // hash for forwarding nodes
static final int TREEBIN = -2; // hash for roots of trees
static final int RESERVED = -3; // hash for transient reservations
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
/** Number of CPUS, to place bounds on some sizings */
static final int NCPU = Runtime.getRuntime().availableProcessors();
上面定義了一些特別的哈希值來表征節點的狀態:
-1:forwarding nodes 主要作用是表征一個節點已經被處理干凈(resize的時候被轉移到新表了)
-2:表示樹的根節點
-3:表示transient
HASH_BITS:31個1用來計算普通的node的哈希碼
NCPU:當前可用的處理器的核數量
//也是用節點數組來構成哈希表,在第一次插入的時候會懶初始化,size是2的整數次冪,直接通過iterators來訪問
transient volatile Node<K,V>[] table;
//下一個要用的數組,當在進行resizing的時候非空
private transient volatile Node<K,V>[] nextTable;
//用來計算整個表的size,和longadder里面的base一致
private transient volatile long baseCount;
//用來控制表初始化,當為負數值。各種狀態下這個int的值如下:
//初始化的:-1
//resize:-(1 + 被激活的參與resize的數量)
//表為空:表的initial size,如果沒有這個值則為0
//初始化后:該表下次應該resize的值,等於當前表的size的0.75倍
private transient volatile int sizeCtl;
//當resizing的時候下一個tab下標索引值(當前值+1)
private transient volatile int transferIndex;
//當resize和創建counterCells的時候的自選鎖,和longadder一致
private transient volatile int cellsBusy;
//和longadder的cells一致
private transient volatile CounterCell[] counterCells;
接下來我們看看構造方法
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
//concurrencyLevel表示估計的參與並發更新的線程數量,必須比初始化容量的要大
if (initialCapacity < concurrencyLevel) // Use at least as many bins
initialCapacity = concurrencyLevel; // as estimated threads
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
//整個構造方法過程就是為了能到這一步。
//初始化只有這一個實際的賦值方法,因此是懶初始化的,當前的map是null的,sizeCtl存儲的值是當前要初始化的map的size值
this.sizeCtl = cap;
}
1.8concurrentHashMap的難點方法解析
其中最難也是最核心的方法肯定是put方法。
注:以下的模擬值全部按照默認初始化值進行計算
public V put(K key, V value) {
return putVal(key, value, false);
}
putVal很長,解釋直接注釋在代碼內;
建議自己跟讀代碼的時候先不要殺進去C和E的部分,看大概掃一眼正常的流程。建議先看A,B和D。
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
//concurrentHashMap中 key和value都不能為空
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
//自旋操作,每次都把當前的table賦給tab
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
//A:concurrentHashMap懶初始化,初始化表
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//B:找到應該put的index對應的節點,並賦值給f
//如果node數組下標對應的node為空,則cas新建,由於自旋失敗了也無所謂
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
//C:這種情況是在resize
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
//D:正常熟悉的哈希表的put流程
else {
V oldVal = null;
//針對單個node節點加鎖
synchronized (f) {
//雙重檢測
if (tabAt(tab, i) == f) {
//正常的節點hash值>0
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;
}
}
}
//樹節點hash值為-2
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;
}
}
}
}
//如果不是onlyIfAbsent為true,且已經找到了key對應的node的話都會來到這一步,因為都會插入成功
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
//E:size+1,里面會觸發resize操作
addCount(1L, binCount);
return null;
}
A:initTable
/**
* Initializes table, using the size recorded in sizeCtl.
*/
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
//自旋操作,每次都對tab賦值而且判斷tab的tab數組的長度
while ((tab = table) == null || tab.length == 0) {
//如果搶鎖失敗(sizeCtl是作為自選鎖使用),則告訴cpu可以讓出時間片
//其他線程如果初始化表成功則自旋結束退出方法
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
//此時搶鎖成功
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;
//sizeCtl置為n的0.75倍
sc = n - (n >>> 2);
}
} finally {
//賦值順便解鎖
sizeCtl = sc;
}
//自旋結束
break;
}
}
return tab;
}
先看E:這樣會更好理解。
方法頭的注釋意思大概是:
增加表容量的計數,如果這個表需要resize但還沒開始resize,則初始化transfer(這個東西用來進行resize)。如果已經開始resize了,則看看需不需要加入幫助一起resize。然后重新檢查表的計數看看需不需要再次resize。
以下的代碼片段第一次看的時候最好先忽略A部分
/**
* 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
*/
//這個方法既可以做加法(put的時候調用)又可以做減法(remove或者clear的時候)
//只有對size做加法的時候才用檢查resize
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
//A:以下代碼和longadder的add操作思路完全一致
//這個方法等同於longAdder的Add
//然后fullAddCount等同於Striped64的longAccumulate,可以參考我之前的博客
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賦值為當前的哈希表的size
s = sumCount();
}
//這里要開始判斷到底需不需要resize
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
//短路與的話看如何能夠進入代碼塊,這里代碼風格和以往一致,判斷的同時賦值
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
//來到這里相當於就一定要resize了,至於這個戳有個印象就好,每次resize每個線程都確認一個戳!標識當前的size(當前的2的多次整數次冪)
//生成一個戳 算法是Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
//如果n=16,則生成的值為0000000000000000010000000000011011(27和2的15次方相或)
int rs = resizeStamp(n);
if (sc < 0) {
//size<0表征當前正在resize
//A :這里應該算是自旋的停止條件: 能夠到達下一個if需要經過5個條件:
//1. 可以對比一下上面和C的兩個值,發現應該是要相等的
// 2.sc!=rs+1;這個暫時不知道是什么意思
//resizer線程不能超過最大允許數量;nextTable非空;transferIndex>=0(resize沒結束)
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
//B : 每次將這個值SIZECTL cas+1 成功的話參與transfer
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
//C: 第一個參與resize的線程:SIZECTL置為1000000000001101100000000000000010,這個值后面+2是為了計算上面的停止條件的,不能讓resizer線程無限制增加
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
//到了這里就是resize完成了,然后通過下一個while自旋判斷是否需要再次resize
s = sumCount();
}
}
}
接下來看transfer方法(最難方法),方法頭說了這個方法就是將每個bin從舊的table轉移到新的table;
以下方法建議先看主線方法E,再看ABCD
/**
* 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表征的是每一個thread進來的時候要搬運的量
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;
}
//第一次進來resize的時候初始化下一次需要的table,
//transferIndex賦值為n,意味着從后往前循環進行表轉移
nextTable = nextTab;
transferIndex = n;
}
int nextn = nextTab.length;
//這個節點第一次看會很懵,在這個方法中是用來表征當前tab[i]的節點不需要被搬運的意思
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
//自旋操作並初始化i和bound,i為操作索引,bound為下限
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
//A advance表征是否繼續走下去:1.是否繼續--i來轉移表 2.是否繼續cas TRANSFERINDEX來獲取當前的i值
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))) {
//第一次進入的時候如果到達了這里則接到了當前應該進行的任務:負責搬運[nextBound:i]之間的內容
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
//B 當線程到達這里則證明家搬運結束,或者異常停止
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
//如果其他人已經設置了這個標志位,則正式完成並return
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
//這個判定條件在addCount的A段方法解釋過
//意思就是雙重校驗失敗的意思,其他線程已經做過了這個操作了
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
//C 如果領取到了的任務i對應的tab[i] 為空,那恭喜了把fwd貼上去然后繼續領活吧,cas失敗也不要緊~下次來看看tab[0]是不是被打標簽了,是的話恭喜了,繼續加班吧,不是的話就再試試cas總會有加班的一天的
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
//D 意思是就是已經被別人打上了fwd的表情,可以重新領取任務了
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
//E搬運的主線流程
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;
//這里的高低位的分法其實和1.7 concurrentHashMap一樣的邏輯,這里不解釋了
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);
//注意這里! 將第tab的第i個項的node設為fwd,這樣就意味着這個節點不需要再次被搬運了,同時他的hash值=-1
setTabAt(tab, i, fwd);
//搬運了一次,會重置i和bound繼續自旋領取任務作為碼農的獎勵,這里別以為幫大家搬磚一次就完事了,就像你進了單位以為干完活就能早下班,實際上領導看你有空會給你繼續派活直到整個組都沒活干為止
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;
}
}
}
}
}
}
這個方法就是神一樣的方法,解決了1.7concurrentHashMap中有可能resize影響性能的問題,原理就是讓每一個put完的線程,或者想要put的線程到了整個表需要resize的時候都過來進入resize流水線工作,直到有一個線程說自己已經全部弄完了,方法才能返回。
以前的正常設計是resize的時候整個表就阻塞住了,但是現在resize的時候,想要操作的線程都會來參與一起resize,這么一來其他的線程就不用干等着了。
相當於想完成一個項目,大家伙都先做完了一個活,然后有一個人分配的活最多,而且都是阻塞的活,那這個時候大家干等着還不如一起幫他來完成這個活,這個被派到搬磚臟活的人也很聰明,把該搬的磚頭分成一份份,讓其他同事可以有序的完成,這個方法展現了團結友愛的精神也展現了被派了臟活的人的機智和有條不紊。
現在回過頭來看putVal方法的C部分:
現在來看代碼就很好懂了,和addCount的下半部分大致類似,只要記住當前的狀態是當前線程還沒有put的狀態,而且已經有線程開始進行流水線搬磚resize的工作了。
/**
* Helps transfer if a resize is in progress.
*/
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;
}
至此put方法講解完畢,如果這個方法能夠看懂,其他方法難度應該都不大,寫不動了,下次有空再看看其他方法。
個人疑惑
還有一一些疑問請教大神們:
- addCount方法里面的一個判定條件sc!=rs+1是什么意思?
請知道答案的大腿不吝賜教,謝謝!