ConcurrentHashMap
Base
- Node Definition:val and next are volatile.
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;
....}
- sizeCtl
Table initialization and resizing control. When negative, the
table is being initialized or resized: -1 for initialization,
else -(1 + the number of active resizing threads). Otherwise,
when table is null, holds the initial table size to use upon
creation, or 0 for default. After initialization, holds the
next element count value upon which to resize the table. - concurrentLevel
as estimated threads,also the number of bins. - table:volatile
the array of bins. Lazily initialized upon first insertion.
Size is always a power of two. Accessed directly by iterators. - nextTable
The next table to use; non-null only while resizing. - transferIndex
The next table index (plus one) to split while resizing.init to n while resizing.
Spread method
static final int spread(int h){
return h^(h >>>16) &0x7fffffff;// the high 16 bits XOR the low 16 bits.
}
Thread.yield()
the current Thread is willing to yield its current use of a processor, but the scheduler is free to ignore the hint.
putVal()
key points.
- null key or null value is not accessible.
- method of compute hash(spread)
- if table is empty,initialize tab(lazy init).No global lock,use
CAS and sizeCtl(volatile) to ensure single thread do initTable. - if tab[i] == null,try CAS put.
- if tab[i].hash == -1,help resize.
- else ,synchronized(tab[i]). if(tab[i].hash >= 0), add to the end of the list and record binCount.else (tab[i].hash == 0), put to a red_black tree.then, if(binCount >= 8),treeifyBin(may be do not treeify, resize can be possible.)
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();//is different from HashMap
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();//when in init, no lock. here use volatile parameter:"sizeCtl" and CAS and spin to ensure init.
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {//when this bin is null,use CAS Operation to do put.
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin,just CAS.
}
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;
}
initTable()
- lazy init.
- sizeCtl to -1 when initializing.
- only one thread do this.
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {//note,use while here.
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {//CAS Operation, use sizeCtl param.
try {
if ((tab = table) == null || tab.length == 0) {//it`s also means.
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);//why ?
}
} finally {
sizeCtl = sc;//when to resize.
}
break;
}
}
return tab;
}
transfer
resize table
key points.
- nextTable.length = tab.length <<1;(double)
- transferIndex is volatile(shared in multi threads.),to allow more than one threads handle tab bins.
- ForwardingNode (hash = -1) in tab[i] means the tab is resizing and the ith bin has already been processed.
- the Nodes in tab[i] will store to nextTab[i] (node.hash & n == 0),otherwise nextTable[i + n].
-for ith bin process: CAS when bin is empty, ignore when bin`s first node is an instance of ForwardingNode(hash == -1),otherwise,synchronized(first node the bin). - question.when finished, why sizeCtl - 1 ?
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
if (nextTab == null) { // initiating
try {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];//double size.
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;
/** find the next bin to handle, if exist.**/
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {//this #{stride} bins will be handled by this thread,while others may be handled by other threads.
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
/** i reprsents the bin index, so it should be between 0 and n - 1. **/
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
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)//why ?
return;
finishing = advance = true;
i = n; // recheck before commit,why?
}
}
else if ((f = tabAt(tab, i)) == null)// CAS operation
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
if (fh >= 0) {
int runBit = fh & n;//must be 0 or 1. because n is power of 2.
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;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
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;
}
}
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);//one bin in old table depart to two bin in new table.
setTabAt(tab, i, fwd); //marked as processed.
advance = true;
}
}
}
}
}
}
get()
- use tab(volatile) and tabAt(i) and node.next(volatile) and node.val (volatile) to get element(up-to-date).
- volatile :write happens before read.
- when resizing, read from the new table(hash & (nextTab.length - 1))
- when a tree, read from the tree.
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
//tab = table (volatile:write happens before read)
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))//for no collision situation
return e.val;
}
else if (eh < 0) // find in the nextTable(-1) or Tree(-2)
return (p = e.find(h, key)) != null ? p.val : null;
//at last,find in the list
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
tabAt()
- tabAt: use Unsafe.getObjectVolatile to get tab[i](up-to-date)
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);
}
网友评论