What's the best collection for high-contention counters — ConcurrentHashMap, AtomicLong, or LongAdder?
⚡ Short Answer
For a single hot counter, LongAdder beats AtomicLong under high contention by striping updates across cells (less CAS retry). For many keyed counters, ConcurrentHashMap<K, LongAdder> with computeIfAbsent gives per-key striped counting.
☕Coffee Chat Question
Concept Made Simple
“What's the best collection for high-contention counters — ConcurrentHashMap, AtomicLong, or LongAdder?”
🧠Mind Map Answer
Remember It Faster
⌨️Hands-on Keyboard
Learn by Doing
ConcurrentHashMap<String, LongAdder> hits = new ConcurrentHashMap<>();
hits.computeIfAbsent(endpoint, k -> new LongAdder()).increment();
// read total: hits.get(endpoint).sum();🔥What If?
Think Beyond the Expected
Why does AtomicLong degrade under many threads while LongAdder scales?
AtomicLong funnels every increment through one memory location via CAS; under contention threads keep retrying. LongAdder spreads increments across multiple internal cells (one per contended thread), so writes rarely collide; sum() adds the cells when you read.
😂Real World
Metrics like request counts, hits, and error tallies under heavy concurrency use LongAdder (it's what many metrics libraries use internally) to avoid the CAS bottleneck of AtomicLong.
🎯Interviewer's Expectation
Keywords they're listening for:
⚠️Common Mistakes
- ✗Using AtomicLong for extremely hot counters
- ✗get-then-put races losing increments
- ✗Reading LongAdder.sum() in a tight loop (it's not free)
✅Best Practices
- ✓LongAdder for high-contention write-heavy counters
- ✓CHM<K, LongAdder> + computeIfAbsent for keyed metrics
- ✓AtomicLong when reads are frequent and contention low
🔁Follow-up Questions
- 1When is AtomicLong still preferable to LongAdder?
- 2Why use computeIfAbsent rather than get-then-put?
- 3How do metrics libraries (Micrometer) implement counters?
🧩Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Performance (Java Collections) Interview question: "What's the best collection for high-contention counters — ConcurrentHashMap, AtomicLong, or LongAdder?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.