← Home
🏗Crack System Design with DSA AnimatorSystem DesignNEW
🏗 System Design›Concurrency & Threading

🗺️ConcurrentHashMap & Concurrent Collections

Use purpose-built concurrent collections instead of manual locking around HashMap/List.

📌 Key IdeaHashMap is unsafe for concurrent mutation. Prefer ConcurrentHashMap, ConcurrentLinkedQueue, CopyOnWriteArrayList, or blocking queues based on read/write profile.
✨

Why It Matters

  • Concurrent writes on plain HashMap can cause races and corrupted state.
  • ConcurrentHashMap uses fine-grained/CAS-based concurrency, so throughput is far better than one global lock in many workloads.
  • Concurrent maps/queues give thread-safe access patterns without forcing a single global lock around every operation.
✅

When to Use

  • Shared mutable maps/queues accessed by many threads.
  • High-throughput caches/counters/registries.
  • Need weakly-consistent iteration under concurrent updates.
🚫

When NOT to Use

  • Single-thread confined state.
  • CopyOnWrite structures under heavy writes (expensive copies).
💻

Code Variations

1?? Atomic map update without external lockjava
ConcurrentHashMap<String, LongAdder> counts = new ConcurrentHashMap<>();
counts.computeIfAbsent(key, k -> new LongAdder()).increment();
Avoids race from get+put pattern.
2?? Unsafe pattern to avoidjava
Map<String, Integer> m = new HashMap<>();
// two threads mutate/read m concurrently -> undefined behavior
Wrap with synchronization or replace with concurrent collection.
📊

Collection choice quick guide

AspectTypeBest forWatch-out
ConcurrentHashMapRead/write maps, high concurrencyNo null keys/values
CopyOnWriteArrayListMany reads, rare writesWrites are O(n) copy
ConcurrentLinkedQueueNon-blocking producer/consumerNo built-in backpressure
BlockingQueueBackpressure + producer/consumerThreads block on put/take
🎤

Interview Q&A

🧾

Quick Cheat Sheet

Default mapConcurrentHashMap for shared mutable key-value state.
Counter patternConcurrentHashMap + LongAdder.
AvoidRaw HashMap under concurrent writes.
🔗

Related Topics