ConcurrentHashMap 源码分析05之函数篇 put 详解

前面巨多属性与内部类,看得我云里雾里,结合函数的执行过程,可能就比较容易懂了吧。

1. put(K key, V value)

  • 指定 key,value,若存在,则替换value值并返回旧值,若不存在,则新建节点值并返回null。
  • 添加元素时,底层调用 putVal() 方法执行真正的添加,使用for循环重新获取tab值,为什么要这么做?继续往下看
    • 添加元素时,肯定是需要初始化数组initTable(),然后再次获取 tab 进行操作;
    • 初始化数组后,首元素为空,直接赋值即可,break退出;
    • 当元素个数越来越多,必须扩容,扩容回来后,获取新数组 tab 进行操作;
    • 桶位不为空时,需要遍历元素进行末尾添加,使用 synchronized 加锁,当然需要区分链表节点添加还是树节点添加
public V put(K key, V value) {
    return putVal(key, value, false);
}
/* onlyIfAbsent: 若为true,表示旧值不给替换 */
final V putVal(K key, V value, boolean onlyIfAbsent) {
	/* ConcurrentHashMap 的 key,value 都不能为 null */
    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;
        /* 初始化 tab,默认为 null */
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
        /* 获取桶位首元素 */    
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
        	/* CAS设置桶位首元素,成功则退出 */
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;                   
        }
        /* 当前桶位首元素正在移动,MOVED = -1 */
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f); // 帮助扩容
        else {
            V oldVal = null;
            /* 锁住首节点 */
            synchronized (f) {
            	/* 判断 f 是否被更改过 */
                if (tabAt(tab, i) == f) {
                	/* 链表节点 */
                    if (fh >= 0) {
                        binCount = 1;
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            /* e.key 与 key 相等 */
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                oldVal = e.val;
                                if (!onlyIfAbsent)
                                    e.val = value;
                                break;
                            }
                            /* e.next == null 表示已遍历至链表尾节点 */
                            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;
                        /* 树节点添加,可回看01篇 */
                        if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                       value)) != null) {
                            oldVal = p.val;
                            if (!onlyIfAbsent)
                                p.val = value;
                        }
                    }
                }
            }
            /* binCount 不为 0 表示要么添加了链表节点,要么添加了树节点 */
            if (binCount != 0) {
            	/* 链表节点个数 >= 树化默认值 8 */
                if (binCount >= TREEIFY_THRESHOLD)
                    treeifyBin(tab, i);
                /* 节点存在,返回旧值 */    
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    /* 添加了元素,count+1即 size + 1 */
    addCount(1L, binCount);
    return null;
}

2. spread(int h)

  • 根据 key 的hash值计算新的hash值
static final int spread(int h) {
    return(h ^ (h >>> 16)) & HASH_BITS;
}

3. initTable

  • 初始化数组,过程比较简单,若 tab 还未被初始化,CAS争抢初始化权限
  • 注意 Thread.yield(),这个是释放CPU资源后重新争抢,若初始化的线程迟迟不能完成,而释放的线程A又总是抢到权限,可能造成100% CPU的情况,不过基本上不会出现
private final Node<K,V>[] initTable() {
    Node<K,V>[] tab; int sc;
    /* tab 为空 || tab 数组长度为 0 */
    while ((tab = table) == null || tab.length == 0) {
    	/* sizeCtl 初始化为0 */
        if ((sc = sizeCtl) < 0)
            Thread.yield(); // 释放CPU,然后去争抢资源
        /* CAS争抢资源 */    
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
            try {
            	/* 抢到资源后判断 tab 为空 || tab 数组长度为 0 */
                if ((tab = table) == null || tab.length == 0) {
                	/* 默认初始容量DEFAULT_CAPACITY = 16 */
                    int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                    @SuppressWarnings("unchecked")
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    table = tab = nt;
                    sc = n - (n >>> 2);  // 相当于 3*n /4 = 0.75n
                }
            } finally {
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

4. addCount(long x, int check)

  • ConcurrentHashMap 使用 baseCount 来记录 size,但在多线程的添加中,若使用CAS去设置 baseCount 的值,性能难免受到局限。所以采用 CounterCell 的方式记录,获取总数时 s = baseCount + for(CounterCell)
/* x: 添加的个数, check: 检测是否需要扩容,树节点为2,删除为-1,链表为当前链个数 */
private final void addCount(long x, int check) {
    CounterCell[] as; long b, s;
    /* counterCells 不为空 || CAS 设置 baseCount 值为false,直接使用 counterCells 进行 count+x */
    if ((as = counterCells) != null ||
        !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
        CounterCell a; long v; int m;
        boolean uncontended = true;
        /* ThreadLocalRandom.getProbe() 根据线程生成一个随机数 num */
        /* as 为null || as.length < 1 || 
          (as[num & m]即CounterCell 桶位为null && CAS设置 value值不成功),
         任意一项为true, 执行fullAddCount()  */
        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;
        }
        /* 长度<= 1,肯定不需要扩容,直接返回 */
        if (check <= 1)
            return;
        s = sumCount(); // 计算当前 size元素个数
    }
    /* 扩容操作,若 check < 0(删除时为-1) 不需要进行此操作 */
    if (check >= 0) {
        Node<K,V>[] tab, nt; int n, sc;
        /* sizeCtl 可以理解为阈值,元素个数s >= 阈值 && (tab数组不为空 && tab数组长度 < 最大容量) */
        while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
               (n = tab.length) < MAXIMUM_CAPACITY) {
            int rs = resizeStamp(n); // 扩容标志
            /* sc 被设置成特殊值, */
            if (sc < 0) {
            	/* 不需要帮助扩容的情况:
            	 * 1. 扩容过程中sc为巨大负数,否则不在扩容过程中
            	 * 2. sc == rs + 1 发生了新的扩容,仔细回看 rs 的生成过程
            	 * 3. sc == rs + MAX_RESIZERS 到达最大扩容数
            	 * 4. nextTable 为null,没的帮忙扩容
            	 * 5. transferIndex <= 0 扩容桶位下标为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);
            }
            /* CAS设置 sc 的值,(rs << RESIZE_STAMP_SHIFT) + 2) 当做是一个特殊的值(巨大负数)即可 */
            else if (U.compareAndSwapInt(this, SIZECTL, sc,
                                         (rs << RESIZE_STAMP_SHIFT) + 2))
                transfer(tab, null); // 真正的扩容函数
            s = sumCount(); // 获取当前元素个数,多线程相加结果
        }
    }
}

5. fullAddCount(long x, boolean wasUncontended)

  • addCount 只是对count进行计数相加,但 fullAddCount 包含 CounterCell 的初始化,扩容等
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;
        /* 当前CounterCell数组不为空 && CounterCell数组长度 > 0 */
        if ((as = counterCells) != null && (n = as.length) > 0) {
        	/* CounterCell对应的桶位为空 */
            if ((a = as[(n - 1) & h]) == null) {
                if (cellsBusy == 0) { // 是否有人正在操作 CounterCell
                	/* 初始化 CounterCell 的值 */
                    CounterCell r = new CounterCell(x);
                    /* 是否有人正在操作 CounterCell && CAS设置 CELLSBUSY */
                    if (cellsBusy == 0 &&
                        U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                        boolean created = false;
                        /* 初始化 CounterCell[j] 位置的值 */
                        try {  
                            CounterCell[] 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; // 释放对 CounterCells 的控制
                        }
                        /* 若发生了初始化桶位的值,则退出,否则继续循环设置值 */
                        if (created)
                            break;
                        continue;
                    }
                }
                collide = false;
            }
            /* 竞争标识,默认为false */
            else if (!wasUncontended) 
                wasUncontended = true; 
            /* CAS 设置当前CELLVALUE */    
            else if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))
                break;
            /* counterCells 发生了改变 || 长度n >= 当前服务器的CPU数 */    
            else if (counterCells != as || n >= NCPU)
                collide = false;            // At max size or stale
            else if (!collide)  // 改变标识用
                collide = true;
            /* cellsBusy == 0 && CAS 设置 cellsBusy */    
            else if (cellsBusy == 0 &&
                     U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
                try {
                	/* 扩容 CounterCell 数组 */
                    if (counterCells == as) {
                        CounterCell[] rs = new CounterCell[n << 1];
                        for (int i = 0; i < n; ++i)
                            rs[i] = as[i];
                        counterCells = rs;
                    }
                } finally {
                    cellsBusy = 0; // 释放 CounterCell 的控制
                }
                collide = false;
                continue;                   // Retry with expanded table
            }
            /* 重新生成 hash 值 */
            h = ThreadLocalRandom.advanceProbe(h);
        }
        /* 当前CounterCell数组为空 && cellsBusy 为0代表没有线程对进行操作
        && counterCells == as 没有线程进行更改 && CAS 设置 CELLSBUSY 值 */
        else if (cellsBusy == 0 && counterCells == as &&
                 U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {
            boolean init = false;
            try {      
            	/* 初始化 CounterCell,长度为2 */                     
                if (counterCells == as) {
                    CounterCell[] rs = new CounterCell[2];
                    rs[h & 1] = new CounterCell(x);
                    counterCells = rs;
                    init = true;
                }
            } finally {
                cellsBusy = 0;
            }
            if (init)
                break;
        }
        /* 无法进行对 CounterCell 操作,尝试设置 BASECOUNT */
        else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))
            break;                          // Fall back on using base
    }
}

6. resizeStamp

/* 返回一个扩容标识,返回的数的第16位肯定为1,这为sc设置为巨大的负数提供了条件 */
static final int resizeStamp(int n) {
    return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));
}
/* 判断前面有多少个 0 */
public static int numberOfLeadingZeros(int i) {
    //HD, Figure 5-6
    if (i == 0)
        return 32;
    int n = 1;
    if (i >>> 16 == 0) { n += 16; i <<= 16; }
    if (i >>> 24 == 0) { n +=  8; i <<=  8; }
    if (i >>> 28 == 0) { n +=  4; i <<=  4; }
    if (i >>> 30 == 0) { n +=  2; i <<=  2; }
    n -= i >>> 31;
    return n;
}

7. putAll(Map<? extends K, ? extends V> m)

  • 添加 集合m 的所有元素,循环调用 putVal()
public void putAll(Map<? extends K, ? extends V> m) {
    tryPresize(m.size());
    for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
        putVal(e.getKey(), e.getValue(), false);
}

/* 调整数组的的大小 */
private final void tryPresize(int size) {
    int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
        tableSizeFor(size + (size >>> 1) + 1);
    int sc;
    while ((sc = sizeCtl) >= 0) {
        Node<K,V>[] tab = table; int n;
        /* tab 还未被初始化 */
        if (tab == null || (n = tab.length) == 0) {
        	/* 判断 应扩容的值c 与 临界值 sc 的大小,因为 sc 可能为构造函数指定的容量 */
            n = (sc > c) ? sc : c;
            /* CAS 抢夺 SIZECTL 设置权限 */
            if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {
                	/* tab 还未被其他线程更改 */
                    if (table == tab) {
                    	/* 初始化 tab */
                        @SuppressWarnings("unchecked")
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = nt;
                        sc = n - (n >>> 2);
                    }
                } finally {
                    sizeCtl = sc;
                }
            }
        }
        /* 容量 <= 临界值 || 数组长度n >= 最大容量,无需扩容 */
        else if (c <= sc || n >= MAXIMUM_CAPACITY)
            break;
        /* tab 没有被修改过,进行扩容 */    
        else if (tab == table) {
            int rs = resizeStamp(n);
            if (sc < 0) {
                Node<K,V>[] nt;
                /* 不需要帮助扩容的情况:
            	 * 1. 扩容过程中sc为巨大负数,否则不在扩容过程中
            	 * 2. sc == rs + 1 发生了新的扩容,仔细回看 rs 的生成过程
            	 * 3. sc == rs + MAX_RESIZERS 到达最大扩容数
            	 * 4. nextTable 为null,没的帮忙扩容
            	 * 5. transferIndex <= 0 扩容桶位下标为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); // 执行扩容的线程
        }
    }
}

7. transfer

  • 扩容函数
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
    int n = tab.length, stride;
    /* 计算步长,最小为16 */
    if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
        stride = MIN_TRANSFER_STRIDE;
    /* 只有一个线程可以初始化 nextTab,其余的是帮助扩容的线程 */    
    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;
    }
    /* 获取新数组的长度,生成一个 fwd 节点 */
    int nextn = nextTab.length;
    ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
    /* advance 是否可以前进,finishing 是否完成扩容 */
    boolean advance = true;
    boolean finishing = false;
    for (int i = 0, bound = 0;;) {
        Node<K,V> f; int fh;
        while (advance) {
            int nextIndex, nextBound;
            /* 当前线程负责的扩容模块完成 || finishing全部扩容完成 */
            if (--i >= bound || finishing)
                advance = false;
            /* transferIndex <= 0 即所有扩容任务分配完成 */    
            else if ((nextIndex = transferIndex) <= 0) {
                i = -1;
                advance = false;
            }
            /* CAS 设置nextIndex,其实就是为当前线程分配扩容任务 */
            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;
            /* 扩容完成,正式设置table = nextTab */
            if (finishing) {
                nextTable = null;
                table = nextTab;
                sizeCtl = (n << 1) - (n >>> 1); // 其实就是 0.75n
                return;
            }
            /* 尝试CAS设置 sc - 1 */
            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
            }
        }
        /* 当前桶位没有元素,设置为 fwd */
        else if ((f = tabAt(tab, i)) == null)
            advance = casTabAt(tab, i, null, fwd);
        /* hash值为MOVED,正在进行移除 */    
        else if ((fh = f.hash) == MOVED)
            advance = true;
        else {
        	/* 有数据的移除,高低链操作,首节点加锁 */
            synchronized (f) {
            	/* 验证首结点有没有被更改 */
                if (tabAt(tab, i) == f) {
                    Node<K,V> ln, hn;
                    /* 链表节点 */
                    if (fh >= 0) {
                    	/* 利用 hash & n == 0 判断出高低位(低位为0,高位为1)
                    	lastRun 判断出最后连续(高位 or 低位)的节点 */
                        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;
                            }
                        }
                        /* 判断 lastRun 是高位节点还是低位节点 */
                        if (runBit == 0) {
                            ln = lastRun;
                            hn = null;
                        }
                        else {
                            hn = lastRun;
                            ln = null;
                        }
                        /* 只需遍历至lastRun,因为后面的节点确定是同一位置,反序next 接上节点 */
                        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);
                        }
                        /* 设置新数组高低位的值,旧数组的低位值为 fwd */
                        setTabAt(nextTab, i, ln);
                        setTabAt(nextTab, i + n, hn);
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                    /* 树节点 */
                    else if (f instanceof TreeBin) {
                    	/* 定位高低位节点,默认为null */
                        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;
                            }
                        }
                        /* 判断高低链个数 <= 链化个数,是否需要链化;lc(hc) == 0 表示移动至同一桶位  */
                        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;
                        /* 设置新数组高低位的值,旧数组的低位值为 fwd */    
                        setTabAt(nextTab, i, ln);
                        setTabAt(nextTab, i + n, hn);
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                }
            }
        }
    }
}

8. helpTransfer

  • 帮助扩容
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
    Node<K,V>[] nextTab; int sc;
    /* tab为null || f不属于 fwd || nextTab 为null,要么还未初始化,要么初始化完成,直接返回 table */
    if (tab != null && (f instanceof ForwardingNode) &&
        (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
        int rs = resizeStamp(tab.length); // 获取扩容标识
        /* 确认 nextTab 没被修改 && tab为扩容完成 && sc < 0 即正在扩容 */
        while (nextTab == nextTable && table == tab &&
               (sc = sizeCtl) < 0) {
            /* 不需要帮忙扩容的情况 */   
            if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
                sc == rs + MAX_RESIZERS || transferIndex <= 0)
                break;
            /* CAS设置 sc 成功 */    
            if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
                transfer(tab, nextTab); // 帮助扩容
                break;
            }
        }
        return nextTab;
    }
    return table;
}

9. 总结

  • put(key, value) 的大致流程:与 HashMap 类似,经历数组创建、扩容、桶位冲突等,区别是每个过程都会使用线程安全的方法执行(加锁、CAS)
  • ConcurrentHashMap 的元素个数使用 baseCount 属性、CounterCell 数组的value值相结合,共同记录size的大小,提高效率,与LongAdder 类似。
  • ConcurrentHashMap 数组的扩容可以多线程进行协助,使用步长的概念(默认为 MIN_TRANSFER_STRIDE = 16),transferIndex 记录未分配扩容的桶位长度。
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ConcurrentHashMapTest01 {
    public static void main(String[] args) throws Exception {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100, 0L, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>());
        ConcurrentHashMap<Integer, Integer> concurrentHashMap = new ConcurrentHashMap<>();
        Field table = concurrentHashMap.getClass().getDeclaredField("table");
        Field nextTable = concurrentHashMap.getClass().getDeclaredField("nextTable");
        Field baseCount = concurrentHashMap.getClass().getDeclaredField("baseCount");
        Field counterCells = concurrentHashMap.getClass().getDeclaredField("counterCells");
        Field transferIndex = concurrentHashMap.getClass().getDeclaredField("transferIndex");
        Field cellsBusy = concurrentHashMap.getClass().getDeclaredField("cellsBusy");
        table.setAccessible(true);
        nextTable.setAccessible(true);
        baseCount.setAccessible(true);
        counterCells.setAccessible(true);
        transferIndex.setAccessible(true);
        cellsBusy.setAccessible(true);

        for (int i = 1; i <= 100000; i++) {
            int finalI = i;
            threadPoolExecutor.execute(() -> {
                for (int j = 1; j <= 100; j++) {
                    concurrentHashMap.put(finalI * 1000 + j, j);
                };
            });

        }
        while (true) {
            System.out.println("table.length(): " + (table.get(concurrentHashMap) == null ? null : ((Object[]) table.get(concurrentHashMap)).length));
            System.out.println("nextTable.length(): " + (nextTable.get(concurrentHashMap) == null ? null : ((Object[]) nextTable.get(concurrentHashMap)).length));
            System.out.println("baseCount: " + baseCount.get(concurrentHashMap));
            Object[] objs = (Object[]) counterCells.get(concurrentHashMap);
            if (objs != null) {
                System.out.print("counterCells: ");
                for (Object obj : objs) {
                    if (obj != null) {
                        Field value = obj.getClass().getDeclaredField("value");
                        if (value != null) {
                            value.setAccessible(true);
                            Object o = value.get(obj);
                            System.out.print(o + "\t");
                        }
                    }
                }
                System.out.println();
            }
            System.out.println("transferIndex: " + transferIndex.get(concurrentHashMap));
            System.out.println("cellsBusy: " + cellsBusy.get(concurrentHashMap));
            Thread.sleep(100);
            System.out.println("==========================================");
        }
    }
}

  • 这里截图部分输出效果,cellsBusy 一直演示不出为1的情况,因为这里的线程hash冲突太少,放弃抵抗。
    在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值