Concurrent collections question 75 of 180 mid
Is ConcurrentHashMap.size() reliable, and what should you use instead?
- Yes, it is exact and O(1)
- Correct: It is an estimate under concurrent modification; for a running total, keep your own
LongAdder - It throws if the map is being modified
- It locks the whole map
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.
Quiz yourself on Concurrent collections Suggest a correction