HashMap內(nèi)部實(shí)現(xiàn)
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
HashMap中,put方法分析HashMap如果工作的茂蚓。
- 其中有兩種結(jié)構(gòu)體胸懈,
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
鏈表中有兩種節(jié)點(diǎn):普通的節(jié)點(diǎn)Node,紅黑樹(shù)的頭節(jié)點(diǎn)TreeNode
put過(guò)程:
如果Map沒(méi)有初始化雏赦,則resize()
如果hash值計(jì)算的位置為空劫笙,則new 一個(gè)新的Node插入到尾端
-
(發(fā)生了hash沖突,準(zhǔn)備解決沖突)
-
如果是key值重復(fù)星岗,則進(jìn)行替換
- 如果沖突節(jié)點(diǎn)已經(jīng)是TreeNode填大,按紅黑樹(shù)的方式進(jìn)行節(jié)點(diǎn)插入(也可能Key重復(fù),但是這里不管了)
- (沖突的是一個(gè)普通Node)
- 使用順序的再散列俏橘,向后查找到為空的位置進(jìn)行插入
- 向后散列的時(shí)候檢查key是否已經(jīng)重復(fù)
- 再散列的時(shí)候進(jìn)行計(jì)數(shù)允华,最后插入時(shí)如果計(jì)數(shù)器大于8(再散列了7次,hash沖突為8)寥掐,將表進(jìn)行紅黑樹(shù)的轉(zhuǎn)換靴寂。
-
ConcurrentHashMap 實(shí)現(xiàn)解析
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
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;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
實(shí)現(xiàn)了并發(fā)的線程安全,所以每一步都考慮有多個(gè)線程同時(shí)操作的情況
實(shí)現(xiàn)邏輯
要點(diǎn):
- 代碼主體是一個(gè)不退出的循環(huán)(確保節(jié)點(diǎn)能最終有位置插入)
如果Map還沒(méi)有初始化召耘,初始化(如果多個(gè)線程同時(shí)進(jìn)入這個(gè)條件:初始化操作是CAS保證線程安全)
initTable()
-
如果Hash得到的地址值為空百炬,CAS進(jìn)行嘗試插入,成功就退出循環(huán)污它,失敗就進(jìn)行下一次循環(huán)(顯然下一次就不為空了)
casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))
-
如果要插入的節(jié)點(diǎn)在進(jìn)行遷移(鏈表向紅黑樹(shù)轉(zhuǎn)換剖踊?),則幫助進(jìn)行遷移(CAS保證安全)
tab = helpTransfer(tab, f);
-
(以上情況都不是衫贬,表示發(fā)生了Hash沖突)
1. (以下方法在同步塊中```synchronized (f)```),且是以**操作的節(jié)點(diǎn)**進(jìn)行加鎖德澈。 2. 如果是普通Node - key值重復(fù)進(jìn)行覆蓋 - 順序再散列解決沖突,找到為空的位置插入 - 和HashMap一樣固惯,記錄沖突個(gè)數(shù)(用于判斷是否轉(zhuǎn)為紅黑樹(shù)) 3. 如果是TreeBin(和HasHMap中TreeNode一個(gè)概念) - 則按照紅黑樹(shù)的方式插入
-
最后判斷沖突個(gè)數(shù)梆造,如需要進(jìn)行紅黑樹(shù)的轉(zhuǎn)換
treeifyBin(tab, i)
- 如果表中節(jié)點(diǎn)數(shù)量過(guò)少,則執(zhí)行擴(kuò)容
- 否則轉(zhuǎn)為紅黑樹(shù)缝呕,(使用了syn同步)