类结构图
Node介绍
static class Node<K,V> implements Map.Entry<K,V> {
//key的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; }
//重写hashcode();key的hashcode异或val的hashcode
public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
public final String toString(){ return key + "=" + val; }
//不支持setValue操作
public final V setValue(V value) {
throw new UnsupportedOperationException();
}
//重写equals
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)));
}
/**
* 这个方法用来支持map.get()方法。大概逻辑就是遍历table寻找node
*/
Node<K,V> find(int h, Object k) {
//当前对象
Node<K,V> e = this;
if (k != null) {
//遍历数组,根据key查找
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;
}
}
ForwardingNode介绍
//该类仅仅用在map扩容
static final class ForwardingNode<K,V> extends Node<K,V> {
//nextTable表示扩容之后的数组。当一个线程访问到ForwardingNode对象,就知道当前正在进行扩容操作,当前这个线程会帮助扩容
final Node<K,V>[] nextTable;
ForwardingNode(Node<K,V>[] tab) {
super(MOVED, null, null, null);
this.nextTable = tab;
}
Node<K,V> find(int h, Object k) {
//遍历新的数组
outer: for (Node<K,V>[] tab = nextTable;;) {
Node<K,V> e; int n;
//检验k,tabl数组是否为空,如果为空直接返回null
if (k == null || tab == null || (n = tab.length) == 0 || (e = tabAt(tab, (n - 1) & h)) == null)
return null;
for (;;) {
int eh; K ek;
//判断bin上的第一个元素是否等于k,等于直接返回
if ((eh = e.hash) == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
//eh<0并且是ForwardingNode 那么继续循环
if (eh < 0) {
if (e instanceof ForwardingNode) {
tab = ((ForwardingNode<K,V>)e).nextTable;
continue outer;
}
else
//否则调用父类Node的find返回
return e.find(h, k);
}
if ((e = e.next) == null)
return null;
}
}
}
}
成员变量
/**
*最大容量:2^30=1073741824
*/
private static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认容量 16
*/
private static final int DEFAULT_CAPACITY = 16;
/**
* 没有用到,注释解释的用来兼容啥玩意的。看代码只在序列化反序列化用到啦
*/
private static final int DEFAULT_CONCURRENCY_LEVEL = 16;
/**
* 加载因子
*/
private static final float LOAD_FACTOR = 0.75f;
/**
* 转为红黑树判断条件之一 bin数量大于8
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 由树转换成链表的阈值UNTREEIFY_THRESHOLD当执行resize操作时
* 当桶中bin的数量少于UNTREEIFY_THRESHOLD时使用链表来代替树。默认值是6
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 如果bin中的数量大于TREEIFY_THRESHOLD,但是capacity小于MIN_TREEIFY_CAPACITY,依然使用链表存储。
* 此时会进行resize操作,如果capacity大于MIN_TREEIFY_CAPACITY进行树化
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 扩容线程每次最少要迁移16个hash桶
*/
private static final int MIN_TRANSFER_STRIDE = 16;
/**
* The number of bits used for generation stamp in sizeCtl.
* Must be at least 6 for 32bit arrays.
*/
private static int RESIZE_STAMP_BITS = 16;
/**
* 帮助扩容线程最大值65535
*/
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
/**
* The bit shift for recording size stamp in sizeCtl.
*/
private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
//当前位置的Node是一个ForwardingNode节点
static final int MOVED = -1;
//当前位置的Node为一个TreeBin节点
static final int TREEBIN = -2;
//暂存态,即这个节点没有真正初始化完毕
static final int RESERVED = -3;
static final int HASH_BITS = 0x7fffffff;
/** 可用处理器(cpu)数量 */
static final int NCPU=Runtime.getRuntime().availableProcessors();
/**
* 桶数组,用来存储Node元素的。默认为null,只在第一次put操作的进行初始化,该数组的长度永远为2的n次方。
*/
transient volatile Node<K,V>[] table;
/**
* 默认为null,当不为null,表示当前正在进行扩容操作,这个数组就是扩容之后的数组,长度为原数组的两倍。
*/
private transient volatile Node<K,V>[] nextTable;
/**
* map中元素个数,由于是多线程操作,baseCount记录的不准确,所以要结合counterCells 来使用保证记录的正确性。map的元素个数 = baseCount + 所有的cell的value值。
*/
private transient volatile long baseCount;
/**
* 表初始化和扩容的控制位。
* -1表示当前table数组正在被初始化;
* -N表示有N-1个线程在进行扩容操作;
* 0(默认值)表示当前table还未使用;此时table为null;
* 正整数时,表示table的容量,默认是table大小的0.75倍,(n - (n>>>2))的方式来计算0.75
*/
private transient volatile int sizeCtl;
/**
* 用来拆分table的,在扩容的时候
*/
private transient volatile int transferIndex;
/**
* 用来实现cellsBusy锁的,0无锁,1锁z
*/
private transient volatile int cellsBusy;
/**
* @sun.misc.Contended 用来避免伪共享 counterCells用来记录出现并发的次数
*/
private transient volatile CounterCell[] counterCells;
// views
private transient KeySetView<K,V> keySet;
private transient ValuesView<K,V> values;
private transient EntrySetView<K,V> entrySet;
构造方法
//initialCapacity 初始容量
//loadFactor加载因子
//concurrencyLevel预估并发线程
public ConcurrentHashMap(int initialCapacity,float loadFactor, int concurrencyLevel) {
//校验参数
if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
throw new IllegalArgumentException();
//如果容量小于预估并发线程数。则使用concurrencyLevel
if (initialCapacity < concurrencyLevel)
initialCapacity = concurrencyLevel;
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
//tableSizeFor((int)size) 找到大于等于size的最小2的幂;得到数组容量
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
//传入一个map
public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
this.sizeCtl = DEFAULT_CAPACITY;
putAll(m);
}
//根据初始容量初始化ConcurrentHashMap
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;
}
操作table的方法
//原子操作,返回table指定位置的元素
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
//cas操作,在指定位置赋值
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, 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);
}
initTable()解析
//初始化table
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
//table等于null或者长度为0则初始化table
while ((tab = table) == null || tab.length == 0) {
//sizeCtl<0说明当前数组正在初始化。则当前让出cpu
if ((sc = sizeCtl) < 0)
Thread.yield();
//否则通过cas把SIZECTL修改成-1,表示当前正在初始化
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if ((tab = table) == null || tab.length == 0) {
//判断初始化map的时候是否指定容量,没有使用DEFAULT_CAPACITY
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
//构造一个node数组指定长度
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
//根据node数组长度重新计算sizeCtl。其实就是n*0.75得到下次扩容的阈值
sc = n - (n >>> 2);
}
} finally {
//重新赋值sizeCtl
sizeCtl = sc;
}
break;
}
}
return tab;
}
put()解析
public V put(K key, V value) {
return putVal(key, value, false);
}
//onlyIfAbsent true不改变存在的值;false改变存在的值
final V putVal(K key, V value, boolean onlyIfAbsent) {
//检验key,value不能为空
if (key == null || value == null) throw new NullPointerException();
//计算hash值。高16位异或低16位与HASH_BITS
int hash = spread(key.hashCode());
int binCount = 0;
//遍历数组
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
//如果node数组为空,则初始化table
if (tab == null || (n = tab.length) == 0)
tab = initTable();
//返回(n - 1) & hash=index 位置的元素
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
//通过cas赋值。
if (casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null)))
//这里操作不需要锁,即使multi thread add 那么只会有一个执行成功。casTabAt是原子操作
break;
}
//f.hash == MOVED表示当前数组正在扩容。则进行帮助扩容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
//注意,这里针对数组的某一个桶加锁
synchronized (f) {
//校验f
if (tabAt(tab, i) == f) {
//fh >= 0得到的节点就是hash值相同的节点组成的链表的头节点
if (fh >= 0) {
binCount = 1;
//遍历数组
for (Node<K,V> e = f;; ++binCount) {
K ek;
//根据hash找到key,判断是否可以覆盖原来的值
//onlyIfAbsent=false覆盖
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) {
//根据onlyIfAbsent判断是否覆盖
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
//binCount >= TREEIFY_THRESHOLD说明要把链表转为红黑树
if (binCount >= TREEIFY_THRESHOLD)
//链表转树
treeifyBin(tab, i);
//老值不为空,返回原来的值
if (oldVal != null)
return oldVal;
break;
}
}
}
//map的容量加1,检查map是否需要扩容
addCount(1L, binCount);
return null;
}
//计算hash值
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
addCount()解析
//如果想要看懂这个方法,那么需要先去了解LongAddr实现的原理。
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
// counterCells!=null,或者通过cas修改baseCount失败则进入if
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
//执行到这里,说明counterCells=null并且cas修改失败(修改失败说明出现竞争)
CounterCell a; long v; int m;
//是否出现竞争,true没有出现竞争
boolean uncontended = true;
//如果as=null,或者数组随机一个node为null,或者cas修改CELLVALUE值失败
if (as == null || (m = as.length - 1) < 0 ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended = U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
//这个方法的原理跟longAccumulate()一模一样。不懂的朋友可以去看完LongAddr源码解析的文章
fullAddCount(x, uncontended);
return;
}
//如果check小于等于0不检查是否需要扩容
if (check <= 1)
return;
//获取map的大小
s = sumCount();
}
//检查是否要扩容
if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;
//根据map的容量s跟sizeCtl比较,判断是否要扩容
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;
//扩容线程数加1
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) //帮助扩容
transfer(tab, nt);
}
//当前线程是唯一的或是第一个发起扩容的线程 此时nextTable=null
//sizeCtl = (resizeStamp(n) << RESIZE_STAMP_SHIFT) + 2表示只有一个线程扩容
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs <<RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
helpTransfer()解析
//这个逻辑跟上面if(check>=0)差不多。帮助扩容
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
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;
}
transfer()解析
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
// 扩容线程每次最少要迁移16个hash桶
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE;
//第一次扩容的时候nextTab=null
if (nextTab == null) {
try {
@SuppressWarnings("unchecked")
//数组长度扩大2倍
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
transferIndex = n;
}
//获取新数组的长度
int nextn = nextTab.length;
//如果已经处理(迁移)就设置为fwd节点
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
//是否继续向前查找的标志位
boolean advance = true;
//扩容操作是否完成标识。完成之前重新扫描一边数组
boolean finishing = false;
// 自旋,i表示数组下标,bound表示当前线程可以处理的当前桶区间最小下标
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
while (advance) {
int nextIndex, nextBound;
//第一次不会进入这个if finishing=true说明扩容完成了
if (--i >= bound || finishing)
advance = false;
//transferIndex<=0桶已经处理完了,不需要别的线程在处理
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
//这里可以得到当前线程处理数组的最小区间
bound = nextBound;
//得到线程处理数组的最大区间
//那么这个线程处理的区间就是[bound,i]
i = nextIndex - 1;
advance = false;
}
}
//i<0数组遍历完成;i目前看到只等于n;i + n >= nextn扩容完成
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
if (finishing) {
//用于扩容table
nextTable = null;
//扩容以后的心table
table = nextTab;
//设置sizeCtl为扩容后的0.75
sizeCtl = (n << 1) - (n >>> 1);
return;
}
/**
第一个扩容的线程,执行transfer方法会设置 sizeCtl = (resizeStamp(n) << RESIZE_STAMP_SHIFT) + 2);
帮助扩容的线程,执行transfer会设置 sizeCtl = sizeCtl+1退出transfer的方法的线程会设置 sizeCtl = sizeCtl-1;
最后一个线程退出sc == (resizeStamp(n) <<RESIZE_STAMP_SHIFT) + 2),即 (sc - 2) == resizeStamp(n) << RESIZE_STAMP_SHIFT
*/
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
//不相等,说明不到最后一个线程,直接退出transfer方法
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
//最后一个线程,扩容完成
finishing = advance = true;
//重新检查
i = n;
}
}
//获取指定位置元素
else if ((f = tabAt(tab, i)) == null)
//指定位置插入fwd节点
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
//已经处理
advance = true;
else {
//迁移数据
synchronized (f) {
//再次校验f
if (tabAt(tab, i) == f) {
//ln=lowNode 低位 hn=hignNode 高位
Node<K,V> ln, hn;
//fh>=0说明是链表。这里涉及到链表的反转。可能反转一部分,可能全反转。ln等于null那么ln链表全反转
if (fh >= 0) {
//把链表数据分为2类,0和1
int runBit = fh & n;
//lastRun记录的是最后一个hash值变化的Node。
Node<K,V> lastRun = f;
//遍历当前桶位置的链表,得到最后一个hash值变化的Node
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 {
//迁移位置old+n
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;
}
}
}
}
}
}
get()方法解析
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
//获取key的hash值
int h = spread(key.hashCode());
//table不等于null,计算index获取元素不等于null
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
//判断第一个节点是否相等
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
//小于0说明在扩容。需要调用forwoard的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;
}
阅读更多文章