ConcurrentHashMap
JDK 1.7
JDK 1.7 是一个Segment数组
总览:
- Segment内部有一个HashEntry[] table 的字段
- Segment数组大小默认是16
- Segment由DEFAULT_CONCURRENT_LEVEL决定,去找比DEFAULT_CONCURRENT_LEVEL大的2次幂
- HashEntry由DEFAULT_CONCURRENT_LEVEL和initialCapacity决定。通过两者相除后再向上取整
- 每个Segment对象内部还会维护一个HashEntry数组
有一个UNSAFE底层函数需要了解:
UNSAFE.getObjectVolatile(segments, u);
/*
表示获取segments数组第u位的对象。与一般意义不同的是,这个是直接从内存中获取,并且是一个原子操作
*/
Segment对象的创建:
private Segment<K,V> ensureSegment(int k) {
final Segment<K,V>[] ss = this.segments;
long u = (k << SSHIFT) + SBASE; // raw offset
Segment<K,V> seg;
//第一次检测
if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u)) == null) {
// 获取ss[0]位置的Segment对象,一遍获取其字段值,避免反复计算
Segment<K,V> proto = ss[0]; // use segment 0 as prototype
int cap = proto.table.length;
float lf = proto.loadFactor;
int threshold = (int)(cap * lf);
HashEntry<K,V>[] tab = (HashEntry<K,V>[])new HashEntry[cap];
// 第二次检测
// 获取ss数组当前第u个位置的对象 -- getObjectVolatile
if ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
== null) { // recheck
Segment<K,V> s = new Segment<K,V>(lf, threshold, tab);
// 自旋筛选
// 如果不为null,退出循环
while ((seg = (Segment<K,V>)UNSAFE.getObjectVolatile(ss, u))
== null) {
// 满足CAS,则赋值。
// 同时赋值数组位置和当前的seg变量
if (UNSAFE.compareAndSwapObject(ss, u, null, seg = s))
break;
}
}
}
return seg;
}
数据的put操作:
final V put(K key, int hash, V value, boolean onlyIfAbsent) {
//tryLock -- 能获取,那么就返回true,否则返回false
// 可以获得锁,那么在这个方法中生成键值对
HashEntry<K,V> node = tryLock() ? null :
// 将会根据hash和key-value生成对应的键值对
scanAndLockForPut(key, hash, value);
V oldValue;
try {
HashEntry<K,V>[] tab = table;
// 获取插入的位置
int index = (tab.length - 1) & hash;
// 获取当前结点的链表
HashEntry<K,V> first = entryAt(tab, index);
for (HashEntry<K,V> e = first;;) {
if (e != null) {
K k;
// 找到结点,那么更新值
if ((k = e.key) == key ||
(e.hash == hash && key.equals(k))) {
oldValue = e.value;
if (!onlyIfAbsent) {
e.value = value;
++modCount;
}
break;
}
// 结点遍历
e = e.next;
}
else {
// 如果已经通过scanAndLockForPut(key, hash, value)构造了结点
if (node != null)
// 采用头插法插入结点
node.setNext(first);
else
node = new HashEntry<K,V>(hash, key, value, first);
int c = count + 1;
// 超过了threshold,重新计算哈希 -- 与HashMap类似
if (c > threshold && tab.length < MAXIMUM_CAPACITY)
rehash(node);
else
// 否则直接放置
setEntryAt(tab, index, node);
++modCount;
count = c;
oldValue = null;
break;
}
}
} finally {
// 解锁
unlock();
}
return oldValue;
}
尝试获取锁的代码
- 因为while(!tryLock())内部会消耗CPU计算资源,所以需要有retries限制重试的次数
private HashEntry<K,V> scanAndLockForPut(K key, int hash, V value) {
// entryForHash -- 根据给定的hash和Segment对象获取键值对
HashEntry<K,V> first = entryForHash(this, hash);
HashEntry<K,V> e = first;
HashEntry<K,V> node = null;
// 重试的次数
int retries = -1; // negative while locating node
// 不断的去尝试获取锁
while (!tryLock()) {
HashEntry<K,V> f; // to recheck first below
// 没有得到锁的过程中将会不断的遍历链表
if (retries < 0) {
if (e == null) {
if (node == null) // speculatively create node
// 遍历到了尾结点,先生成键值对,但是暂时不插入链表,等待锁
node = new HashEntry<K,V>(hash, key, value, null);
retries = 0;
}
// 链表中发现KEY相同的节点
else if (key.equals(e.key))
// 作用是跳出 retries < 0 的这部分的循环
retries = 0;
else
// 链表遍历
e = e.next;
}
// 超过最大重试次数,加锁
else if (++retries > MAX_SCAN_RETRIES) {
lock();
break;
}
else if ((retries & 1) == 0 &&
// 检查键值对是否发生了改变
(f = entryForHash(this, hash)) != first) {
e = first = f; // re-traverse if entry changed
// 如果改变那么就重新进行链表的遍历
retries = -1;
}
}
// 返回需要插入的节点
return node;
}
JDK 1.8
采用与HashMap相同的结构。即数组+链表+红黑树。
put方法:
图示:
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;
// 还没有创建table,执行table的初始化
if (tab == null || (n = tab.length) == 0)
tab = initTable();
// 如果想要插入的位置上没有值
// 如果其他线程添加了值,这里就不会为null跳出这个分支
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 执行CAS的插入操作 -- 不加锁
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
// 跳出循环
break; // no lock when adding to empty bin
}
// 当前Map正在执行扩容
else if ((fh = f.hash) == MOVED)
// 这个线程会帮助Map执行扩容
tab = helpTransfer(tab, f);
else {
V oldVal = null;
// 对发生Hash冲突的节点执行加锁操作
// 在这个结点执行链表或者红黑树的插入 -- 而不影响桶的其他结点
synchronized (f) {
// 加锁后的重检
// 判断头结点是否是在加锁过程中发生了变化
if (tabAt(tab, i) == f) {
// 哈希值> 0代表是链表结点
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;
}
桶初始化:
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
// sizeCtl 默认值为0
if ((sc = sizeCtl) < 0)
// 让出CPU时间片,防止while循环执行造成性能浪费
// 当前线程执行完成后其他线程得到唤醒 --- while循环条件中tab不再为null,退出循环
Thread.yield(); // lost initialization race; just spin
// 只有一个线程可以执行sc的减一操作
// 即只有一个线程可以执行初始化操作
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
// 0.75 * n
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
Map计数与扩容判断函数:
目的:当多个线程竞争去修改总数的时候,将多个线程去竞争baseCount改为少数几个线程竞争CounterCell(Fork Join)
// 遍历整个CounterCell。记录其他线程的加一次数,算得总数
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;
}
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)) {
CounterCell a; long v; int m;
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
// 随机值取Hash,取得当前线程对应的CounterCell
// ThreadLocalRandom.getProbe() -- 每个线程生成的随机数
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
// CAS比较的是当前CounterCell中的值如果成功那么执行了+x,并且不执行下面的fullAddCount
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
// 汇总所有线程的添加操作
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) {
// wasUncontended就是false
int h; // 重新生成线程的hash值
// ThreadLocalRandom.getProbe() -- 每个线程有一个固定的随机值,不会发生改变
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
CounterCell r = new CounterCell(x); // Optimistic create
// 再检验
if (cellsBusy == 0 &&
// CAS加锁
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
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;
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
// 再次尝试CAS加一
else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
break;
// 扩容条件:1.数组变化 2.数组长度不小于CPU核心数
else if (counterCells != as || n >= NCPU)
collide = false; // At max size or stale
else if (!collide)
collide = true;
// 发生碰撞,执行扩容
// 一个线程老是加不上,就会去扩容,让其他线程可以执行CounterCell的+1
else if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
try {
if (counterCells == as) {// Expand table unless stale
// 执行CounterCell数组的扩容
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);
}
// 如果counterCells不为空
// cellsBusy == 0 表示没有其他线程在占用
else if (cellsBusy == 0 && counterCells == as &&
// 通过CAS改变cellsBusy的状态,表示线程进行了占用
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
// 再检验
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
// 在数组的第二个位置创建一个为x的countercell对象
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
// 相当于解锁操作
cellsBusy = 0;
}
// 初始化成功退出
if (init)
break;
}
// 如果有一个线程在操作cell。那么就去抢占BaseCount。 -- 每个线程都有事儿做
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break; // Fall back on using base
}
}
扩容操作:
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)) {
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))) {
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
s = sumCount();
}
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
// sizeCtl此时是扩容的阈值
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n);
if (sc < 0) {
// 如果已经有线程对nextTable进行初始化,将会走到这个逻辑
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
// nexttable在transfer中赋值
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
// 每有一个线程帮助扩容,会执行sc+1
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
// 只有一个线程可以把sc改成负数
else if (U.compareAndSwapInt(this, SIZECTL, sc,
// rs << RESIZE_STAMP_SHIFT肯定返回一个很大的负数
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
转移(扩容)Map的操作:
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];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
// n - 扩容之前的数组大小
transferIndex = n;
}
int nextn = nextTab.length;
// put的位置如果碰到fwd,那么说明前面的转移已经完成,将会辅助后面的数据转移
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;
// i >= bound 表示这个线程还在其他线程的修改区域,继续执行循环
if (--i >= bound || finishing)
advance = false;
// 如果当前的transferIndex不大于0,说明修改已经完成,退出循环
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
// 修改transferindex的值
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
// stride -- 步长。每次修改一个步长的值
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
// 确定当前线程转移的区域。避免其他线程进入这段区域
bound = nextBound;
// 修改i的值,执行下面的转移
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;
}
// 先执行 - 1,表明当前线程的工作已经完成
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
// 看是否与初始值相等。相等说明已经没有线程参与扩容,扩容执行完毕
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
// 实际上退到上面的代码
/* 最终会走到这里面执行。将原来的table改变
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
*/
// 表明当前线程的扩容执行完成
finishing = advance = true;
i = n; // recheck before commit
}
}
// 这个位置为空,那么将fwd放到对应的位置
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
// 找到了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;
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);
// 转移完了就把当前位置设置为fwd
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}