put
final V putVal(K key, V value, boolean onlyIfAbsent) {
//key和value都不能为空
if (key == null || value == null) throw new NullPointerException();
//确保key的hash在整数最大范围之内。
int hash = spread(key.hashCode());
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();
//n是table的大小,即node数组的大小,默认16,该方法表示获取tab数组的下标 i 处的节点并赋值给f,默认在0--15之间。
//如果f为空,说明该索引处还没有put过值,进行cas操作。
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
//将 k v 组合成一个node节点,节点中包含hash,key,value,next(null)属性。
if (casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null)))
//如果put成功,则break结束循环
break; // no lock when adding to empty bin
}
//在上一步的else if中 f 不为null时,则判断f的hash值是否为MOVED,即-1,如果为-1,表示正在扩容
else if ((fh = f.hash) == MOVED)
//协助数据迁移
tab = helpTransfer(tab, f);
else {
//开始put操作。
V oldVal = null;
//锁住节点f。f表示索引i处的第一个节点。即头节点。
synchronized (f) {
//由于并发问题,再次判断索引i处的节点是否为f节点。此时有可能已经不是f节点了,已经有其他线程提前插入了值。
if (tabAt(tab, i) == f) {
//如果fh大于0,表示可以正常put。如果小于0,表示正在扩容,正在做数据迁移工作
if (fh >= 0) {
//记录链的长度
binCount = 1;
//开始从f节点,即头节点遍历这条链。
for (Node<K,V> e = f;; ++binCount) {
K ek;
//判断要插入的key是否已经存在,如果存在表示插入了相同的key,break。
if (e.hash == hash && ((ek = e.key) == key ||(ek != null && key.equals(ek)))) {
oldVal = e.val;
//是否覆盖原来的值,onlyIfAbsent 是自己配置的。
if (!onlyIfAbsent){
e.val = value;
}
break;
}
Node<K,V> pred = e;
//遍历到最后一个节点,将新插入的节点赋值给最后一个节点的next属性。即新插叙的节点放到了链表尾部。
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
//fh.hash > 0 链转书操作。 fh小于0,但是不为-1,判断f是否为树节点。
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;
}
//将 k v 组合成一个node节点,节点中包含hash,key,value,next(null)属性。
1.casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null));
2.static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i, Node<K,V> c, Node<K,V> v) {
//表示先找到索引 i 的物理位置(寻址),如果在tab的该位置处为null,在赋值为node。
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
解释:在数组table的索引i处,如果为null,则设置为node(c)。
初始化
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
//table就是tab数组,默认值为16,用于存储node节点,节点中存放的就是我put的数据,如果为空或长度为0就会通过while循环初始化,直到初始化成功。
while ((tab = table) == null || tab.length == 0) {
//sizeCtl,可以理解为标识符,不同的值,代表不同的状态
//-1 表示正在初始化,其他负数表示正在扩容,绝对值表示扩容的线程数,ConcurrentHashMap是可以多个线程协作扩容的。
//正数表示扩容阈值,当addCount()时,如果发现达到了该阈值,就会执行扩容操作。
if ((sc = sizeCtl) < 0)
//如果sizeCtl小于0说明已经有线程在初始化了。
Thread.yield(); // lost initialization race; just spin
//否则,通过cas竞争初始化权力。可以理解为获取初始化的锁的权力。获取成功则进行初始化。否则进行下一次while循环
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
//如果tab为空,说明没有进行初始化。
if ((tab = table) == null || tab.length == 0) {
//获取table的大小。默认16
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
//创建数组。
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
//获取下一次扩容的阈值。取n的四分之三。
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
U.compareAndSwapInt(this, SIZECTL, sc, -1)
方法解释:this表示当前对象,SIZECTL表示sizeCtl在内存的偏移量,说白了就是sizeCtl在内存中的位置,sc就是sizeCtl的值。
就是说,先根据SIZECTL找到sizeCtl的位置,看看sizeCtl是不是-1,即如果sc == -1,则返回false,sc != -1 ,就把sizeCtl更改为-1,返回true表示获取到了初始化的权利。
helpTransfer(tab, f);
addCount分两步:一.数量加1. 二.校验是否扩容。看代码。
private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
//一:数量加1。由于并发,可能会有多个线程同时进行baseCount加1操作,但在同一时刻只能有一个成功的。
//其他失败了就会通过CounterCell进行加1.即chm的并发加1操作。妙哉。
//baseCount加1失败,执行if内部,通过as加1。加1成功(此时s=baseCount就是size大小),直接执行2.
if ((as = counterCells) != null ||!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
//as加1失败,执行if内的。并结束方法。
if (as == null || (m = as.length - 1) < 0 ||
//获取随机的as元素
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
//as加1。
!(uncontended = U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) { //as加1失败了
fullAddCount(x, uncontended);
return;
}
//as加1成功,check小于等1,return。
if (check <= 1)
return;
//as加1成功,记录as的总数。即size的大小
s = sumCount();
}
//执行2 //二:校验是否扩容
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);
//sc<0说明已经有线程在扩容了。
if (sc < 0) {
//当前线程无需加入扩容
if (
(sc >>> RESIZE_STAMP_SHIFT) != rs //表示比较高RESIZE_STAMP_BITS位生成戳和rs是否相等,相同
|| sc == rs + 1 //表示扩容结束
||sc == rs + MAX_RESIZERS //表示帮助线程线程已经达到最大值了
|| (nt = nextTable) == null //表示扩容已经结束
//表示所有的transfer任务都被领取完了,没有剩余的hash桶来给自己自己好这个线程来做transfer
||transferIndex <= 0)
break;
//当前线程加入扩容。
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);
}
//第一个线程开始扩容时执行。将sizeCtl设置为负数。
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
s = sumCount();
}
}
}
fullAddCount();
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已经初始化成功
if ((as = counterCells) != null && (n = as.length) > 0) {
//随机选择一个数组元素,如果为null,则进入if进行创建cell。
if ((a = as[(n - 1) & h]) == null) {
//判断此时,cc是否在扩容或初始化。
if (cellsBusy == 0) { // Try to attach new Cell
CounterCell r = new CounterCell(x); // Optimistic create
//如果没有扩容和初始化,使用cas锁
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 &&//cc不为空
(m = rs.length) > 0 &&//cc长度大于0
rs[j = (m - 1) & h] == null) {//随意选的一个元素为空
//rs[j]为null,指向r。
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);
}
//初始化counterCells,cellsBusy表示cc是否在初始化或扩容,值为0和1.
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;
//如果没有获取初始化的权利,则尝试baseCount加1,如果失败,则进行自旋。
else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
break; // Fall back on using base
}
}