HashMap是集合框架中非常常用的一個成員,但是HashMap並不是線程安全的。在併發場景下,可以使用Collections類的靜態方法synchronizedMap使用線程安全的Map,但是synchronizedMap方法返回的SynchronizedMap實例實際上是通過在各個方法中添加synchronized同步鎖來保證線程安全的,頻繁的加鎖和開鎖會導致性能的嚴重下降。推薦使用ConcurrentHashMap來滿足併發場景下對HashMap的需求。
一、實現原理
程序就是算法加數據結構。我們從ConcurrentHashMap的數據結構,以及put方法和擴容方法transfer方法所體現的算法思想,來看一下ConcurrentHashMap的實現原理。
總的來說,ConcurrentHashMap使用了“數組+鏈表+紅黑樹”的數據結構。
1、它的基礎數據結構,或者說最外層數據結構是數組,鏈表和紅黑樹都是存放在數組中的;
2、數組中存放的是Node的實例,Node是ConcurrentHashMap定義的內部類,包括key、value、hash、next等成員屬性。顧名思義,key和value就是要存儲的鍵值對;hash一般來說是key的hash值,特殊情況參考第二章第三小節transfer方法源碼後面的說明;next執行下一個Node實例;
3、數組中存放的Node實例,對於鏈表,是鏈表的頭節點;對於紅黑樹,則是特定封裝的一個特殊節點TreeBin,節點中不存儲鍵值對,只有next和hash兩個成員屬性有意義,hash值爲固定值-2,next則指向存儲數據的紅黑樹節點;
4、一個數組的成員中存放的是鏈表還是紅黑樹,取決於該位置存儲的節點的數量。在JDK1.8的情況下,如果當鏈表中的節點數量大於等於8,則將鏈表樹化成紅黑樹的結構;如果紅黑樹中的元素小於等於6的時候,則將紅黑樹去樹化成鏈表結構。
5、對於一個key值,ConcurrentHashMap找其在數組中對應位置的方法,並不是遍歷數組,而是計算(key的hash)和(數組長度-1)進行邏輯與運算的結果,該結果就是在數組中的位置索引。
6、ConcurrentHashMap擴容的時機:
- 鏈表中節點數增加到8個及以上的時候,觸發樹化操作,此時會首先判斷數組長度是否小於64,滿足條件則擴容;
- 存入新的鍵值對後,會調用addCount方法對應增加記錄的元素個數。當元素個數達到閾值(數組當前長度的0.75倍)會觸發擴容
二、重要方法的源碼分析
1、put方法
put方法和putIfAbsent方法都是通過putValue方法來實現的。源碼及分析如下:
final V putVal(K key, V value, boolean onlyIfAbsent) {
// key和value都不允許爲null
if (key == null || value == null) throw new NullPointerException();
// 計算哈希值
int hash = spread(key.hashCode());
// 這裏“bin”的概念相當於一組節點(Node鏈表),即binCount就是鏈表或者紅黑樹中的Node實例數
// 當鏈表中的節點數(binCount)大於或者等於TREEIFY_THRESHOLD(數值爲8)的時候會被替換成紅黑樹
int binCount = 0;
// 循環遍歷table中的節點
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
// 情況1:table爲null或空,此時需要初始化table
if (tab == null || (n = tab.length) == 0)
tab = initTable();
// 情況2:key-value放入的目標節點爲空
// 目標節點在數組中的index是通過將"數組長度減一的數值"和"key的哈希值"相與得到的
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 利用CAS操作創建目標節點可以避免加鎖
if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
// 情況3:hash = MOVED表示節點類型是ForwardingNode,這種節點只用在resize的過程中
// 說明此時的ConcurrentHashMap實例正在擴容,所以需要當前線程幫忙去完成這個過程
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
// 情況4:這種就是正常的數組的目標位置已存在節點,此時需要把目標節點放入目標位置的鏈表或者紅黑樹中
else {
V oldVal = null;
// 向數組中目標位置的鏈表或者紅黑樹中添加目標節點,此時需要加鎖
synchronized (f) {
// 這裏的判斷是在確認目標位置的節點f沒有在“發生判斷“和”加鎖完成“的短暫間隔內被修改過
if (tabAt(tab, i) == f) {
//
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
// 如果節點e的hash和key的hash相等且e.key和key相等,就可以認爲Map中已經存在該key了
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
// 如果是putIfAbsent方法,此時就不進行添加了
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
// e的下一個節點爲null,說明e已經是最後一個節點,說明遍歷全部節點後未發現相同key值,
// 此時直接把目標節點加到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;
}
}
}
}
// 這裏同步鎖已經解開了
// binCount如果等於0,說明加鎖後實際上避開了所有會把元素添加進去的判斷
if (binCount != 0) {
// 樹化臨界值,如果大於這個值,就用紅黑樹替代鏈表
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
// 當前ConcurrentHashMap實例中包含的元素數量加1
addCount(1L, binCount);
return null;
}
獲取節點在table數組中的位置:index = hash & (table.length-1)。通過hash和數組長度-1相與,可以得到table.length個不同的結果,正好放入到長度爲table.length的數組中。例如table.length=16,那麼hash & (16-1) 的結果,只和hash最低的4位有關,hash的高位和0相與都是0。
2、initTable方法
/**
* Initializes table, using the size recorded in sizeCtl.
*/
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
// 這裏用到成員屬性sizeCtl:這裏如果sizeCtl小於0,則有其他線程正在進行初始化或者擴容,該操作不允許並行執行,讓出CPU
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
// 用Unsafe類的CAS方法將sizeCtl設置爲-1
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
// 判斷table是不是還沒有初始化
if ((tab = table) == null || tab.length == 0) {
// sc=sizeCtl如果是0,table就使用默認容量;如果大於0,就使用就使用sizeCtl的值作爲容量
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
// sc = 3/4 * n. 用移位操作替換乘法,性能會高很多
sc = n - (n >>> 2);
}
} finally {
// 初始化完成,更新sizeCtl的值
sizeCtl = sc;
}
break;
}
}
return tab;
}
註釋:
1、成員變量sizeCtl:table初始化和擴容相關的成員屬性。
1)初始化過程中:sizeCtl = -1;
2)擴容過程中:sizeCtl爲其他負值:-(1+激活的擴容線程數)
3)初始化之前:如果爲ConcurrentHashMap實例傳入了初始容量,那麼sizeCtl爲該初始容量;如果沒有設置初始容量,那麼sizeCtl=0;
4)初始化完成後,sizeCtl指示的是擴容的閾值,這個版本是當前容量的0.75倍
2、Unsafe類的CAS方法:Unsafe類調用native方法實現原子性操作CAS操作,用來通過無鎖的方式線程安全地修改屬性的值。
這裏的CAS方法有4個參數:
1)this:當前ConcurrentHashMap的實例
2)SIZECTL:成員屬性sizeCtl在當前ConcurrentHashMap實例中的偏移,用於定位sizeCtl在內存中的位置;
3)sc是CAS操作中sizeCtl的期望值;
4)-1是sizeCtl修改的目標值。
3、transfer方法
/**
* 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;
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
// 如果傳入的nextTab爲null,就給nextTab賦一個容量爲原tab兩倍的新數組
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 = n;
}
int nextn = nextTab.length;
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
// 循環的目的就是--i,從而實現從後到前對table的遍歷
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
// for循環的第一輪的while循環,一般都是執行到這裏然後才能結束while循環的即i的初始值實際上是nextIndex - 1
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只在擴容期間使用,擴容完成則置空
nextTable = null;
// 將table指向擴容後的數組
table = nextTab;
// sizeCtl表示擴容的閾值,這裏sizeCtl = 1.5n,n是原table的容量,即sizeCtl是新table容量的0.75倍
sizeCtl = (n << 1) - (n >>> 1);
return;
}
// 這裏CAS的目的是令sizeCtl = 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; // recheck before commit
}
}
// 如果tab[i] == null,則設置tab[i] = fwd
// 對照下一條else if,這裏是用來併發控制的
else if ((f = tabAt(tab, i)) == null)
// 這裏如果CAS修改失敗,advance=false,則下一輪for循環不會進入while循環體,i不會自減,依然訪問當前位置的節點
advance = casTabAt(tab, i, null, fwd);
// MOVED是fwd的hash,如果遍歷到的元素hash = MOVED,說明這個元素已經被其他線程處理過
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
// 這種情況就是正常的、需要當前線程去複製的節點了
else {
// 對當前節點加鎖,同一個節點只需要一個線程處理
synchronized (f) {
// 判斷tabAt(tab, i) == f是爲了避免在加鎖前的短暫時間內節點已經被其他線程修改了
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
// hash >= 0說明這是一個Node的實例;在這裏執行函數複製工作
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;
// 這裏需要注意的是,當前節點的下一個節點(next),是上一次循環中創建的節點(ln或者hn)
// 也就是說,隨着p=p.next的迭代,實際上創建出來的鏈表是一個反序鏈表
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
// 假設原數組長度n對應的二進制最高位是第x位,那麼分別在nextTab的i和i+n位置中保存hash值的二進制中,第x位爲0和1節點
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
// 當前線程處理完當前節點,就將當前節點設置爲fwd,這樣其他線程看到節點內容是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;
}
}
// 如果擴容後節點數量低於或等於去樹化的門限(UNTREEIFY_THRESHOLD=6),則去樹化,轉換成鏈表形式
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);
// 當前線程處理完當前節點,就將當前節點設置爲fwd,這樣其他線程看到節點內容是fwd就不會再處理了
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}
hash值和節點Node類型的關係:
- 鏈表節點:hash >= 0
- ForwardingNode:hash=MOVED=-1(構造器中設置)
- TreeBin:hash=TREEBIN=-2(構造器中設置)
- ReservationNode:hash=RESERVED=-3(構造器中設置)
- TreeNode:這種節點只用在TreeBin的內部,所以在數組中檢索到的沒有這種類型
4、get方法
get方法比較簡單,主要是處理了四種情況:直接找到了目標節點,在樹節點中查找目標節點,在鏈表節點中查找目標節點,以及在沒找到的時候返回null。
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code key.equals(k)},
* then this method returns {@code v}; otherwise it returns
* {@code null}. (There can be at most one such mapping.)
*
* @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;
// 獲取hash
int h = spread(key.hashCode());
// key對應的節點在數組中的index,是通過(table.length-1) & key.hash計算出來的,不需要遍歷,降低時間複雜度
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
// 如果找到的節點key值和要搜索的key相等,就直接返回該節點的value
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
// hash值小於0,說明這是紅黑樹的頭結點,直接從樹裏面去找value
else if (eh < 0)
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;
}
(未完待續)