ConcurrentHashMap's clear() may make size() always incorrent

Liu via Concurrency-interest <[email protected]> Sat, 18 Jul 2020 18:01:20 +0800 (GMT+08:00)
Newsgroups gmane.comp.java.jsr.166-concurrency
Message-ID <[email protected]>
hi concurrency-interest:
    In JDK8's ConcurrentHashMap, we would use size() or mappingCount() to get size of map.


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


    But sometimes, the sumCount() may return a negative number, and size() or mappingCount() function must ignore the negative number and return zero.


    The reason why sumCount() may return a negative number, is that when sumCount() invoked by clear() just traverse a CounterCell object to get its count, a later delete operation comes and decrease this CounterCell's value. Then addCount(delta, -1) invoked by clear() will add a smaller negative number which is incorrent.


    I know sumCount() return a negative number is acceptable, because sumCount() not need return a very accurate number. But this incorrectness will always maintain in baseCount and counterCells, if above case happens.


    BUT I am wonder why not to corrent this incorrectness, when sumCount() return a negative number? 


    When this incorrectness happen, sumCount() always return a number that less than the correct count number. For example, in a time, ConcurrentHashMap has three node currently, but size() could return zero.


    Perhaps correct way is to make baseCount and counterCells all zero.


--------------------------------------------------------------------------------
Regards
Liu | someone who are very interested in concurrency

_______________________________________________
Concurrency-interest mailing list
[email protected]
http://cs.oswego.edu/mailman/listinfo/concurrency-interest