概述
- ConcurrentHashMap是JDK中的并发Map,我们这次关于源码的探究,使用的是JDK8的版本。并没有去分析JDK7的ConcurrentHashMap的分段锁。
- 在实际开发中,经常使用的就是Map,在大多数情况下,使用的都是HashMap,而在并发场景下,则会使用ConcurrentHashMap,对于HashMap来说,其实现比较简单,就是红黑树和链表的处理。HashMap的源码,下次一定安排。
- 那我们就来分析一下ConcurrentHashMap的源码
CHM数据结构
CHM字段分析
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/*
* 散列表最大值,最大的元素个数
*/
private static final int MAXIMUM_CAPACITY = 1 << 30;
/*
* 散列表默认值
*/
private static final int DEFAULT_CAPACITY = 16;
/**
* 数组的最大长度
*/
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 并发级别 JDK1.7遗留下来的
* JDK只有在初始化的时候用了,其他时间没用
* 在JDK8中 不代表并发级别
*/
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
/**
* 负载因子
* JDK8不可以修改这个负载因子
* HashMap是可以修改的
*/
private static final float LOAD_FACTOR = 0.75f;
/**
*
* 树化的阈值
* 链表长度达到8的时候,有可能会树化操作
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 红黑树转化为链表的阈值
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 联合 TREEIFY_THRESHOLD 控制桶位是否树化,只有当table长度达到64且某个桶位中的链表长度达到8才会树化
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
*
* 线程迁移数据的最小步长 控制线程迁移任务最小区间的一个值
*/
private static final int MIN_TRANSFER_STRIDE = 16;
/**
* 扩容相关
* 计算扩容时生成的一个标识戳
*/
private static int RESIZE_STAMP_BITS = 16;
/**
* 65535 表示并发扩容的最多线程数
*/
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
/**
* 扩容相关
*/
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
/*
* Encodings for Node hash fields. See above for explanation.
*/
// node 节点的hash值为-1的时候,标识当前节点是FWD节点
static final int MOVED = -1; // hash for forwarding nodes
// node 节点的hash值为-2的时候,标识当前节点已经树化,且当前节点为TreeBin对象代理操作红黑树
static final int TREEBIN = -2; // hash for roots of trees
static final int RESERVED = -3; // hash for transient reservations
// 0x7fffffff => 0111 1111 1111 1111 1111 1111 1111 1111 31个1,二进制
// 可以将一个负数通过位运算的时候得到正数,但是不是取绝对值
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
/** Number of CPUS, to place bounds on some sizings */
// 当前CPU的核心数
static final int NCPU = Runtime.getRuntime().availableProcessors();
/** For serialization compatibility. */
// JDK1.8 会序列化,为了兼容JDK1.7的数据进行兼容的
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("segments", Segment[].class),
new ObjectStreamField("segmentMask", Integer.TYPE),
new ObjectStreamField("segmentShift", Integer.TYPE)
};
// table 就是散列表 长度是2的次方数
transient volatile Node<K,V>[] table;
/**
*
* 扩容的过程中,会将扩容中的新的table赋值给 nextTable 保持引用,扩容结束之后,这里会设置为null
*/
private transient volatile Node<K,V>[] nextTable;
/**
* 和 LongAdder 类似 LongAdder 的 baseCount 没有发生竞争的时候 或者 当前LongAdder处于加锁的状态中。使用这个进行计值
*/
private transient volatile long baseCount;
/**
* sizeCtl < 0
* 1. -1 表示当前table正在初始化(有线程正在创建table数组),当前线程需要自旋等待...
* 2. 表示当前table正在扩容,高16位表示扩容的标识戳 低16位表示 (1+nThread) 当前参与并发扩容的线程数量
*
* sizeCtl = 0 表示创建table数组的时候,使用 DEFAULT_CAPACITY 为大小
*
* sizeCtl > 0
* 1. 如果table没有初始化,表示初始化大小
* 2. 如果table已经发生初始化,表示下次扩容时候的触发条件(阈值)
*/
private transient volatile int sizeCtl;
/**
* 多线程情况下,扩容过程中,记录当前的扩容进度,所有的线程都需要从 transferIndex 中分配区间任务,去执行自己的任务
*/
private transient volatile int transferIndex;
/**
* LongAdder 中的 cellBusy 0 表示无锁 1 表示有锁
*/
private transient volatile int cellsBusy;
/**
* LongAdder 中的Cells数组,当baseCount发生竞争的时候,会创建Cells数组
* 线程会通过计算hash值,取到自己的cell,将增量累加到指定的cell中
* 取总数的时候 sum = base + Cells
*/
private transient volatile CounterCell[] counterCells;
}
- 上面的baseCount + counterCells 的总和,就是当前ConcurrentHashMap的元素综合,其计算方式和获取方式和LongAdder方式完全一样。如果不了解,参见如下链接。
此处为语雀内容卡片,点击链接查看:www.yuque.com/icanci/wer5…
CHM内部Node节点对象
- CHM内部Node节点对象:ConcurrentHashMap的所有的节点都继承此类,一共有四个实现类。我们在后面会进行分析。
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
// Node<K,V> 节点
static class Node<K,V> implements Map.Entry<K,V> {
// hash 值
final int hash;
// key
final K key;
// value 保证值的线程可见性
volatile V val;
// 下一个node节点 保证值的线程可见性
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;
}
public final K getKey() { return key; }
public final V getValue() { return val; }
public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
public final String toString(){ return key + "=" + val; }
public final V setValue(V value) {
throw new UnsupportedOperationException();
}
public final boolean equals(Object o) {
Object k, v, u; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(v = e.getValue()) != null &&
(k == key || k.equals(key)) &&
(v == (u = val) || v.equals(u)));
}
/**
* Virtualized support for map.get(); overridden in subclasses.
*/
Node<K,V> find(int h, Object k) {
Node<K,V> e = this;
if (k != null) {
do {
K ek;
if (e.hash == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
} while ((e = e.next) != null);
}
return null;
}
}
}
CHM内部小方法分析
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* 求和方法,参见LongAdderDe求和方式
*/
public int size() {
long n = sumCount();
return ((n < 0L) ? 0 :
(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
(int)n);
}
/**
* 是否为空
*/
public boolean isEmpty() {
return sumCount() <= 0L; // ignore transient negative values
}
// CounterCell
@sun.misc.Contended static final class CounterCell {
volatile long value;
CounterCell(long x) { value = x; }
}
// 求和
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;
}
/*
* rehash 的一个算法
*
* 1100 0011 1010 0101 0001 1100 0001 1110
* 0000 0000 0000 0000 1100 0011 1010 0101
*
* 1100 0011 1010 0101 1101 1111 1011 1011
* ---------------------------------------
* 0111 1111 1111 1111 1111 1111 1111 1111
* 0100 0011 1010 0101 1101 1111 1011 1011 修改符号位 是一个正数
*/
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
// 返回指定table下边的Node节点元素
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
// tab 数组对象
// 指定元素的偏移量
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
/**
* casTabAt
*
* @param tab tab
* @param i 位置
* @param c 期望值
* @param v 设置值
*/
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
// CAS 修改
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
/**
*
* @param tab tab
* @param i 数组下标位置
* @param 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);
}
/**
* 计算一个扩容标识戳 用来识别是不是同一批次扩容,因为并发场景下可能多次进行扩容
*
* 16 -> 32 长度
* n = 16
* Integer.numberOfLeadingZeros(n) => 1 0000 = 32 - 5 = 27
*/
static final int resizeStamp(int n) {
// RESIZE_STAMP_BITS 是固定值 16 左移15位
// (1 << (RESIZE_STAMP_BITS - 1) => 0000 0000 0000 0001
// 1000 0000 0000 0000 = 32768
// 27 | 65536
// 0000 0000 0001 1011
// 1000 0000 0000 0000
// 1000 0000 0001 1011 => 一个戳
return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}
}
CHM构造方法分析
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* Creates a new, empty map with the default initial table size (16).
*/
public ConcurrentHashMap() {
}
/**
* 指定元素大小的初始容量
*/
public ConcurrentHashMap(int initialCapacity) {
if (initialCapacity < 0)
throw new IllegalArgumentException();
// 大于一半的值 就使用 MAXIMUM_CAPACITY
int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
MAXIMUM_CAPACITY :
// 否则就调用 tableSizeFor
// 将initialCapacity+initialCapacity又移1位再加1
tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
// sizeCtl > 0 并且table没有初始化,就表示初始化容量
this.sizeCtl = cap;
}
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
this.sizeCtl = DEFAULT_CAPACITY;
putAll(m);
}
public ConcurrentHashMap(int initialCapacity, float loadFactor) {
this(initialCapacity, loadFactor, 1);
}
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
// 计算size
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
}
- 针对上面的构造方法和初始化大小的计算,我这里做了一个Demo来测试,为什么不直接使用
initialCapacity
计算出来的大小,而是使用initialCapacity + (initialCapacity >>> 1) + 1)
public class SizeDemo {
private static final int MAXIMUM_CAPACITY = 1 << 30;
private static final int DEFAULT_CAPACITY = 16;
public static void main(String[] args) {
initCapacity(0);
initCapacity(1);
initCapacity(2);
initCapacity(3);
initCapacity(4);
initCapacity(5);
}
private static void initCapacity(int initialCapacity) {
System.out.println("传参大小:" + initialCapacity);
int res = initialCapacity + (initialCapacity >>> 1) + 1;
System.out.println("偏移之后大小:" + res);
int tableSize = tableSizeFor(res);
System.out.println("实际Table大小:" + tableSize);
System.out.println("计算的下次扩容大小:" + (tableSize - (tableSize >>> 2)));
System.out.println("----------------- 华丽的分隔线 -----------------");
}
/**
* tableSizeFor
*/
private static final int tableSizeFor(int c) {
int n = c - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
}
- 测试结果如下
传参大小:0
偏移之后大小:1
实际Table大小:1
计算的下次扩容大小:1
----------------- 华丽的分隔线 -----------------
传参大小:1
偏移之后大小:2
实际Table大小:2
计算的下次扩容大小:2
----------------- 华丽的分隔线 -----------------
传参大小:2
偏移之后大小:4
实际Table大小:4
计算的下次扩容大小:3
----------------- 华丽的分隔线 -----------------
传参大小:3
偏移之后大小:5
实际Table大小:8
计算的下次扩容大小:6
----------------- 华丽的分隔线 -----------------
传参大小:4
偏移之后大小:7
实际Table大小:8
计算的下次扩容大小:6
----------------- 华丽的分隔线 -----------------
传参大小:5
偏移之后大小:8
实际Table大小:8
计算的下次扩容大小:6
----------------- 华丽的分隔线 -----------------
- 在
initTable()
方法中,这sc = n - (n >>> 2);
(n表示当前table数组的长度,sc表示下一次扩容阈值),上述代码就是将sc设置为3/4 n = 0.75 * n
,也就是当前table长度的0.75倍,也就是固定的扩容因子 - 这个地方呼应上方的初始化操作
tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)
,我理解的是最大程度的保证这个sc是当前table的0.75倍
- 根据我们上面的SizeDemo的数据来看,只有传参是
0或者1
的时候,下次扩容的阈值是table本身大小,其他的数值,都是table的0.75倍,所以我说最大程度的保证这个sc是当前table的0.75倍
CHM#put方法分析
- put方法是核心方法之一,源码解析如下
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
public V put(K key, V value) {
// putVal 方法
// false 说明会替换,为true,则有相同数据,写失败
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();
// 根据hashcode 计算hash,在数据量少的时候,高16位也参与计算
int hash = spread(key.hashCode());
// binCount 表示当前k-v 封装成的node之后,插入到指定桶位后,在桶位中的所属链表的下标位置
// 0 表示当前桶位为null,mode可以直接放着
// 2 表示当前桶位已经树化为红黑树
int binCount = 0;
// 自旋
// tab 就是引用table
for (Node<K,V>[] tab = table;;) {
// f 表示桶位的头结点
// n 表示散列表数组的长度
// i 表示key通过寻址计算之后得到的桶位的下标
// fh 表示桶位头结点的hash值
Node<K,V> f; int n, i, fh;
// CASE1:tab尚未进行初始化,需要初始化table
if (tab == null || (n = tab.length) == 0)
// 初始化表
tab = initTable();
// CASE2:tab 是有值的,
// i 表示key使用路由寻址算法得到 key对应 table数组的下标位置
// tabAt 获取指定桶位的头结点
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
// 如果头节点是空,也就这个桶位没有被初始化,这里就设置CAS设置桶位的值
// CAS成功,break 跳出循环
// CAS失败,当前线程再次自旋设值
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
// CASE3:得到的桶头节点有值,有可能是个普通节点,
// 如果hash值为 MOVED 标识当前节点是FWD节点,表示当前map正在处于扩容过程中
else if ((fh = f.hash) == MOVED)
// 迁移的时候才会处理
// 当前线程有义务帮助当前的map对象完成数据迁移的工作
// 扩容完成之后处理
tab = helpTransfer(tab, f);
// CASE4:当前桶位置可能是链表、也有可能是红黑树代理节点
else {
// 当插入的key存在的时候,会将老的值丢出去
V oldVal = null;
// 给头元素加锁,那就是加锁整个桶节点
synchronized (f) {
// 理论头节点
// 再次计算想要操作的桶是不是想要操作的桶
// PS:这里可以总结出来的是什么呢(包括LongAdder),锁的是同一个对象,但是但是有室内外的差异
// 那就要重新判断
if (tabAt(tab, i) == f) {
// 如果桶位头结点的hash值 等于0
// 说明当前节点就是普通的链表节点
if (fh >= 0) {
// 1.当前插入key与链表的所有元素的key都不一样时候,当前的插入操作追到到链表末尾 binCount 指的是链表长度
// 2.当前插入key与链表的所有元素的key一样时候,当前操作可能是替换,binCount 表示冲突位置 (binCount - 1 )
binCount = 1;
// 迭代当前桶位的链表
// e 是每次循环处理的节点
for (Node<K,V> e = f;; ++binCount) {
// 当下e的key
K ek;
// 条件1:e.hash == hash 表示当前元素的hash值与插入节点的hash值,需要进一步判断
// 条件2:(ek = e.key) == key 说明e key 和 key 相等
// 条件3:ek != null && key.equals(ek) 判断 ek 和 key 一直
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
// 赋旧值
oldVal = e.val;
// 是否进行替换操作
if (!onlyIfAbsent)
e.val = value;
// 跳出
break;
}
// 当前元素和当前插入的key不一致
Node<K,V> pred = e;
// 1.更新当前节点的下一个节点,如果是null则插入到队尾节点
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,因为 binCount <= 1 的时候有其他含义,这里设置为2
binCount = 2;
// 条件1:成立,说明key一样,冲突了,
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
// 冲突节点赋值给oldVal
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
// 说明当前桶位不为null,可能是红黑树,也可能是链表
if (binCount != 0) {
// 如果大于等于8 ,表示处理的一定是链表
if (binCount >= TREEIFY_THRESHOLD)
// 链表转化为树
treeifyBin(tab, i);
// 返回 oldVal
if (oldVal != null)
return oldVal;
break;
}
}
}
// 1.统计当前table一共有多少数据
// 2.判断是否达到扩容阈值标准,触发扩容
addCount(1L, binCount);
// 没有冲突
return null;
}
}
CHM#initTable方法分析
- ConcurrentHashMap是懒加载的,当使用的时候才回去创建表
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* Initializes table, using the size recorded in sizeCtl.
*
* sizeCtl < 0
* 1. -1 表示当前table正在初始化(有线程正在创建table数组),当前线程需要自旋等待...
* 2. 表示当前table正在扩容,高16位表示扩容的标识戳 低16位表示 (1+nThread) 当前参与并发扩容的线程数量
*
* sizeCtl = 0 表示创建table数组的时候,使用 DEFAULT_CAPACITY 为大小
*
* sizeCtl > 0
* 1. 如果table没有初始化,表示初始化大小
* 2. 如果table已经发生初始化,表示下次扩容时候的触发条件(阈值)
*
* 可能被多个线程调用
* 初始化table
*/
private final Node<K,V>[] initTable() {
// tab 表示map的table引用
// sc 表示临时局部的sizeCtl的值
Node<K,V>[] tab; int sc;
// 自旋
// 条件是 散列表没有初始化
while ((tab = table) == null || tab.length == 0) {
// 小于0,此时表示 其他线程正在初始化操作
if ((sc = sizeCtl) < 0)
Thread.yield(); // lost initialization race; just spin
// 1. sizeCtl = 0 表示创建table数组的时候,使用DEFAULT_CAPACITY
// 2. 如果table未初始化,表示初始化大小
// 3. 如果table初始化了,表示下次扩容的触发条件(阈值)
// CAS 设置 sc 为 -1,也就是设置 sizeCtl 为-1
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
// 设置成功
// 判断table是否初始化了
// 这里的判断和LongAdder里面的判断逻辑类似,在加锁之后在进行一次单独的判断
// 防止其他线程初始化完毕之后,再次初始化,丢失数据
if ((tab = table) == null || tab.length == 0) {
// 如果 sc 大于0 就使用 sc,否则使用 DEFAULT_CAPACITY
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
// 创建数组
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
// 赋值给table
table = tab = nt;
// n 无符号右移2位
// sc设置为 3/4 n = 0.75 * n
// 这个地方呼应上方的初始化操作 tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1)
// 最大程度的保证这个sc是0.75倍n
// 表示下一次扩容的条件
sc = n - (n >>> 2);
}
} finally {
// 扩容条件
// 1.如果table已经初始化了,那sc就不变
// 2.如果当前线程是初始化线程,那么sc表示下一次扩容的阈值
// 3.在进入自旋的时候,修改为了-1,这时候需要修改为sc
sizeCtl = sc;
}
break;
}
}
return tab;
}
}
CHM#addCount方法分析
- 在进行添加或者删除元素的时候,都有调用addCount方法,其会做2个事情,第一就是计数,当前有多少元素;第二就是计算是否需要进行扩容。
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* Adds to count, and if table is too small and not already
* resizing, initiates transfer. If already resizing, helps
* perform transfer if work is available. Rechecks occupancy
* after a transfer to see if another resize is already needed
* because resizings are lagging additions.
*
* @param x the count to add
* @param check if <0, don't check resize, if <= 1 only check if uncontended
*/
private final void addCount(long x, int check) {
// LongAdder Start
// as: CounterCell 数组
// b : baseCount
// s : 当前map.table 元素的数量
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);
// 考虑到 fullAddCount 里面的事情已经比较耗时了,就让当前线程不参与到扩容相关的逻辑
return;
}
// check
// put 方法进来
// check >= 1 桶位链表长度
// check == 0 插入的桶位没有数据
// check == 2 已经树化了
// remove 方法进来
// check == -1
if (check <= 1)
return;
// 获取当前散列表的元素个数 是期望值
s = sumCount();
}
// LongAdder End
// 上述这一段代码和 fullAddCount 方法,和LongAdder的思想以及实现方式完全一致,看LongAdder即可
// 上面在if里面写成功之后,就走到这里
// 一定是一个put操作调用的addCount
// 删除的时候不需要扩容
if (check >= 0) {
// tab 表示 map.table
// nt 表示map.nextTable
// n 表示map.table数组的长度
// sc 表示sizeCtl的临时值
Node<K,V>[] tab, nt; int n, sc;
/**
* sizeCtl < 0
* 1. -1 表示当前table正在初始化(有线程正在创建table数组),当前线程需要自旋等待...
* 2. 表示当前table正在扩容,高16位表示扩容的标识戳 低16位表示 (1+nThread) 当前参与并发扩容的线程数量 可能
*
* sizeCtl = 0 表示创建table数组的时候,使用 DEFAULT_CAPACITY 为大小
*
* sizeCtl > 0
* 1. 如果table没有初始化,表示初始化大小
* 2. 如果table已经发生初始化,表示下次扩容时候的触发条件(阈值)
*/
// 自旋
// 条件1: s >= (long)(sc = sizeCtl) 表示
// true -> 1.当前sizeCtl为一个负数,表示正在扩容中
// 2.当前sizeCtl为一个整数,表示扩容阈值
// false ->表示当前table尚未达到扩容条件
// 条件2:(tab = table) != null TODO 恒成立?需要验证下
// 条件3: (n = tab.length) < MAXIMUM_CAPACITY 散列表的长度小于限制的最大值,表示可以扩容
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
// 先拿到当前扩容(批次)的唯一标识戳
// 16 -> 32 => 1000 0000 0001 1011
int rs = resizeStamp(n);
// 正在扩容 当前table正在扩容
// 当前线程理论上应该协助table完成扩容
// 条件1:(sc >>> RESIZE_STAMP_SHIFT) != rs
// true 说明当前线程获取到的扩容唯一标识戳 非 本批次扩容
// false 说明当下线程获取的扩容唯一标识戳 是 本批次扩容
// 条件2:sc == rs + 1 JDK1.8中有bug,其实想表达的是 sc == (rs << 16) + 1
// true:标识扩容完毕了
// false:扩容正在进行中,当前线程可以参与
// 条件3:sc == rs + MAX_RESIZERS 其实想表达的是 sc == (rs << 16) + MAX_RESIZERS
// true:表示当前线程并发达到了极限值
// false:表示当前线程可以参与进来
// 条件4:(nt = nextTable) == null 表示扩容结束
// 条件5: transferIndex <= 0 扩容进度结束 不需要在扩容了
if (sc < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
// 前置条件,当前table正在进行扩容,更新 SIZECTL 为 sc + 1
// 条件成立:说明当前线程成功参与到扩容任务中,并且将sc低16位的值+1 表示多了 一个线程参与工作
// 条件失败:说明参与工作的线程,cas失败,下次还会来到这里
// 1:很多线程在这里尝试修改sizeCtl,导致一个成功,其他的都失败
// 2:transfer 任务内部线程也修改了 sizeCtl
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
// 协助扩容线程持有 nextTable 引用
transfer(tab, nt);
}
// 1000 0000 0001 1011 0000 0000 0000 0000 + 2
// 1000 0000 0001 1011 0000 0000 0000 0010
// 条件成立,当前是触发扩容的第一个线程,transfer 需要做一些准备工作
// 否则,不是第一个触发的
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
// 触发条件的线程不持有 nextTable
transfer(tab, null);
s = sumCount();
}
}
}
// See LongAdder version for explanation
// 此处的方法和LongAdder中的计算方式一致
private final void fullAddCount(long x, boolean wasUncontended) {
int h;
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 &&
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
else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
break;
else if (counterCells != as || n >= NCPU)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (cellsBusy == 0 &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
try {
if (counterCells == as) {// Expand table unless stale
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);
}
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
if (counterCells == as) {
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
if (init)
break;
}
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break; // Fall back on using base
}
}
}
CHM#transfer方法分析
- 在扩容的时候,需要进行数据的迁移
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* 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) {
// n 为扩容之前数组的table的长度
// stride 表示分配给线程的任务的步长
int n = tab.length, stride;
// 根据CPU核心数计算出来的一个值
// 现在将 stride 固定为16进行讲解
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
// nextTable为null走到这里
// 条件成立:当前线程为触发本次扩容的线程,需要做一些准备工作
// 条件不成立:当下线程为协助扩容的线程...
if (nextTab == null) { // initiating
try {
// 创建一个比扩容之前大一倍的table
@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;
}
// 赋值对象给 nextTab
nextTable = nextTab;
// 记录当前的扩容进度
transferIndex = n;
}
// 新数组的长度
int nextn = nextTab.length;
// fwd节点 当某个桶位数据处理完毕之后,将此桶位设置为fwd节点,其他写线程或者读线程看到之后,会有不同的逻辑
// 指向新表的引用
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
// 推进标记
boolean advance = true;
// 完成标记
boolean finishing = false; // to ensure sweep before committing nextTab
// 自旋
// i 表示分配给当前线程任务,执行到的桶位
// bound 表示分配给当前线程任务的下界限制
// int i = 0, bound = 0
for (int i = 0, bound = 0;;) {
// f 桶位的头结点
// fh 头结点的hash值
Node<K,V> f; int fh;
/**
* 1.给当前线程分配任务区间
* 2.维护当下线程任务进度(i 表示当前处理的桶位)
* 3.维护map对象全局范围内的进度
*/
while (advance) {
// 分配任务区间的变量
// nextIndex 分配任务的开始下标
// nextBound 分配任务的结束下标
int nextIndex, nextBound;
// CASE1
// 条件1:成立表示 当前线程的任务尚未完成,还有响应的区间的桶位需要处理,--i 就让当前线程处理下一个桶位
// 不成立表示 当前线程已经完成或者未分配
if (--i >= bound || finishing)
advance = false;
// CASE2
// 前置条件:当前任务已经完成或者未分配
// 条件成立,表示对象全局范围内的桶位分配完毕,没有区间可分配了,设置当前线程i的变量为-1,跳出循环之后,执行退出迁移任务相关的程序
// 条件不成立 说明对象全局范围内的桶位尚未分配完毕
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
// CASE3
// 前提条件:当前线程需要分配任务空间 并且 全局范围内还有桶位尚未迁移
// CAS 去更新
// 条件成功 说明给当前线程你从分配任务成功
// 条件不成立 说明分配给当下线程失败,应该是和其他线程发生了竞争
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
// CASE1
// 处理线程任务完成之后,退出方法的逻辑
// i >= n || i + n >= nextn 这两个条件应该不会成立
// i < 0 成立表示当下线程没有分配到任务
if (i < 0 || i >= n || i + n >= nextn) {
// sc sizeCtl 的变量
int sc;
// 结束了
if (finishing) {
// nextTable 清空
nextTable = null;
// 设置table值
table = nextTab;
// sizeCtl 修改为 0.75 n
sizeCtl = (n << 1) - (n >>> 1);
return;
// CAS 更新
// 条件成立,说明设置sizeCtl 低16位 -1 成功,当前线程可以正常退出
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
// 说明当前线程不是最后一个退出 transfer任务的线程
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
// 前置条件 【CASE2~CASE4】当前线程尚未处理完,正在进行中
// 线程处理一个桶位的数据的迁移工作,处理完毕之后设置advance为true继续推进,然后就会回到for
// CASE2:如果头节点为空
// 说明当前桶位没有存放数据,只需要设置为FWD节点接口
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
// CASE3:如果当前节点是FWD节点。表示已经处理了,继续自旋
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
// CASE4:前置条件,当前桶位有数据,而且Node节点不是FWD节点,说明这些数据需要迁移
else {
// 锁在头节点
synchronized (f) {
// 如果f是头节点,有可能是第一次取到的是头对象,然后别的线程把头节点替换了
if (tabAt(tab, i) == f) {
// ln 低位链表引用
// hn 高位链表的引用
Node<K,V> ln, hn;
// 条件成立,说明当前桶位是链表
if (fh >= 0) {
// 头节点hash & tab数组长度
// lastrun 机制
// 可以获取出当前链表末尾连续高位不变的node
int runBit = fh & n;
Node<K,V> lastRun = f;
for (Node<K,V> p = f.next; p != null; p = p.next) {
// 当前节点的hash & tab数组长度
int b = p.hash & n;
// 和上一个节点不相等,则 lastRun = p
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
// 说明 lastrun 引用的链表为低位链表
if (runBit == 0) {
ln = lastRun;
hn = null;
}
// 否则说明lastrun引用的链表为高位链表
else {
hn = lastRun;
ln = null;
}
// 迭代链表 跳出条件:当前循环节点抵达lastRun节点
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);
}
// 设置新低位为i ln
setTabAt(nextTab, i, ln);
// 设置新高位为 i+n hn
setTabAt(nextTab, i + n, hn);
// 原tab的i节点设置为fwd,也即是不需要进行处理,已经处理过了。
// 注意:这里的扩容,不会存在冲突的场景
setTabAt(tab, i, fwd);
advance = true;
}
// 说明是红黑树代理节点
else if (f instanceof TreeBin) {
// 转化头节点为 TreeBin
TreeBin<K,V> t = (TreeBin<K,V>)f;
// 低位双向链表 lo 低位链表头 loTail 低位链表尾巴
TreeNode<K,V> lo = null, loTail = null;
// 高位双向链表 hi 高位链表头 hiTail 高位链表尾巴
TreeNode<K,V> hi = null, hiTail = null;
// lc 表示低位链表元素数量
// hc 表示高位链表元素数量
int lc = 0, hc = 0;
// 迭代TreeBin节点进行迭代
for (Node<K,V> e = t.first; e != null; e = e.next) {
// 当前循环节点的hash值
int h = e.hash;
// p 使用当前节点构建的新的node节点
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
// 使用的是尾插法
// 如果 (h & n) == 0 是低位节点
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;
}
}
}
}
}
}
}
- 在addCount,方法中,会调用
transfer
方法,在调用之前,会先设置sizeCtl的临时值,如果是第一个线程进来,会设置为(rs << RESIZE_STAMP_SHIFT) + 2)
,如何是第二个之后的线程进来,会设置为sc + 1
- 而在
transfer
方法中,执行完操作之后,会CASsc - 1
,如果成功,再判断(sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT
,如果成立,那就是不等于,也就不会进行处理。如果不成立,那就是等于,也就是说,当前线程是第一次进来的线程,也就是第一次写线程,这个时候,会进行一些收尾工作。 - 可以理解为现在外面进行加锁,然后再方法里面解锁,保证多线程的处理是能够有始有终的。
CHM#helpTransfer方法分析
- 在扩容的时候,需要进行数据的迁移
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* Helps transfer if a resize is in progress.
*
* 帮助迁移数据
* table
* f 头节点
*/
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
// nextTab 引用的是 fwd的nextTable == map.nextTable
// sc 保存的是 sizeCtl
Node<K,V>[] nextTab; int sc;
// tab 不为空
// f 是FWD节点
if (tab != null && (f instanceof ForwardingNode) &&
// 当前的 fwd 的 nextTable 不为空
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
// 获取扩容标识戳
int rs = resizeStamp(tab.length);
// 条件1:nextTab == nextTable
// 成立:标识当前扩容正在进行中
// 不成立:1.nextTable被设置成null了,扩容完毕之后,会设置成null
// 2.再次触发扩容了,拿到的nextTable过期了
// 条件1:table == tab
// 成立:说明扩容还未完成
// 不成立:扩容结束了
// 条件3:(sc = sizeCtl) < 0
// 成立:扩容还在进行中
// 不成立:扩容完成了,表示的是阈值
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
// 条件1:(sc >>> RESIZE_STAMP_SHIFT) != rs
// true 说明当前线程获取到的扩容唯一标识戳 非 本批次扩容
// false 说明当下线程获取的扩容唯一标识戳 是 本批次扩容
// 条件2:sc == rs + 1 JDK1.8中有bug,其实想表达的是 sc == (rs << 16) + 1
// true:标识扩容完毕了
// false:扩容正在进行中,当前线程可以参与
// 条件3:sc == rs + MAX_RESIZERS 其实想表达的是 sc == (rs << 16) + MAX_RESIZERS
// true:表示当前线程并发达到了极限值
// false:表示当前线程可以参与进来
// 条件4: transferIndex <= 0 扩容进度结束 不需要在扩容了
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
//
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}
}
CHM#get方法分析
- get方法,获取获取元素
- 在查询元素的时候,我们可以和HashMap的查找元素结合起来,是先找到hash之后的index桶节点,然后再判断桶节点,在进行处理。
- 需要注意的是TreeBin节点,里面即有双向链表,也有红黑树,我们可以理解为双向链表的元素和红黑树的数据是一样的,在后面分析TreeBin的时候会说明如果是TreeBin节点如何进行查找元素的。
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
// 查询元素
public V get(Object key) {
// tab map.table
// e 当前元素
// p 目标节点
// n table的长度
// eh 当前元素的hash
// ek 当前元素的key
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
// 得到一个hash值,写的时候就是这样运算的
int h = spread(key.hashCode());
// 条件1:(tab = table) != null && (n = tab.length) > 0 没有数据或者table的长度也有
// 条件2:e = tabAt(tab, (n - 1) & h)) != null 头节点不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
// 如果头节点的hash值等于查询的hash
if ((eh = e.hash) == h) {
// 并且key完全相等
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
// 1. -1 fwd 节点,桶里面的数据已经被迁移了
// 2. -2 TreeBin节点,需要使用TreeBin提供的find方法进行查询
else if (eh < 0)
// 调用TreeBin的find方法
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;
}
}
// 不满足,返回null
return null;
}
}
CHM#remove方法分析
- 删除元素的分析
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
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.
* @param key key
* @param value 需要被替换的值(新值)
* @param cv 需要比较的value(老值)
*/
final V replaceNode(Object key, V value, Object cv) {
// 计算hash
int hash = spread(key.hashCode());
// tab 当前的table
// 自旋处理
for (Node<K,V>[] tab = table;;) {
// f 桶位头节点
// n table的长度
// i 表示hash命中桶位下标
// fh 头节点的hash
Node<K,V> f; int n, i, fh;
// CASE1
// tab == null || (n = tab.length) == 0 表示为空,不需要处理
// f = tabAt(tab, i = (n - 1) & hash)) == null 头节点为空,不处理
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null)
break;
// CASE2:当前节点不是空
// 如果当前节点的hash为-1 当前节点是fwd节点
// 当前是扩容操作,当前操作是一个写操作,所以这个线程需要协助table完成扩容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
// CASE3
// 否则是一个正常的有数据的桶位
// 可能是链表,也可能是红黑树
else {
// oldVal 旧的元素的值
V oldVal = null;
// validated 是否执行成功
boolean validated = false;
// 加锁桶位头节点
synchronized (f) {
// 计算当前节点是桶节点
if (tabAt(tab, i) == f) {
// 如果头节点的hash大于0
// 为链表节点或单个元素
if (fh >= 0) {
validated = true;
// 遍历链表
// e 循环处理元素
// pred 当前节点的上一个节点
for (Node<K,V> e = f, pred = null;;) {
// 元素的hash
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
V ev = e.val;
// cv == null 替换的值为null,那就是一个删除操作
// cv == ev || (ev != null && cv.equals(ev)) 那么就是一个替换操作
if (cv == null || cv == ev ||
(ev != null && cv.equals(ev))) {
oldVal = ev;
// 是一个替换操作
if (value != null)
e.val = value;
// 当前节点不是头节点
else if (pred != null)
pred.next = e.next;
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;
// r 为TreeBin的根节点
// p 查找到key一致的node
TreeNode<K,V> r, p;
// 条件1:(r = t.root) != null
// 条件2:findTreeNode 搜索红黑树的方法 查找的元素不为null,并且查找到了
if ((r = t.root) != null &&
(p = r.findTreeNode(hash, key, null)) != null) {
// 赋值给p
// pv P的value
V pv = p.val;
// cv == null 替换的值为null,那就是一个删除操作
// cv == ev || (ev != null && cv.equals(ev)) 那么就是一个替换操作
if (cv == null || cv == pv ||
(pv != null && cv.equals(pv))) {
oldVal = pv;
// 替换
if (value != null)
p.val = value;
// 删除
// 删除之后如果节点太短了,就要逆序树化
else if (t.removeTreeNode(p))
// 需要链表化,反转为链表
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
}
// 当其他线程修改过桶位头节点的时候
// 当前线程sync头节点,锁错对象的时候,validated 为false。会进入下次自旋
if (validated) {
if (oldVal != null) {
if (value == null)
addCount(-1L, -1);
return oldVal;
}
break;
}
}
}
return null;
}
}
CHM#TreeBin分解
- 在上文我们说了Node节点的四个实现类,其中一个就是TreeBin,是一个代理节点
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* TreeNodes used at the heads of bins. TreeBins do not hold user
* keys or values, but instead point to list of TreeNodes and
* their root. They also maintain a parasitic read-write lock
* forcing writers (who hold bin lock) to wait for readers (who do
* not) to complete before tree restructuring operations.
*
* TreeBin 元素
*/
static final class TreeBin<K,V> extends Node<K,V> {
// 红黑树root节点
TreeNode<K,V> root;
// 链表的头节点
volatile TreeNode<K,V> first;
// 当前等待这线程,未获取到(lockState是读锁状态)
volatile Thread waiter;
// 1. 写锁状态 写是独占状态,写线程只能有一个
// 2. 读锁状态 读是共享状态,同一时刻可以有多个线程同时进入到TreeBin中获取数据,每个线程都会给 lockstate + 4
// 3. 等待状态(写线程等待) 当TreeBin 中有读线程目前正在读取数据的时候,写线程无法修改数据, 那么就将lockstate设置为最低2位 0b 10 即,换算成十进制就是WAITER = 2;
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
/**
* Tie-breaking utility for ordering insertions when equal
* hashCodes and non-comparable. We don't require a total
* order, just a consistent insertion rule to maintain
* equivalence across rebalancings. Tie-breaking further than
* necessary simplifies testing a bit.
*/
static int tieBreakOrder(Object a, Object b) {
int d;
if (a == null || b == null ||
(d = a.getClass().getName().
compareTo(b.getClass().getName())) == 0)
d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
-1 : 1);
return d;
}
/**
* Creates bin with initial set of nodes headed by b.
*
* @param b 链表的头元素
*/
TreeBin(TreeNode<K,V> b) {
// 设置节点hash为-2 表示次节点是TREEBIN 节点
super(TREEBIN, null, null, null);
// first 就是这个双向链表
this.first = b;
// 红黑树的根节点
TreeNode<K,V> r = null;
// x 表示遍历的当前节点
// next 当前节点的下一个节点
for (TreeNode<K,V> x = b, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
// 强制设置当前插入节点的左右子树为null
x.left = x.right = null;
// 条件成立,当前的红黑树是空树,那么设置插入元素,为根节点
if (r == null) {
// 根节点的父节点为null
x.parent = null;
// 根节点为黑色
x.red = false;
// 让r引用x对象
r = x;
}
// 非第一次
else {
// k key
// h hash
K k = x.key;
int h = x.hash;
// key 的 class类型
Class<?> kc = null;
// 自旋
// p 表示为查找插入节点父节点的一个临时节点
for (TreeNode<K,V> p = r;;) {
// dir -1 1
// -1 表示插入节点的hash值大于 当前p节点的hash
// 0 表示插入节点的hash值小于 当前p节点的hash
// ph 为查找插入节点的父节点的一个临时节点的hash
int dir, ph;
// 临时节点key
K pk = p.key;
// 插入节点的hash值小于当前节点
if ((ph = p.hash) > h)
// 插入节点可能需要插入到当前节点的左子节点 或者在左子树上查找
dir = -1;
// 插入节点的hash值,大于当前节点
else if (ph < h)
// 插入节点可能需要插入到当前节点的右子节点 或者在右子树上查找
dir = 1;
// 如果执行到这里,说明当前插入的节点的hash如当前节点的hash一致,会做出排序
// 拿到的dir不是-1就是1
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
// xp 想要表示的是插入节点的父节点
TreeNode<K,V> xp = p;
// 条件成立:说明当前p节点,为插入节点的父节点
// 条件不成立:说明p节点地下还有层次,需要将p指向p的左子节点或者右子节点。继续向下搜索
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
// 平衡
r = balanceInsertion(r, x);
break;
}
}
}
}
// root 设置为r
this.root = r;
assert checkInvariants(root);
}
/**
* Acquires write lock for tree restructuring.
*/
private final void lockRoot() {
// 条件成立,说明CAS失败,说明 LOCKSTATE 不是0,此时有读线程正在TreeBin红黑树中读取数据
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;
// 循环
// s 表示lock值
for (int s;;) {
// ~WAITER = 11111...0
// (s = lockState) & ~WAITER) == 0 表示Treebin没有读线程在访问红黑树
if (((s = lockState) & ~WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
if (waiting)
// 设置Treebin对象因为为null
waiter = null;
return;
}
}
// 条件不成立
// (s & WAITER) == 0
// lock & 0000...10 = 0
// 说明lock中waiter的标志位为0,此时当前线程可以设置为1了,然后将当前线程挂起
else if ((s & WAITER) == 0) {
if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
// 设置 waiting 为true
waiting = true;
// 设置 waiter
waiter = Thread.currentThread();
}
}
// 是等待
// 挂起当前线程
else if (waiting)
LockSupport.park(this);
}
}
/**
* Returns matching node or null if none. Tries to search
* using tree comparisons from root, but continues linear
* search when lock not available.
*/
final Node<K,V> find(int h, Object k) {
// 判断key 不为空
if (k != null) {
// 循环
// e 当前元素
// first 链表节点
for (Node<K,V> e = first; e != null; ) {
// s lock状态
// ek 链表当前节点的key
int s; K ek;
// 0010 | 0001 = 0011
// 条件成立,表示当前的TreeBin 有等待线程(写操作线程正在加锁)
if (((s = lockState) & (WAITER|WRITER)) != 0) {
// 按照链表进行查询
if (e.hash == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
e = e.next;
}
// 前置条件:当前TreeBin中,没有等待线程(写线程)
// CAS 增加 READER
else if (U.compareAndSwapInt(this, LOCKSTATE, s,
s + READER)) {
TreeNode<K,V> r, p;
try {
// 从红黑树查找节点
p = ((r = root) == null ? null :
r.findTreeNode(h, k, null));
} finally {
// 查询结束
// 释放读锁
// (READER|WAITER) 0110 表示当前只有一个线程在读,且有一个线程在等待
// -4 之后的值
// 当前读线程是最后一个读线程,才会进行 unpark
Thread w;
if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
(READER|WAITER) && (w = waiter) != null)
// 唤醒 w 线程
LockSupport.unpark(w);
}
return p;
}
}
}
return null;
}
/**
* Finds or adds a node.
* 丢值
* @return null if added
*/
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;
if (p == null) {
first = root = new TreeNode<K,V>(h, k, v, null, null);
break;
}
else if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 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;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
// 当前循环节点p就是x节点的父亲节点
// x 表示插入节点
// f 表示修改链表之前的头节点
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;
// 如果是黑色,改成共色
if (!xp.red)
x.red = true;
else {
// 否则就需要加锁自平衡
// Tips: 为啥TreeBin节点需要有链表也要有红黑树?
//
lockRoot();
try {
root = balanceInsertion(root, x);
} finally {
unlockRoot();
}
}
break;
}
}
assert checkInvariants(root);
return null;
}
/**
* Removes the given node, that must be present before this
* call. This is messier than typical red-black deletion code
* because we cannot swap the contents of an interior node
* with a leaf successor that is pinned by "next" pointers
* that are accessible independently of lock. So instead we
* swap the tree linkages.
*
* @return true if now too small, so should be untreeified
* 如果返回true,说明节点太短了,外面需要链表化
*/
final boolean removeTreeNode(TreeNode<K,V> p) {
// 当前节点的下一个节点
TreeNode<K,V> next = (TreeNode<K,V>)p.next;
// 当前节点的上一个节点
TreeNode<K,V> pred = p.prev; // unlink traversal pointers
TreeNode<K,V> r, rl;
if (pred == null)
first = next;
else
pred.next = next;
if (next != null)
next.prev = pred;
if (first == null) {
root = null;
return true;
}
if ((r = root) == null || r.right == null || // too small
(rl = r.left) == null || rl.left == null)
return true;
lockRoot();
try {
TreeNode<K,V> replacement;
TreeNode<K,V> pl = p.left;
TreeNode<K,V> pr = p.right;
if (pl != null && pr != null) {
TreeNode<K,V> s = pr, sl;
while ((sl = s.left) != null) // find successor
s = sl;
boolean c = s.red; s.red = p.red; p.red = c; // swap colors
TreeNode<K,V> sr = s.right;
TreeNode<K,V> pp = p.parent;
if (s == pr) { // p was s's direct parent
p.parent = s;
s.right = p;
}
else {
TreeNode<K,V> sp = s.parent;
if ((p.parent = sp) != null) {
if (s == sp.left)
sp.left = p;
else
sp.right = p;
}
if ((s.right = pr) != null)
pr.parent = s;
}
p.left = null;
if ((p.right = sr) != null)
sr.parent = p;
if ((s.left = pl) != null)
pl.parent = s;
if ((s.parent = pp) == null)
r = s;
else if (p == pp.left)
pp.left = s;
else
pp.right = s;
if (sr != null)
replacement = sr;
else
replacement = p;
}
else if (pl != null)
replacement = pl;
else if (pr != null)
replacement = pr;
else
replacement = p;
if (replacement != p) {
TreeNode<K,V> pp = replacement.parent = p.parent;
if (pp == null)
r = replacement;
else if (p == pp.left)
pp.left = replacement;
else
pp.right = replacement;
p.left = p.right = p.parent = null;
}
root = (p.red) ? r : balanceDeletion(r, replacement);
if (p == replacement) { // detach pointers
TreeNode<K,V> pp;
if ((pp = p.parent) != null) {
if (p == pp.left)
pp.left = null;
else if (p == pp.right)
pp.right = null;
p.parent = null;
}
}
} finally {
unlockRoot();
}
assert checkInvariants(root);
return false;
}
/* ------------------------------------------------------------ */
// Red-black tree methods, all adapted from CLR
// 左旋
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) {
if ((rl = p.right = r.left) != null)
rl.parent = p;
if ((pp = r.parent = p.parent) == null)
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
// 右旋
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
// 自平衡,参见红黑树的自平衡
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
TreeNode<K,V> x) {
x.red = true;
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {
if ((xppr = xpp.right) != null && xppr.red) {
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.right) {
root = rotateLeft(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateRight(root, xpp);
}
}
}
}
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
// 自平衡,参见红黑树的自平衡
static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
TreeNode<K,V> x) {
for (TreeNode<K,V> xp, xpl, xpr;;) {
if (x == null || x == root)
return root;
else if ((xp = x.parent) == null) {
x.red = false;
return x;
}
else if (x.red) {
x.red = false;
return root;
}
else if ((xpl = xp.left) == x) {
if ((xpr = xp.right) != null && xpr.red) {
xpr.red = false;
xp.red = true;
root = rotateLeft(root, xp);
xpr = (xp = x.parent) == null ? null : xp.right;
}
if (xpr == null)
x = xp;
else {
TreeNode<K,V> sl = xpr.left, sr = xpr.right;
if ((sr == null || !sr.red) &&
(sl == null || !sl.red)) {
xpr.red = true;
x = xp;
}
else {
if (sr == null || !sr.red) {
if (sl != null)
sl.red = false;
xpr.red = true;
root = rotateRight(root, xpr);
xpr = (xp = x.parent) == null ?
null : xp.right;
}
if (xpr != null) {
xpr.red = (xp == null) ? false : xp.red;
if ((sr = xpr.right) != null)
sr.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateLeft(root, xp);
}
x = root;
}
}
}
else { // symmetric
if (xpl != null && xpl.red) {
xpl.red = false;
xp.red = true;
root = rotateRight(root, xp);
xpl = (xp = x.parent) == null ? null : xp.left;
}
if (xpl == null)
x = xp;
else {
TreeNode<K,V> sl = xpl.left, sr = xpl.right;
if ((sl == null || !sl.red) &&
(sr == null || !sr.red)) {
xpl.red = true;
x = xp;
}
else {
if (sl == null || !sl.red) {
if (sr != null)
sr.red = false;
xpl.red = true;
root = rotateLeft(root, xpl);
xpl = (xp = x.parent) == null ?
null : xp.left;
}
if (xpl != null) {
xpl.red = (xp == null) ? false : xp.red;
if ((sl = xpl.left) != null)
sl.red = false;
}
if (xp != null) {
xp.red = false;
root = rotateRight(root, xp);
}
x = root;
}
}
}
}
}
/**
* Recursive invariant check
*/
static <K,V> boolean checkInvariants(TreeNode<K,V> t) {
TreeNode<K,V> tp = t.parent, tl = t.left, tr = t.right,
tb = t.prev, tn = (TreeNode<K,V>)t.next;
if (tb != null && tb.next != t)
return false;
if (tn != null && tn.prev != t)
return false;
if (tp != null && t != tp.left && t != tp.right)
return false;
if (tl != null && (tl.parent != t || tl.hash > t.hash))
return false;
if (tr != null && (tr.parent != t || tr.hash < t.hash))
return false;
if (t.red && tl != null && tl.red && tr != null && tr.red)
return false;
if (tl != null && !checkInvariants(tl))
return false;
if (tr != null && !checkInvariants(tr))
return false;
return true;
}
private static final sun.misc.Unsafe U;
private static final long LOCKSTATE;
static {
try {
U = sun.misc.Unsafe.getUnsafe();
Class<?> k = TreeBin.class;
LOCKSTATE = U.objectFieldOffset
(k.getDeclaredField("lockState"));
} catch (Exception e) {
throw new Error(e);
}
}
}
}
- 在多线程操作TreeBin节点的时候,会对读加锁,对写也加锁。但是写是独占锁。
- 写是CAS写,先写TreeBin里面的链表,然后再写红黑树,所以在读元素的时候,会进行加锁的判断,如果是写锁,就读取链表,否则就读取红黑树,我猜测这样的设计是考虑到红黑树的自平衡比较耗时,保证了读的高效性。
- 但是要耗费更多的空间。
CHM#treeifyBin方法分析
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable {
/**
* 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) {
// b 需要转化为 TreeBin的桶位
// n tab长度
// sc emm 没用到
Node<K,V> b; int n, sc;
if (tab != null) {
// 如果 tab长度 小于 64 尝试扩容解决问题
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) {
// hd 头
// tl 尾
TreeNode<K,V> hd = null, tl = null;
// 遍历链表,转换为TreeNode双向链表
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;
}
// 设置值
setTabAt(tab, index, new TreeBin<K,V>(hd));
}
}
}
}
}
}
总结
- ConcurrentHashMap设计的很牛皮,理解起来相对比较困难,但是有几个地方不是很理解,还需要处理一下。也就是说,在写的时候,读线程发现正在扩容,那么读线程就要去帮助进行扩容。