1.
2. jdk8
2.1 重要的属性与内部类
// 当初始化或扩容完成后,下一次扩容的阈值大小
// 默认为0;初始化时,为-1;扩容时,为-(1+扩容线程数)
private transient volatile int sizeCtl;
// 整个concurrentHashmap就是一个 node[] 数组
static class Node<K,V> implements Map.Entry<K,V> { }
// hash表
transient volatile Node<K,V>[] table;
// 扩容时的新hash表
private transient volatile Node<K,V>[] nextTable;
// 扩容时如果整个bin迁移完毕,用ForwardingNode作为旧table bin的头结点(做个标记)
static final class ForwardingNode<K,V> extends Node<K,V> {}
// 用在compute以及conputeIfAbsent时,用来占位,计算完成后替换为普通Node
static final class ReservationNode<K,V> extends Node<K,V> { }
// 作为treebin的头结点,存储root和first(红黑树)
static final class TreeBin<K,V> extends Node<K,V> { }
// 作为treebin的结点,存储parent ,left, right(红黑树)
static final class TreeNode<K,V> extends Node<K,V> { }
// 获取node[]中第i个node
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) { }
// cas修改node[]中第i个node的值,c为旧值,v为新值
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) { }
// 直接修改node[]中第i个node的值,v为新值
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) { }
2.2 构造方法
懒惰初始化,构造房中仅仅计算了table的大小,以后在第一次使用时才会真正创建
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);
// 2的幂次方
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
2.3 get方法
- 计算hash值,定位到该table索引位置,如果是首节点符合就返回
- 如果遇到扩容的时候,会调用标志正在扩容节点ForwardingNode的find方法,查找该节点,匹配就返回
- 以上都不符合的话,就往下遍历节点,匹配就返回,否则最后就返回null
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
// spread方法保证返回结果是正数
int h = spread(key.hashCode());
// table 不为空 && 长度>0 && 当前数组位置有元素
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
// 如果头结点e的hash是已经要找的key,就判断内容是否相等
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
// 如果e的hash为负数表示改bin在扩容中(扩容的ForwardingNode就是-1)在新table中找,
// 或者是treebin(-2),这时调用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;
}
2.4 put方法
public V put(K key, V value) {
return putVal(key, value, false);
}
// onlyIfAbsent值表示遇到相同的key是否用新值代替旧值(false就是代替,true就是不代替)
final V putVal(K key, V value, boolean onlyIfAbsent) {
// 不允许有null的键值对
if (key == null || value == null) throw new NullPointerException();
// 保证key的hashcode为正数
int hash = spread(key.hashCode());
int binCount = 0;
// 死循环
for (Node<K,V>[] tab = table;;) {
// f是链表头结点,fh是链表头结点的hash,i是链表在table中的下标
Node<K,V> f; int n, i, fh;
// table为null,创建table
if (tab == null || (n = tab.length) == 0)
// 初始化table使用cas,无需synchronized,创建成功,进入下一轮循环
tab = initTable();
// 否则,查看该位置index是否是null的,如果是创建链表头结点
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 添加链表头使用cas,无需synchronized
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
// 成功就break,失败就继续循环
break; // no lock when adding to empty bin
}
// 头结点不为null
// 帮忙扩容,看这个节点是不是forwardNode,如果是,就知道别的线程正在扩容
else if ((fh = f.hash) == MOVED)
// 帮忙扩容,进行下一轮循环
tab = helpTransfer(tab, f);
else {
// 正式扩容
V oldVal = null;
// 锁住链表头结点
synchronized (f) {
// 再次确认链表头节点没有被移动
if (tabAt(tab, i) == f) {
// 链表
if (fh >= 0) {
// 链表长度,初始值为1
binCount = 1;
// 遍历链表
for (Node<K,V> e = f;; ++binCount) {
K ek;
// 找到相同的key
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
// 更新并break
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
// 最后一个节点,新增node,追加至链表尾部
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;
// putTreeVal会看key是否已经在树中,是的话返回对应的treeNode
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
// 释放头结点的锁
}
// 树化
if (binCount != 0) {
// 如果链表长度 >= 树化阈值(8),链表转换成红黑树(总数组长度>=64才转换,不然就扩容)
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
// 增加size计数,多个累加单元进行计数。
addCount(1L, binCount);
return null;
}
initTable方法
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
// 没有被创建
while ((tab = table) == null || tab.length == 0) {
// 让其他线程yield,节约资源
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
// 尝试将 sizeCtl设置为-1,表示初始化
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
// 获得锁,创建table,这是其他线程cas失败会在while中yield直至table创建
try {
// 确认没有创建
if ((tab = table) == null || tab.length == 0) {
// sc是初始容量,没有给就用默认值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);
}
} finally {
// 恢复成正数,使其他忙等待的线程进入compareAndSwapInt比较,此时sc的值改变了,就退出来了
sizeCtl = sc;
}
break;
}
}
return tab;
}
addCount方法
// check 是之前binCount的个数
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
// 累加单元数组不为null,已经有了,向cell累加
if ((as = counterCells) != null ||
// 还没有,向baseCount累加
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
// 累加失败了
CounterCell a; long v; int m;
boolean uncontended = true;
// 还没有counterCells
if (as == null || (m = as.length - 1) < 0 ||
// 还没有cell
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
// cell cas增加计数失败
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
// 创建累加单元数组和cell,累加重试
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);
// sc改成-1,扩容标识
if (sc < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
// newtable已经创建了,帮忙扩容
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
// 需要扩容,这时newtable未创建(懒惰初始化)
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
2.5 size计算流程
size计算实际发生在put、remove改变集合元素的操作之中
- 没有竞争发生时,向baseCount累加计数
- 有竞争发生,新建counterCells,向其中一个cell累加计数
- counterCells初始有两个cell
- 如果计数竞争比较激烈,会创建新的cell来累加计数
- 注意:size计数结果有一定误差,多线程条件下,容易出现误差。
```java
public int size() {
}long n = sumCount();
return ((n < 0L) ? 0 :
(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
(int)n);
final long sumCount() { CounterCell[] as = counterCells; CounterCell a; long sum = baseCount; // 将baseCount与所有cell计数累加 if (as != null) { for (int i = 0; i < as.length; ++i) { if ((a = as[i]) != null) sum += a.value; } } return sum; }
<a name="H4xsb"></a>
## 2.6 transfer扩容
```java
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
// 初始化新table
if (nextTab == null) { // initiating
try {
@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;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
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)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
// 链表头是null,说明处理完了,就把他替换成ForwardingNode
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
// 如果已经是ForwardingNode,就处理下一个链表
else if ((fh = f.hash) == MOVED))
advance = true; // already processed
else {
// 链表头有元素,锁住链表
synchronized (f) {
//
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
// 普通节点,转移节点类似hashmap里的,高位低位链表转移
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;
}
}
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;
}
// 红黑树,类似hashmap里面的红黑树转移,隐藏的双向链表,高低位链表转移
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);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}