0. ConcurrentHashMap是什么
- key和value都不能為
null,和HashTable一樣 - 默認(rèn)大小為16,擴(kuò)容時(shí)為2的冪,擴(kuò)容閾值為
0.75*cap - 節(jié)點(diǎn)相同的標(biāo)準(zhǔn)為
hash相等并且k1==k2 || k1.equals(k2)
1. 實(shí)現(xiàn)的本質(zhì)
- 數(shù)組+鏈表+紅黑樹
- volatile + CAS
2. 常用api解析
2.0 重要子類解析
Node節(jié)點(diǎn),數(shù)組的元素類型
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
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;
}
}
TreeBin:放在tab[i]位置的節(jié)點(diǎn),當(dāng)該節(jié)點(diǎn)的內(nèi)容是紅黑樹時(shí)使用,其中:
- root:紅黑樹的根節(jié)點(diǎn)
- first:鏈表的頭節(jié)點(diǎn)
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;
// values for 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
...
}
//紅黑樹的節(jié)點(diǎn)
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;
}
}
Forwarding節(jié)點(diǎn),擴(kuò)容時(shí)把舊表的tab[i]位置移動(dòng)到新表后,在舊表的i位置插入該節(jié)點(diǎn)。
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;
}
}
2.1 構(gòu)造函數(shù)
public ConcurrentHashMap()
public ConcurrentHashMap(int initialCapacity)
public ConcurrentHashMap(Map<? extends K, ? extends V> m)
public ConcurrentHashMap(int initialCapacity, float loadFactor)
public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)
2.2 initTable初始化
初始化只能由一個(gè)線程進(jìn)行,搶占到的線程將sizeCtl設(shè)為-1,未搶占到的線程進(jìn)行yield()操作。初始化完成之后sizeCtl的值為0.75*n。
/**
* 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) {
//sc小于0表示未搶占到,自旋
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
//搶占到的線程把sizeCtl置為-1,防止其他線程進(jìn)入
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
//默認(rèn)大小為16
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
//寫入table
table = tab = nt;
//寫入sc=0.75*n
sc = n - (n >>> 2);
}
} finally {
//table初始化完成后,寫入正確的sizeCtl
sizeCtl = sc;
}
break;
}
}
return tab;
}
2.3 數(shù)組元素原子操作
arrayBaseOffset獲取數(shù)組中第一個(gè)元素的偏移地址。即數(shù)組對(duì)象頭的偏移距離。
arrayIndexScale獲取數(shù)組中每一個(gè)元素的大小。
若2^n = scale,則ASHIFT = n。
i<<ASHIFT = i * 2^ASHIFT = i * scale
所以((long)i << ASHIFT) + ABASE=i * scale + ABASE即為內(nèi)存中元素的真實(shí)位置。
使用getObjectVolatile putObjectVolatile是為了保證讀寫原子性,同時(shí)直接讀寫到內(nèi)存而不是線程緩存。
...
private static final long ABASE;
private static final int ASHIFT;
...
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");
// 2^ASHIFT = scale
ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
@SuppressWarnings("unchecked")
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
//參數(shù)分別為 table數(shù)組、index、expect、update
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
2.4 put方法
/**
* Maps the specified key to the specified value in this table.
* Neither the key nor the value can be null.
*
* <p>The value can be retrieved by calling the {@code get} method
* with a key that is equal to the original key.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}
* @throws NullPointerException if the specified key or value is null
*/
public V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
//key和value都不能為null
if (key == null || value == null) throw new NullPointerException();
//將key的hash無符號(hào)右移16位,然后與其本身異或,再將符號(hào)位置0
int hash = spread(key.hashCode());
int binCount = 0;
//原子操作失敗時(shí)自旋使用
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
//如果表是空的,初始化
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//如果tab[i]是空,使用原子操作更新,不加鎖
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
//操作成功,退出循環(huán),停止自旋
break; // no lock when adding to empty bin
}
//如果當(dāng)前節(jié)點(diǎn)是一個(gè)fwd節(jié)點(diǎn),則本線程幫助完成擴(kuò)容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
//鎖住tab[i]位置的第一個(gè)元素,相當(dāng)于鎖住tab[i]整個(gè)位置
synchronized (f) {
//檢查tab[i]位置元素有無變化
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
//如果節(jié)點(diǎn)已經(jīng)存儲(chǔ)過(key和hash分別相等)
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
//如果onlyIfAbsent為false,更新
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
//tab[i]位置的鏈表上沒有元素,則插入到鏈表最后
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
//如果f是紅黑樹的根節(jié)點(diǎn)
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) {
//如果鏈表上的節(jié)點(diǎn)大于等于8個(gè),轉(zhuǎn)成紅黑樹
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
//將key的hash無符號(hào)右移16位,然后與其本身異或,再將符號(hào)位置0
//目的是為了減少hash沖突,使分布更均勻
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
helpTransfer方法,如果正在擴(kuò)容,則幫助進(jìn)行擴(kuò)容:
/**
* 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;
//多一個(gè)線程幫助擴(kuò)容時(shí),sc+1
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}
紅黑樹節(jié)點(diǎn)的put方法:
/**
* Finds or adds a node.
* @return null if added
*/
//紅黑樹中添加節(jié)點(diǎn),如果是添加加點(diǎn)返回null,如果是更新節(jié)點(diǎn)返回舊節(jié)點(diǎn)
final TreeNode<K,V> putTreeVal(int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
//如果根節(jié)點(diǎn)是空,新建根節(jié)點(diǎn)
if (p == null) {
first = root = new TreeNode<K,V>(h, k, v, null, null);
break;
}
//先比較hash
else if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
//hash相等時(shí)比較key
else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
return p;
//hash相等,但是key不等
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
//如果key沒實(shí)現(xiàn)Comparable<K>接口,或者compareTo()方法返回0
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.findTreeNode(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.findTreeNode(h, k, kc)) != null))
return q;
}
//決勝局,使用系統(tǒng)的hash值比較,若還有相等,dir=-1
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
//在樹中找到插入的位置,鏈表中放到鏈表頭部
TreeNode<K,V> x, f = first;
first = x = new TreeNode<K,V>(h, k, v, f, xp);
if (f != null)
f.prev = x;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//如果父節(jié)點(diǎn)是黑色,x設(shè)為紅色
if (!xp.red)
x.red = true;
//如果父節(jié)點(diǎn)是紅色,進(jìn)行調(diào)整
else {
lockRoot();
try {
//按照紅黑樹的規(guī)則進(jìn)行調(diào)整
root = balanceInsertion(root, x);
} finally {
unlockRoot();
}
}
break;
}
}
assert checkInvariants(root);
return null;
}
檢查key是否實(shí)現(xiàn)了Comparable<Key>接口:
/**
* Returns x's Class if it is of the form "class C implements
* Comparable<C>", else null.
*/
static Class<?> comparableClassFor(Object x) {
if (x instanceof Comparable) {
Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
//如果是string,直接返回
if ((c = x.getClass()) == String.class) // bypass checks
return c;
//獲取c實(shí)現(xiàn)的全部接口
if ((ts = c.getGenericInterfaces()) != null) {
for (int i = 0; i < ts.length; ++i) {
//如果是參數(shù)化類型,并且原始類型是Comparable,參數(shù)只有一個(gè),且為c
if (((t = ts[i]) instanceof ParameterizedType) &&
((p = (ParameterizedType)t).getRawType() ==
Comparable.class) &&
(as = p.getActualTypeArguments()) != null &&
as.length == 1 && as[0] == c) // type arg is c
return c;
}
}
}
return null;
}
以指定的節(jié)點(diǎn)為根,在樹種查找key節(jié)點(diǎn),未找到返回null:
/**
* Returns the TreeNode (or null if not found) for the given key
* starting at given root.
*/
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;
//如果key實(shí)現(xiàn)了Comparable<K>接口,并且compareTo()方法返回值不為0
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;
}
進(jìn)行紅黑樹平衡調(diào)整時(shí),先鎖住樹根:
/**
* Acquires write lock for tree restructuring.
*/
private final void lockRoot() {
if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER))
contendedLock(); // offload to separate method
}
/**
* Releases write lock for tree restructuring.
*/
private final void unlockRoot() {
lockState = 0;
}
/**
* Possibly blocks awaiting root lock.
*/
private final void contendedLock() {
boolean waiting = false;
for (int s;;) {
//lockState為0或WAITER時(shí),搶占
if (((s = lockState) & ~WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
if (waiting)
waiter = null;
return;
}
}
//如果WAITER位為0,將WAITER位置1
else if ((s & WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
waiting = true;
waiter = Thread.currentThread();
}
}
else if (waiting)
LockSupport.park(this);
}
}
2.5 get方法
/**
* 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;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
//如果tab[i]就是要查找的節(jié)點(diǎn)
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
//如果是特殊節(jié)點(diǎn),用find方法
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;
}
Node節(jié)點(diǎn)調(diào)用find方法有3種情況:
- MOVED:
ForwardingNode - TREEBIN:
TreeBin - RESERVED:
ReservationNode
都繼承了Node類,在子類中分別重寫了find方法
2.6 remove方法
/**
* Removes the key (and its corresponding value) from this map.
* This method does nothing if the key is not in the map.
*
* @param key the key that needs to be removed
* @return the previous value associated with {@code key}, or
* {@code null} if there was no mapping for {@code key}
* @throws NullPointerException if the specified key is null
*/
public V remove(Object key) {
return replaceNode(key, null, null);
}
/**
* Implementation for the four public remove/replace methods:
* Replaces node value with v, conditional upon match of cv if
* non-null. If resulting value is null, delete.
*/
final V replaceNode(Object key, V value, Object cv) {
int hash = spread(key.hashCode());
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
//如果tab是空,或者tab[i]位置為空,結(jié)束
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null)
break;
//如果tab[i]位置是fwd節(jié)點(diǎn),參與擴(kuò)容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
boolean validated = false;
//鎖住tab[i]位置
synchronized (f) {
if (tabAt(tab, i) == f) {
//普通節(jié)點(diǎn)
if (fh >= 0) {
validated = true;
for (Node<K,V> e = f, pred = null;;) {
K ek;
//鏈表循環(huán)往后查找,如果找到
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
V ev = e.val;
if (cv == null || cv == ev ||
(ev != null && cv.equals(ev))) {
oldVal = ev;
//如果新值不為空,替換
if (value != null)
e.val = value;
//如果不是tab[i]位置的第一個(gè)節(jié)點(diǎn),刪除節(jié)點(diǎn)
else if (pred != null)
pred.next = e.next;
//如果是tab[i]位置的第一個(gè)節(jié)點(diǎn),原子替換
else
setTabAt(tab, i, e.next);
}
break;
}
//往鏈表后查找
pred = e;
if ((e = e.next) == null)
break;
}
}
//如果是紅黑樹
else if (f instanceof TreeBin) {
validated = true;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
//如果找到節(jié)點(diǎn)
if ((r = t.root) != null &&
(p = r.findTreeNode(hash, key, null)) != null) {
V pv = p.val;
if (cv == null || cv == pv ||
(pv != null && cv.equals(pv))) {
oldVal = pv;
//如果新值不為空,替換
if (value != null)
p.val = value;
//否則刪除節(jié)點(diǎn)
else if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
}
if (validated) {
if (oldVal != null) {
if (value == null)
addCount(-1L, -1);
return oldVal;
}
break;
}
}
}
return null;
}
2.7 擴(kuò)容方法
如果tab[i]位置的節(jié)點(diǎn)超過8個(gè),轉(zhuǎn)換成紅黑樹
/**
* Replaces all linked nodes in bin at given index unless table is
* too small, in which case resizes instead.
*/
private final void treeifyBin(Node<K,V>[] tab, int index) {
Node<K,V> b; int n, sc;
if (tab != null) {
//如果長度小于64,擴(kuò)容
if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
tryPresize(n << 1);
else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {
synchronized (b) {
if (tabAt(tab, index) == b) {
TreeNode<K,V> hd = null, tl = null;
//轉(zhuǎn)為雙向鏈表
for (Node<K,V> e = b; e != null; e = e.next) {
TreeNode<K,V> p =
new TreeNode<K,V>(e.hash, e.key, e.val,
null, null);
if ((p.prev = tl) == null)
hd = p;
else
tl.next = p;
tl = p;
}
//把紅黑樹放到tab[i]位置
setTabAt(tab, index, new TreeBin<K,V>(hd));
}
}
}
}
}
擴(kuò)大table的長度:
/**
* Tries to presize table to accommodate the given number of elements.
*
* @param size number of elements (doesn't need to be perfectly accurate)
*/
private final void tryPresize(int size) {
int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(size + (size >>> 1) + 1);
int sc;
while ((sc = sizeCtl) >= 0) {
Node<K,V>[] tab = table; int n;
//未初始化,進(jìn)行初始化
if (tab == null || (n = tab.length) == 0) {
n = (sc > c) ? sc : c;
if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if (table == tab) {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
}
}
else if (c <= sc || n >= MAXIMUM_CAPACITY)
break;
else if (tab == table) {
int rs = resizeStamp(n);
if (sc < 0) {
Node<K,V>[] nt;
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
//多一個(gè)線程進(jìn)行擴(kuò)容操作,sc+1
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
//實(shí)際進(jìn)行擴(kuò)容的路徑
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
}
}
}
把雙向鏈表轉(zhuǎn)為紅黑樹:
/**
* Creates bin with initial set of nodes headed by b.
*/
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;
//確定節(jié)點(diǎn)x的插入方向
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;
//插入節(jié)點(diǎn)x
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//調(diào)整紅黑樹
r = balanceInsertion(r, x);
break;
}
}
}
}
this.root = r;
assert checkInvariants(root);
}
并行擴(kuò)容transfer方法:
- 每個(gè)線程每次處理
stride個(gè)元素。 - 索引
i到bound時(shí),本線程本次處理完成,i到0時(shí),整體數(shù)組處理完成,更新table和sizeCtl的值。 - 多一個(gè)線程進(jìn)行擴(kuò)容操作時(shí),
sc+1,完成后每個(gè)線程sc-1
/**
* 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最小為16
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { // initiating
try {
//新表擴(kuò)容的大小為2*n
@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;
while (advance) {
int nextIndex, nextBound;
//判斷是否到本線程處理的邊界
if (--i >= bound || finishing)
advance = false;
//判斷是否到table的邊界
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
//讀取本線程本次需要處理的部分,即i到bound部分
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
//i<0說明table數(shù)組整體處理完了
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
//結(jié)束處理,賦值table和sizeCtl
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
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
}
}
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {
//鎖住tab[i]位置的節(jié)點(diǎn)f
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
//如果是鏈表節(jié)點(diǎn)
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;
}
}
//循環(huán)完成后lastRun后面的節(jié)點(diǎn)與lastRun在新table中在一個(gè)格子
//感覺這一趟循環(huán)沒有什么意義???反正后面還要循環(huán)一趟
if (runBit == 0) {
ln = lastRun;
hn = null;
}
else {
hn = lastRun;
ln = null;
}
//重新遍歷tab[i]位置的鏈表,第n位為0的放到ln頭部,為1的放到hn頭部
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);
}
//把ln和hn分別放到新表的i和i+n位置
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
//舊表的i位置標(biāo)為MOVED
setTabAt(tab, i, fwd);
advance = true;
}
//如果是紅黑樹節(jié)點(diǎn)
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;
//紅黑樹的所有節(jié)點(diǎn)同時(shí)也在一個(gè)雙向鏈表上
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);
//第n位為0時(shí)放在lo后
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
//第n位為1時(shí)放在hi后
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
//新的鏈表如果少于6個(gè),轉(zhuǎn)為單鏈表,否則轉(zhuǎn)為紅黑樹,如果另外一個(gè)鏈?zhǔn)强盏?,直接把原來的t放過去
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;
//把ln和hn分別放入新表的i和i+n位置
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
//舊表的i位置設(shè)為MOVED
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}
3. 總結(jié)
- 默認(rèn)大小16,每次擴(kuò)容時(shí)為原來的2倍,擴(kuò)容閾值為
0.75*n - 指定初始化大小時(shí),容量為大于指定數(shù)的最小的2的冪,由
tableSizeFor()方法實(shí)現(xiàn) -
table長度大于64,并且單個(gè)位置的節(jié)點(diǎn)數(shù)大于8個(gè),會(huì)將該位置轉(zhuǎn)為紅黑樹,否則只是擴(kuò)大table的長度 - 在進(jìn)行寫操作時(shí),每次只鎖
tab[i]位置,不是整表上鎖 -
sizeCtl比較難理解- 為
-1是表示在初始化,初始化只能由一個(gè)線程進(jìn)行,其他線程yield()操作,在initTable()方法中 - 為
0x80xx00xx時(shí)(即resizeStamp(n)<<RESIZE_STAMP_SHIFT+2),表示在擴(kuò)容操作,在tryPresize()方法中 - 為
0x80xx00xx時(shí)(上種情況下+n),表示并發(fā)擴(kuò)容操作,每多一個(gè)線程,進(jìn)行sizeCtl+1操作,在putVal()remove()方法中,節(jié)點(diǎn)為REMOVED情況下,完成擴(kuò)容操作后,每退出一個(gè)線程,進(jìn)行sizeCtl-1操作,直到(sc - 2) == resizeStamp(n) << RESIZE_STAMP_SHIFT,表示最后一個(gè)線程完成,在transfer()方法中
- 為
4. 參考
- ConcurrentHashMap源碼build 1.8.0_121-b13版本
- Java7/8 中的 HashMap 和 ConcurrentHashMap 全解析
- ConcurrentHashMap總結(jié)
- 二叉樹 - 紅黑樹