简介
线程安全的hash表,支持并发的更新和检索。功能和hashtable相同。此类在java.lang.util.concurrent并发包中。
类图
此类 继承AbstractMap所以HashMap有的功能这里都会提供,实现了ConcurrentMap将会是并发安全的hash表。
属性
这里属性总体和HashMap相同,如果想了解HashMap可以去看我的另一篇文章。
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; //最大可能的数组大小
private static final int DEFAULT_CONCURRENCY_LEVEL = 16; //默认并发级别
private static final float LOAD_FACTOR = 0.75f; //默认加载因子
static final int TREEIFY_THRESHOLD = 8; //树化阈值
static final int UNTREEIFY_THRESHOLD = 6; //反树化阈值
static final int MIN_TREEIFY_CAPACITY = 64; //树化前提 槽位不小于64
private static final int MIN_TRANSFER_STRIDE = 16;
private static int RESIZE_STAMP_BITS = 16;
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;//可以帮助调整大小的最大线程数
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
/*
* 节点特定的hash码
*/
static final int MOVED = -1; // forwarding节点的hash码 认为当前槽位正在被移动
static final int TREEBIN = -2; // 树的根节点hash码
static final int RESERVED = -3; // 预留的哈希码
static final int HASH_BITS = 0x7fffffff; // 普通节点哈希的可用位
static final int NCPU = Runtime.getRuntime().availableProcessors();//cpu的数量
transient volatile Node<K,V>[] table; //hash表、槽位
private transient volatile Node<K,V>[] nextTable;
private transient volatile long baseCount; //基本计数器值
// 表初始化和大小调整控制。如果为负,则表正在初始化或调整大小:-1表示初始化,
// 或者表示调整数量-(1 +活动的调整大小线程数)
// 当table为null时,保留创建时的初始表大小(16)
// 初始化后,保留下一次调整大小的阈值(16 - 16>>2 = 12),以在该值上调整表的大小。
private transient volatile int sizeCtl;
private transient volatile CounterCell[] counterCells; //表的计数格子,如果不是null就是2的n次方
内部类
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next; //单链表
}
static final class TreeNode<K,V> extends Node<K,V> {
TreeNode<K,V> parent; // 红黑树父节点
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // 删除后需要取消链接(这是个单链表 串联了所有树节点)
boolean red;
}
构造方法
// 使用默认的容量16 创建一个空的map
public ConcurrentHashMap() {
}
// 创建一个能够容纳指定容量的空map
public ConcurrentHashMap(int initialCapacity) {
if (initialCapacity < 0)
throw new IllegalArgumentException();
int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
this.sizeCtl = cap;
}
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)
initialCapacity = concurrencyLevel; //初始容量最少应为并发数
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
获取 get
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) {
if ((eh = e.hash) == h) { //如果第一个元素等于key 就返回
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0) //如果hash码小于0说明正在扩容或者是树
//因为这时能确定e为树节点 这里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;
}
}
return null;
}
移除 remove
public V remove(Object key) {
return replaceNode(key, null, null); //调用替换节点值方法
}
final V replaceNode(Object key, V value, Object cv) {
int hash = spread(key.hashCode()); //计算hash
for (Node<K,V>[] tab = table;;) { //自旋
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null) //如果表为空 或要删除的hash槽为空 返回null
break;
else if ((fh = f.hash) == MOVED) // 如果正在扩容迁移元素 当前线程帮助迁移
tab = helpTransfer(tab, f);
else { //没有特殊情况 就删除元素
V oldVal = null;
boolean validated = false;
synchronized (f) { // 分段锁 锁的一个槽位
if (tabAt(tab, i) == f) { //再次检查槽位第一个元素是否变化 变化了 自旋进入下次循环
if (fh >= 0) { //hash>=0 说明是链表
validated = true;
for (Node<K,V> e = f, pred = null;;) { //遍历链表查找元素
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) { //找到了要删除元素
V ev = e.val;
if (cv == null || cv == ev || //如果cv == null 或者
(ev != null && cv.equals(ev))) { //cv和oldValue相同 就去删除数据
oldVal = ev;
if (value != null) // 传入value不等于空 替换旧值
e.val = value;
//如果传入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;
TreeNode<K,V> r, p;
if ((r = t.root) != null &&
(p = r.findTreeNode(hash, key, null)) != null) { //遍历找到要删除的节点
V pv = p.val;
if (cv == null || cv == pv || //如果cv==null 或者cv和oldValue相等 删除
(pv != null && cv.equals(pv))) {
oldVal = pv;
if (value != null) //传入值 不等于空 替换旧值
p.val = value;
else if (t.removeTreeNode(p)) //传入值等于空 将节点删除
//removeTreeNode返回true 说明太小 应该取消树化 这句就直接设置桶位为链表
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
}
if (validated) { //处理过了
if (oldVal != null) { //如果找到了元素 返回旧值
//如果传入value为空 说明删除了元素 baseCount-1
//值得一提 看上面代码 value不为空 就会替换而不是删除
if (value == null)
addCount(-1L, -1);
return oldVal; //返回旧值
}
break;
}
}
}
return null;
}
添加 put
public V put(K key, V value) {
return putVal(key, value, false);
}
// onlyIfAbsent: false已经存在的元素 替换值
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode()); //调整hash码
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();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { //要插入桶位没有元素 将当前元素插入
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null))) //cas循环插入
break; // 添加到空槽时无锁
}
else if ((fh = f.hash) == MOVED) //如果要插入的槽位 正在迁移数据 当前线程帮忙迁移
tab = helpTransfer(tab, f);
else { // 没有特殊情况 就上锁 添加数据
V oldVal = null;
synchronized (f) { //锁住槽位的第一个元素 这是分段锁
if (tabAt(tab, i) == f) { //再次确认第一个元素没有变化 有变化进入下次循环
if (fh >= 0) { //hashcode>=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;
// 调用树的put方法插入元素 如果有返回值 就替换旧值 返回空说明已经插入
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) { //不等于0说明已经插入
if (binCount >= TREEIFY_THRESHOLD) //计数器大于树形化阈值
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
//成功插入元素后 将 元素个数baseCount+1
addCount(1L, binCount);
return null; //返回null
}
初始化桶
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) { //==0说明还未初始化
//sizeCtl < 0说明其他线程正在初始化或者扩容 当前线程晚来了一步
if ((sc = sizeCtl) < 0) //sizeCtl创建对象时 存的容量
Thread.yield(); // 其他线程抢先初始化了 让出cpu
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { //cas乐观锁
//如果设置-1失败 其他线程抢先了 进入下次循环
//下次循环 其他线程设置-1 进行初始化了 让出cpu
//下次循环 如果已经初始化完毕 table数组>0 依旧退出循环
//这是自旋锁 不成功就重试 直到不满足条件结束
try {
//再次验证table是否初始化
if ((tab = table) == null || tab.length == 0) {
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
//比如tab.length=16 那么sc=12 是下次扩容门槛
//写死了0.75倍 这是和HashMap不一样的地方
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc; //扩容后sizeCtl存的是下次要扩容的阈值
}
break;
}
}
return tab;
}
迁移元素
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
// nextTab为空 说明还没开始迁移 数组扩容一倍
if (nextTab == null) { // initiating
try {
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;
// 改变了i的值 作用不清楚
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;
}
}
// i 下标不合法 可能扩容完成了
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)) {
// 扩容完成后 两边相等 注意扩容时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 {
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);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}
添加后计数和判断扩容
// 添加过元素后调整baseCount大小
// x 调整数, check >= 0 检查是否需要扩容
private final void addCount(long x, int check) {
// CounterCell(以下简称as)是多线程并发操作时
// 抢不到在baseCount操作权限时 就将数据放入这里
// b 存储baseCount, s存储总计数
CounterCell[] as; long b, s;
// 如果as有数据,或者as没数据但是我更新basecount失败了
// 都说明此时并发大,那么当前线程不操作basecount了 直接放到CounterCell里面
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
// 下面是将要扩容的数据放到as
// 如果 as 等于空,as长度<=0,数据要插入的位置等于null,或者插入又失败了
if (as == null || (m = as.length - 1) < 0 ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
// 这次更新又失败了 说明并发依然很大 这个时候就去扩容 as 数组
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();
}
}
}
帮助扩容
// 如果正在调整大小 帮助进行扩容
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
// 如果数组不为空、并且是ForwardingNode而且它的下一个table不为空 说明当前桶已经迁移完毕
// 当前桶迁移完毕 去帮助其他桶迁移后 返回新数组
// 当前桶没迁移完毕 返回原数组
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;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}