Java系列-ConcurrentHashMap获取size

 baseCount和数组counterCells的每个元素的value之和

public class ConcurrentHashMap extends AbstractMap
    implements ConcurrentMap, Serializable {
    
    private transient volatile long baseCount;

    /**
     * Table of counter cells. When non-null, size is a power of 2.
     */
    private transient volatile CounterCell[] counterCells;

    public int size() {
        long n = sumCount();
        return ((n < 0L) ? 0 :
                (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
                (int)n);
    }

    final long sumCount() {
        CounterCell[] as = counterCells; 
        CounterCell a;
        long sum = baseCount;
        if (as != null) {
            //遍历counterCells
            for (int i = 0; i < as.length; ++i) {
                if ((a = as[i]) != null){
                    sum += a.value;
                }
            }
        }
        return sum;
    }
}

你可能感兴趣的:(Java,java)