Java Concurrency Interview

Concurrent collections question 75 of 180 mid

Is ConcurrentHashMap.size() reliable, and what should you use instead?

size() sums a base value plus an array of striped counter cells, the same design as LongAdder. With no concurrent writers the answer is exact; with writers it is a snapshot that was true at no single instant. mappingCount() is the same thing returning a long, and is the preferred method because a concurrent map can exceed Integer.MAX_VALUE entries.

isEmpty() has the same caveat, and using it to decide whether to shut something down is a classic race. If you need an authoritative count, count it yourself with a LongAdder updated alongside the map.

chm api

Quiz yourself on Concurrent collections Suggest a correction