ConcurrentHashMap的size计算(分析JDK1.7 1.8)

本文分析了JDK1.7和1.8中ConcurrentHashMap的size()方法实现,详细解释了如何通过CounterCell、counterCells[]和baseCount来无锁地计算size。在高并发情况下,1.8引入了更精确的mappingCount方法以避免竞争和提高准确性。
摘要由CSDN通过智能技术生成

JDK1.7 的 ConcurrentHashMap的size()

 /**
     * Returns the number of key-value mappings in this map.  If the
     * map contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of key-value mappings in this map
     */
    public int size() {
        // Try a few times to get accurate count. On failure due to
        // continuous async changes in table, resort to locking.
        final Segment<K,V>[] segments = this.segments; //map数据从segments中拿取
        int size; //统计的大小
        boolean overflow; // true if size overflows 32 bits //size过大的溢出情况
        long sum;         // sum of modCounts 统计modCounts的值
        long last = 0L;   // previous sum 最近的一个sum值
        int retries = -1; // first iteration isn't retry 重试的次数
        try {
            for (;;) { //一直循环统计size直至segment结构没有发生变化
                if (retries++ &#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值