put方法

//onlyIfAbsent 表示有重复的key是否覆盖,默认false表示会覆盖final V putVal(K key, V value, boolean onlyIfAbsent) {if (key == null || value == null) throw new NullPointerException();// 算出hash值 这个值一定是个正数 0x7fffffff;// f的二进制为:1111,7的二进制位0111 换算完之后最高位为0,所以最终值肯定为正数int hash = spread(key.hashCode());int binCount = 0;//这是一个死循环for (Node<K,V>[] tab = table;;) {// f 是链表头节点// fh 是链表头结点的 hash// i 是链表在 table 中的下标Node<K,V> f; int n, i, fh;if (tab == null || (n = tab.length) == 0){//第一个线程进来的第一次添加必然为truetab = initTable(); // 初始化 table 使用了 cas, 无需 synchronized 创建成功, 进入下一轮循环}// tabAt通过hash计算取出数组中的一个值,判断是否为空else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { //拿出key hash位置的value,如果为空则去添加//如果为空,就CAS创建一个新的node放在这个位置//多线程访问,第二个线程会CAS失败if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null)))break; // no lock when adding to empty bin}//如果此判断成立 说明此数组正在扩容,则去协助扩容 MOVED -1else if ((fh = f.hash) == MOVED){// 帮忙之后, 进入下一轮循环tab = helpTransfer(tab, f);}else {V oldVal = null;//锁住链表头节点synchronized (f) {if (tabAt(tab, i) == f) { //再次判断是因为 此位置的value有可能变为红黑树,锁就没用了if (fh >= 0) { //如果成立说明是链表binCount = 1;// 遍历链表for (Node<K,V> e = f;; ++binCount) {K ek;// 找到相同的 keyif (e.hash == hash &&((ek = e.key) == key ||(ek != null && key.equals(ek)))) { //如果key和value都一样oldVal = e.val;if (!onlyIfAbsent)//判断key相同的时候是否覆盖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;// putTreeVal 会看 key 是否已经在树中, 是, 则返回对应的 TreeNodeif ((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) //如果链表的长度>=8 则变为黑红树treeifyBin(tab, i); //但是如果数组的长度小于64,那么则不变为红黑树,则扩容if (oldVal != null)return oldVal;break;}}}//维护集合长度,判断是否达到扩容阈值,如果是,则扩容addCount(1L, binCount);return null;}
initTable() 初始化数组
-
compareAndSwapInt(Object var1, long var2, int var4, int var5);
o:目标Java变量引用。
- offset:目标Java变量中的目标属性的偏移地址。
- expected:目标Java变量中的目标属性的期望的当前值。
- x:目标Java变量中的目标属性的目标更新值。
步骤:
- 第一个线程进来将sizeCtl 改为-1,表示正在初始化中
- 第二个线程进来发现是-1,就yield放弃当前cpu时间。如果还是自己抢到cpu时间就继续空轮询再执行到这里判断是否是小于0。
- 第一个线程初始化完成后将sizeCtl改为扩容阈值
- 后续的线程继续进来,将sizeCtl赋值给sc
private final Node<K,V>[] initTable() {Node<K,V>[] tab; int sc;while ((tab = table) == null || tab.length == 0) {//sizeCtl小于0,代表 数组正在初始化或者正在扩容if ((sc = sizeCtl) < 0) {Thread.yield();}// 尝试将 sizeCtl 设置为 -1(表示初始化 table)else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {// 第一次进来SIZECTL= sc会成立, 将SIZECTL修改为-1,// -1表示正在初始化,返回true// 获得锁, 创建 table, 这时其它线程会在 while() 循环中 yield 直至 table 创建try {//双重判断是为了不重复创建 因为一个线程创建完后,会更改sizeCtl值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];//n为初始化的容量table = tab = nt;//可以换算为 n*0.75 n >>> 2表示 四分之一 ,此时sizeCtl=扩容阈值sc = n - (n >>> 2);}} finally {sizeCtl = sc;}break;}}return tab;}
addCount(1L, binCount)
- 维护size的计数
如果计数超过阈值,则触发扩容
// check 传进来的是binCount,表示当前位置链表的长度private final void addCount(long x, int check) {CounterCell[] as; long b, s;if ((as = counterCells) != null ||// BASECOUNT 用于单线程情况下的计数 x=1 传进来的!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {//多线程情况下添加basecount失败,就进入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);return;}if (check <= 1)return;//算出当前map中有多少元素,判断是否达到扩容阈值,如果是,则扩容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) { //第一个线程进来不可能小于0if ((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, //将SIZECTL 改为一个负数(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 initializationh = ThreadLocalRandom.getProbe();wasUncontended = true;}boolean collide = false; // True if last slot nonemptyfor (;;) {CounterCell[] as; CounterCell a; int n; long v;if ((as = counterCells) != null && (n = as.length) > 0) { //第一次进来肯定为false(一旦有线程进入,则为true,那么数组已经创建)if ((a = as[(n - 1) & h]) == null) { //随机取计数数组的一个位置,数组的这个位置还没有值则赋值if (cellsBusy == 0) { // Try to attach new CellCounterCell r = new CounterCell(x); // Optimistic createif (cellsBusy == 0 &&U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {boolean created = false;try { // Recheck under lockCounterCell[] 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 failwasUncontended = true; // Continue after rehashelse if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))//数组的这个位置已经有值,那么直接累加//多线程的累加操作 自旋 最终会在这里停止(小于CPU的核数)break;else if (counterCells != as || n >= NCPU)//当计数数组的长度n >=CPU核数时,避免计数数组扩容collide = false; // At max size or staleelse if (!collide)//只要n一直大于cpu核数,就会在这里死循环collide = true;else if (cellsBusy == 0 && U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { //数组扩容try {if (counterCells == as) {// Expand table unless staleCounterCell[] 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 tableif (counterCells == as) {CounterCell[] rs = new CounterCell[2];rs[h & 1] = new CounterCell(x); //x=1 传进来的counterCells = rs;init = true;}} finally {cellsBusy = 0;}if (init)break;}else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x)) //数组正在创建 对baseCount++break; // Fall back on using base}}
