什么是CHM ?
1、CHM 全稱:ConcurrentHashMap 是J.U.C工具包中所提供的,顯然是個map集合,而且是個執行緒安全的HashMap,既然是執行緒安全的那么顯然下并發場景下用的還是比較頻繁的,
2、CHM作用和HashMap差不太多,也可以說是一個執行緒安全的HashMap
3、使用和普通的Map是一致的,包含put,get 方法等
ConcurrentHashMap chmMap = new ConcurrentHashMap();
chmMap.put("key","value");
chmMap.get("key");
CHM的發展
這里為什么說下它的發展呢,是因為在jdk1.7和jdk1.8這2個版本下發生了一些比較大的變化(即對它進行的優化升級)
jdk1.7版本的主要內容:jdk1.7在執行緒安全方面主要利用到了分段鎖(segment),簡單的說一個CHM是由N(初始化16)個segment組成的,這樣的話就通過在每個segment端上加鎖來控制執行緒安全的,
如下圖:

jdk1.8 針對jdk1.7做了些改進 主要有如下:
1、取消了segement分段鎖這部分
2、由原來的數字+單向鏈表 改為 陣列+單向鏈表(或紅黑樹)
原因: 1、去掉segment的分段鎖,使得鎖的范圍更小了,減少了阻塞的概率,提升鎖的效率,
2、陣列+鏈表,缺點:單向鏈表的時間復雜度為0(n),如果同一個節點hash碰撞過多的話,那么這個節點的單向鏈表的長度就很可能成為整個map查詢的瓶頸了,因此優化了當單向鏈表的長度增加到了8(默認),那么就會由原來的鏈表轉為紅黑樹,紅黑樹的查詢效率比鏈表要高很多0(logn),利用了二分查找等機制,加速了查找速度,
如下圖:

CHM的原理淺析
初始化
// 初始化陣列
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
// 回圈存在多執行緒競爭的情況下
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0) // 以及被其他執行緒搶到了,開始初始化了
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try { // cas原子操作,標記已經在初始化了,與第一個if相對應
if ((tab = table) == null || tab.length == 0) {
// 默認初始值16 ,
// private static final int DEFAULT_CAPACITY = 16;
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)
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
//鍵不能為空,否則報錯
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;
if (tab == null || (n = tab.length) == 0)
// 初始化 陣列
tab = initTable();
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;
synchronized (f) {
if (tabAt(tab, i) == f) {
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;
}
}
}
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;
}
}
}
}
// static final int TREEIFY_THRESHOLD = 8;
if (binCount != 0) {
// 如果節點數,大于初始值默認8),那么轉成紅黑樹
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
============
Class<?> ak = Node[].class;
ABASE = U.arrayBaseOffset(ak);
int scale = U.arrayIndexScale(ak);
if ((scale & (scale - 1)) != 0)
throw new Error("data type scale not a power of two");
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
=============
@SuppressWarnings("unchecked")
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
// 此方法 是通過獲取offset的偏移量 如上代碼,實際等價于tab[i],那么為什么不這么取值?
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
為什么通過tabAt()單獨的去獲取值呢??不知直接用tab[i]更家直接的獲取值呢?
原因: 看代碼上getObjectVolatile 雖然有volatile關鍵字,但是我們都知道,因為對 volatile 寫操作 happen-before 于 volatile 讀操作,
因此其他執行緒對 table 的修改均對 get 讀取可見的,由此可見直接tab[i] 不一定能獲取的最新的值,
雖然 table 陣列本身是增加了 volatile 屬性,但是“volatile 的陣列只針對陣列的參考具有volatile 的語意,而不是它的元素”,所以就直接用記憶體上的偏移量來獲取值,
個數計算
api 方法 - > chmMap.size();
這個計算計算個數由于涉及到多執行緒,那么單純的計算個數是可能不準確的,因此這邊利用的分而治之的演算法方式,來獲取最后的個數
/**
* 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 // check 指的是擴容標記
*/
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 是基礎個數,可以認為是在沒有競爭的情況下,通過baseCount的累加記錄個數的
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))) {
// 計算元素個數 baseCount+x(1.競爭,2.無競爭)
fullAddCount(x, uncontended);
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();
}
}
}
// 計算個數,期間需要考慮擴容等,加鎖等問題
private final void fullAddCount(long x, boolean wasUncontended) {
int h;
// 隨機獲取一個下標,如沒有對應陣列下標內為空,那么不存在競爭
if ((h = ThreadLocalRandom.getProbe()) == 0) {
ThreadLocalRandom.localInit(); // force initialization
h = ThreadLocalRandom.getProbe();
wasUncontended = true;
}
boolean collide = false; // True if last slot nonempty
for (;;) {
CounterCell[] as; CounterCell a; int n; long v;
if ((as = counterCells) != null && (n = as.length) > 0) {
if ((a = as[(n - 1) & h]) == null) { // 若為空
if (cellsBusy == 0) { // Try to attach new Cell 為新的值,當前不再初始化或擴容狀態下,創建新的cell值,設定 x(個數)
CounterCell r = new CounterCell(x); // Optimistic create
if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { // cas 加鎖
boolean created = false;
try { // Recheck under lock // 加鎖防止并發修改對應的值
CounterCell[] rs; int m, j;
if ((rs = counterCells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) {
rs[j] = r; // 將元素的個數 放入對應于的陣列內rs[j]
created = true;
}
} finally {
cellsBusy = 0;
}
if (created)
break;
continue; // Slot is now non-empty
}
}
collide = false;
}
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash ,未沖突
else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
break;
// 如果已經有其他執行緒建立了新的 counterCells 或者 CounterCells 大于 CPU 核心數(執行緒的并發數不會超過 cpu 核心數)
else if (counterCells != as || n >= NCPU)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
try {
if (counterCells == as) {// Expand table unless stale
// // 需要擴容了 n*2 (左移1位)
CounterCell[] rs = new CounterCell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
counterCells = rs;
}
} finally {
cellsBusy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h = ThreadLocalRandom.advanceProbe(h);
}
// 沒有初始化,開始初始化 默認為2的大小
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
if (init)
break;
}
// cas操作成功,baseCount累加
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break; // Fall back on using base
}
}
// 求計算個數的table初始化 默認大小為2,后面也可以擴容
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}

通過上面的這個圖以及結合代碼知道2點: 1、當沒有并發的時候,會有個baseCount 來記錄當前元素的個數的,2、當出現并發時,那么就需要考慮到怎么樣更加高效的計算出個數,那么這里就引入了通過對當前執行緒的Random隨機落到一個陣列的一個節點上,因此組中通過計算整個陣列上的value值來得出最終的count數,如果陣列不夠的情況,也會有設計到擴容的哦,如下代碼:
//計算總的元素個數
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;
}
// 創建cell陣列,存在競爭以及擴容
else if (cellsBusy == 0 && U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
try {
if (counterCells == as) {// Expand table unless stale
CounterCell[] rs = new CounterCell[n << 1];
for (int i = 0; i < n; ++i)
rs[i] = as[i];
counterCells = rs;
}
} finally {
cellsBusy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h = ThreadLocalRandom.advanceProbe(h);
擴容
資料遷移
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/100725.html
標籤:其他
上一篇:Windows系統組件漏洞
下一篇:初識加密技術
