Video in progress
How reliable is the size() result of a ConcurrentHashMap for metrics or business decisions?
While parallel writes are happening, size() is an approximate value: it adds up the counter cells without a lock and may not match any single moment. That is enough for a metric, but you can't build a decision like "did we go over the limit" on it.
📖 Answer
Inside there are baseCount and CounterCell[], the same idea as LongAdder. size() adds them up while other threads keep writing. The result is squeezed into an int; for a big map, mappingCount() returns a long, and the documentation prefers it.
Using it as a gauge is fine:
Gauge.builder("sessions.active", sessions, Map::size).register(registry);
Being off by a few elements hurts nobody.
Here is where the trouble starts:
// wrong: check and add are not atomic
if (sessions.size() < MAX_SESSIONS) {
sessions.put(id, session);
}
If 100 threads check at the same time, they all pass and the limit is exceeded several times over. The right solutions:
- "reserve a slot" with a separate
SemaphoreorAtomicInteger, then add, and give the slot back on failure; - a ready-made structure that enforces the limit, for example Caffeine with
maximumSize(it isn't exact either, but it holds the bound itself).
The same applies to isEmpty(), to the containsKey + put pair, and to computing totals by iteration. Each individual operation is thread-safe, but a sequence of them is not. For a compound update, use atomic methods like compute, merge and putIfAbsent.
Sign up to mark studied questions and save your progress.