chm的继承关系
常量分析
//数组的最大长度
private static final int MAXIMUM_CAPACITY = 1 << 30;
//默认数组长度
private static final int DEFAULT_CAPACITY = 16;
//用于toArray方法
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;
//每个线程转移的最小数组长度
private static final int MIN_TRANSFER_STRIDE = 16;
//用于生成stamp标记
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;
static final int MOVED = -1; // hash for forwarding nodes
static final int TREEBIN = -2; // hash for roots of trees
static final int RESERVED = -3; // hash for transient reservations
//最高位位0
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
//当前系统cpu数
static final int NCPU = Runtime.getRuntime().availableProcessors();
//volatile保证可见性,可用于cas操作
transient volatile Node<K,V>[] table;
private transient volatile Node<K,V>[] nextTable;
//基础计数器
private transient volatile long baseCount;
/*多种身份,数组为空时存储初始化长度,和HashMap的threshold类似
*正在初始化数组时,为-1
*当在迁移数据时用来表示工作线程数(负值)
*初始化完成以后保存扩容临界点
*/
private transient volatile int sizeCtl;
//
private transient volatile int transferIndex;
//初始化或扩容标记
private transient volatile int cellsBusy;
//计数器数组
private transient volatile CounterCell[] counterCells;
// views
private transient KeySetView<K,V> keySet;
private transient ValuesView<K,V> values;
private transient EntrySetView<K,V> entrySet;
构造方法
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;
}
chm的node节点
基本上和HashMap相同,不同点是不支持setValue,多了find方法,添加了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;
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;
}
}
put操作
public V put(K key, V value) {
return putVal(key, value, false);
}
final V putVal(K key, V value, boolean onlyIfAbsent) {
//chm的key和value都不可以为null,而HashMap则可以
if (key == null || value == null) throw new NullPointerException();
//和HashMap的hash操作类似,多了一个& HASH_BITS,消除负数,因为负数在chm里是有意义的
int hash = spread(key.hashCode());
//用来计算链表的长度,超过8转化为红黑树
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) {
//cas设置当前null节点为put的值,失败则自旋重试
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
//当前节点在做数据迁移时,去帮助迁移
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
//否则就是添加到链表或红黑树
else {
V oldVal = null;
//同步锁,锁定当前节点
synchronized (f) {
//二次确认节点值是否有变
if (tabAt(tab, i) == f) {
//红黑树根节点的hash为-2
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);
//oldVal != null说明没有增加节点,仅仅是替换数据
if (oldVal != null)
return oldVal;
break;
}
}
}
//计数器+1,并且进行扩容和数据迁移操作,binCount>0,说明增加了节点
addCount(1L, binCount);
return null;
}
初始化数组
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)
//此时已有线程初始化,让出时间片
Thread.yield(); // lost initialization race; just spin
//使用cas将sizeCtl变成-1,默认值是数组的初始化长度
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,下次扩容临界点
sc = n - (n >>> 2);
}
} finally {
//现在存储的是下次扩容的临界长度
sizeCtl = sc;
}
break;
}
}
return tab;
}
计数器+1,包括计数器扩容(fullAddCount),数组扩容&数据迁移(transfer)
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
//counterCells为null并且baseCount增加成功时会跳过,否则就会进入if
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
//当counterCells为null,并且竞争baseCount激烈
//当counterCells不为null,并且随机选择一个计数器是null或者不为null但增加失败
if (as == null || (m = as.length - 1) < 0 ||
//随机数选取CounterCell数组的一个
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
//进入这里表示线程的竞争很激烈,所以暂时不考虑数组扩容return
fullAddCount(x, uncontended);
return;
}
if (check <= 1)
return;
s = sumCount();
}
//check大于0表示map发生了结构性的改变,所以要考虑扩容
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
//sizeCtl存储的是数组扩容临界点(负值正在扩容),table不为空并且长度小于MAXIMUM_CAPACITY
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n);
/* static final int resizeStamp(int n) {
//n的二进制前面0的个数|1000 0000 0000 0000
return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}
*/
if (sc < 0) {
//sc >>> RESIZE_STAMP_SHIFT得到时间戳
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);
}
//高16位表示唯一标记,后16位表示扩容迁移线程个数,(-1表示初始化)
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
@sun.misc.Contended static final class CounterCell {
volatile long value;
CounterCell(long x) { value = x; }
}
计数器的扩容
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;
//当counterCells数组不为null时
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) {
//将新建的counterCells放在数组中为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;
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);
}
//将cellsBusy 设置为1并初始化
else if (cellsBusy == 0 && counterCells == as &&
U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
boolean init = false;
try { // Initialize table
if (counterCells == as) {
//默认是2的数组
CounterCell[] rs = new CounterCell[2];
rs[h & 1] = new CounterCell(x);
counterCells = rs;
init = true;
}
} finally {
cellsBusy = 0;
}
if (init)
break;
}
//当数组在被其他线程初始化,再次尝试使用base
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break;
// Fall back on using base
}
}
数据迁移
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
//数据迁移和cpu的数量有关,但最少不得低于16
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;
transferIndex = n;
}
int nextn = nextTab.length;
//nextTab目标数组
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
/*static final class ForwardingNode<K,V> extends Node<K,V> {
final Node<K,V>[] nextTable;
ForwardingNode(Node<K,V>[] tab) {
super(MOVED, null, null, null);
this.nextTable = tab;
}
....
}
*/
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减1,bound是下边界
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是数据迁移的上边界
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
}
}
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) {
//注意这里是和n&操作,得到的结果是迁移到新数组的位置(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;
}
}
}
}
}
}
解决Hash冲突方法
1.线性探索(开放寻址),当出现冲突时会将位置递归+1,直到找到不冲突位置
2.链式地址法(HashMap)
3.再hash(通过多个Hash函数运算)->布隆过滤器(bitMap)
4.建立公共溢出区