J.U.C之Java併發容器:ConcurrentHashMap
HashMap是我們用得非常頻繁的一個集合,但是由於它是非執行緒安全的,在多執行緒環境下,put操作是有可能產生死迴圈的,導致CPU利用率接近100%。為了解決該問題,提供了Hashtable和Collections.synchronizedMap(hashMap)兩種解決方案,但是這兩種方案都是對讀寫加鎖,獨佔式,一個執行緒在讀時其他執行緒必須等待,吞吐量較低,效能較為低下。故而Doug Lea大神給我們提供了高效能的執行緒安全HashMap:ConcurrentHashMap。
ConcurrentHashMap的實現
ConcurrentHashMap作為Concurrent一族,其有著高效地併發操作,相比Hashtable的笨重,ConcurrentHashMap則更勝一籌了。
在1.8版本以前,ConcurrentHashMap採用分段鎖的概念,使鎖更加細化,但是1.8已經改變了這種思路,而是利用CAS+Synchronized來保證併發更新的安全,當然底層採用陣列+連結串列+紅黑樹的儲存結構。
我們從如下幾個部分全面瞭解ConcurrentHashMap在1.8中是如何實現的:
- 重要概念
- 重要內部類
- ConcurrentHashMap的初始化
- put操作
- get操作
- size操作
- 擴容
- 紅黑樹轉換
重要概念
ConcurrentHashMap定義瞭如下幾個常量:
// 最大容量:2^30=1073741824
private static final int MAXIMUM_CAPACITY = 1 << 30;
// 預設初始值,必須是2的幕數
private static final int DEFAULT_CAPACITY = 16;
//
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;
// 連結串列轉紅黑樹閥值,> 8 連結串列轉換為紅黑樹
static final int TREEIFY_THRESHOLD = 8 ;
//樹轉連結串列閥值,小於等於6(tranfer時,lc、hc=0兩個計數器分別++記錄原bin、新binTreeNode數量,<=UNTREEIFY_THRESHOLD 則untreeify(lo))
static final int UNTREEIFY_THRESHOLD = 6;
//
static final int MIN_TREEIFY_CAPACITY = 64;
//
private static final int MIN_TRANSFER_STRIDE = 16;
//
private static int RESIZE_STAMP_BITS = 16;
// 2^15-1,help resize的最大執行緒數
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
// 32-16=16,sizeCtl中記錄size大小的偏移量
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
// forwarding nodes的hash值
static final int MOVED = -1;
// 樹根節點的hash值
static final int TREEBIN = -2;
// ReservationNode的hash值
static final int RESERVED = -3;
// 可用處理器數量
static final int NCPU = Runtime.getRuntime().availableProcessors();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
上面是ConcurrentHashMap定義的常量,簡單易懂,就不多闡述了。下面介紹ConcurrentHashMap幾個很重要的概念。
- table:用來存放Node節點資料的,預設為null,預設大小為16的陣列,每次擴容時大小總是2的冪次方;
- nextTable:擴容時新生成的資料,陣列為table的兩倍;
- Node:節點,儲存key-value的資料結構;
- ForwardingNode:一個特殊的Node節點,hash值為-1,其中儲存nextTable的引用。只有table發生擴容的時候,ForwardingNode才會發揮作用,作為一個佔位符放在table中表示當前節點為null或則已經被移動
- sizeCtl:控制識別符號,用來控制table初始化和擴容操作的,在不同的地方有不同的用途,其值也不同,所代表的含義也不同
- 負數代表正在進行初始化或擴容操作
- -1代表正在初始化
- -N 表示有N-1個執行緒正在進行擴容操作
- 正數或0代表hash表還沒有被初始化,這個數值表示初始化或下一次進行擴容的大小
重要內部類
為了實現ConcurrentHashMap,Doug Lea提供了許多內部類來進行輔助實現,如Node,TreeNode,TreeBin等等。下面我們就一起來看看ConcurrentHashMap幾個重要的內部類。
Node
作為ConcurrentHashMap中最核心、最重要的內部類,Node擔負著重要角色:key-value鍵值對。所有插入ConCurrentHashMap的中資料都將會包裝在Node中。定義如下:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val; //帶有volatile,保證可見性
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; }
/** 不允許修改value的值 */
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)));
}
/** 賦值get()方法 */
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
在Node內部類中,其屬性value、next都是帶有volatile的。同時其對value的setter方法進行了特殊處理,不允許直接呼叫其setter方法來修改value的值。最後Node還提供了find方法來賦值map.get()。
TreeNode
我們在學習HashMap的時候就知道,HashMap的核心資料結構就是連結串列。在ConcurrentHashMap中就不一樣了,如果連結串列的資料過長是會轉換為紅黑樹來處理。當它並不是直接轉換,而是將這些連結串列的節點包裝成TreeNode放在TreeBin物件中,然後由TreeBin完成紅黑樹的轉換。所以TreeNode也必須是ConcurrentHashMap的一個核心類,其為樹節點類,定義如下:
static final class TreeNode<K,V> extends Node<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
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);
}
//查詢hash為h,key為k的節點
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
原始碼展示TreeNode繼承Node,且提供了findTreeNode用來查詢查詢hash為h,key為k的節點。
TreeBin
該類並不負責key-value的鍵值對包裝,它用於在連結串列轉換為紅黑樹時包裝TreeNode節點,也就是說ConcurrentHashMap紅黑樹存放是TreeBin,不是TreeNode。該類封裝了一系列的方法,包括putTreeVal、lookRoot、UNlookRoot、remove、balanceInsetion、balanceDeletion。由於TreeBin的程式碼太長我們這裡只展示構造方法(構造方法就是構造紅黑樹的過程):
static final class TreeBin<K,V> extends Node<K,V> {
TreeNode<K, V> root;
volatile TreeNode<K, V> first;
volatile Thread waiter;
volatile int lockState;
static final int WRITER = 1; // set while holding write lock
static final int WAITER = 2; // set when waiting for write lock
static final int READER = 4; // increment value for setting read lock
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);
}
/** 省略很多程式碼 */
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
通過構造方法是不是發現了部分端倪,構造方法就是在構造一個紅黑樹的過程。
ForwardingNode
這是一個真正的輔助類,該類僅僅只存活在ConcurrentHashMap擴容操作時。只是一個標誌節點,並且指向nextTable,它提供find方法而已。該類也是整合Node節點,其hash為-1,key、value、next均為null。如下:
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;
}
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;
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
建構函式
ConcurrentHashMap提供了一系列的建構函式用於建立ConcurrentHashMap物件:
public ConcurrentHashMap() {
}
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;
}
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
this.sizeCtl = DEFAULT_CAPACITY;
putAll(m);
}
public ConcurrentHashMap(int initialCapacity, float loadFactor) {
this(initialCapacity, loadFactor, 1);
}
public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
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);
this.sizeCtl = cap;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
初始化: initTable()
ConcurrentHashMap的初始化主要由initTable()方法實現,在上面的建構函式中我們可以看到,其實ConcurrentHashMap在建構函式中並沒有做什麼事,僅僅只是設定了一些引數而已。其真正的初始化是發生在插入的時候,例如put、merge、compute、computeIfAbsent、computeIfPresent操作時。其方法定義如下:
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
//sizeCtl < 0 表示有其他執行緒在初始化,該執行緒必須掛起
if ((sc = sizeCtl) < 0)
Thread.yield();
// 如果該執行緒獲取了初始化的權利,則用CAS將sizeCtl設定為-1,表示本執行緒正在初始化
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;
// 下次擴容的大小
sc = n - (n >>> 2); ///相當於0.75*n 設定一個擴容的閾值
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
初始化方法initTable()的關鍵就在於sizeCtl,該值預設為0,如果在建構函式時有引數傳入該值則為2的冪次方。該值如果 < 0,表示有其他執行緒正在初始化,則必須暫停該執行緒。如果執行緒獲得了初始化的許可權則先將sizeCtl設定為-1,防止有其他執行緒進入,最後將sizeCtl設定0.75 * n,表示擴容的閾值。
put操作
ConcurrentHashMap最常用的put、get操作,ConcurrentHashMap的put操作與HashMap並沒有多大區別,其核心思想依然是根據hash值計算節點插入在table的位置,如果該位置為空,則直接插入,否則插入到連結串列或者樹中。但是ConcurrentHashMap會涉及到多執行緒情況就會複雜很多。我們先看原始碼,然後根據原始碼一步一步分析:
public V put(K key, V value) {
return putVal(key, value, false);
}
final V putVal(K key, V value, boolean onlyIfAbsent) {
//key、value均不能為null
if (key == null || value == null) throw new NullPointerException();
//計算hash值
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
// table為null,進行初始化工作
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//如果i位置沒有節點,則直接插入,不需要加鎖
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
}
// 有執行緒正在進行擴容操作,則先幫助擴容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
//對該節點進行加鎖處理(hash值相同的連結串列的頭節點),對效能有點兒影響
synchronized (f) {
if (tabAt(tab, i) == f) {
//fh > 0 表示為連結串列,將該節點插入到連結串列尾部
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
//hash 和 key 都一樣,替換value
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;
//連結串列尾部 直接插入
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;
}
}
}
}
if (binCount != 0) {
// 如果連結串列長度已經達到臨界值8 就需要把連結串列轉換為樹結構
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
//size + 1
addCount(1L, binCount);
return null;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
按照上面的原始碼,我們可以確定put整個流程如下:
- 判空;ConcurrentHashMap的key、value都不允許為null
- 計算hash。利用方法計算hash值。
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
- 1
- 2
- 3
- 遍歷table,進行節點插入操作,過程如下:
- 如果table為空,則表示ConcurrentHashMap還沒有初始化,則進行初始化操作:initTable()
- 根據hash值獲取節點的位置i,若該位置為空,則直接插入,這個過程是不需要加鎖的。計算f位置:i=(n - 1) & hash
- 如果檢測到fh = f.hash == -1,則f是ForwardingNode節點,表示有其他執行緒正在進行擴容操作,則幫助執行緒一起進行擴容操作
- 如果f.hash >= 0 表示是連結串列結構,則遍歷連結串列,如果存在當前key節點則替換value,否則插入到連結串列尾部。如果f是TreeBin型別節點,則按照紅黑樹的方法更新或者增加節點
- 若連結串列長度 > TREEIFY_THRESHOLD(預設是8),則將連結串列轉換為紅黑樹結構
- 呼叫addCount方法,ConcurrentHashMap的size + 1
這裡整個put操作已經完成。
get操作
ConcurrentHashMap的get操作還是挺簡單的,無非就是通過hash來找key相同的節點而已,當然需要區分連結串列和樹形兩種情況。
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());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
// 搜尋到的節點key與傳入的key相同且不為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) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}