Algorithms

ConcurrentHashMap

๐Ÿ“‹ Quick Reference

PropertyValue
TypeThread-safe hash map
Get/PutO(1) average, thread-safe
ConcurrencyLock striping (segments)
NullNeither keys nor values can be null
ConsistencyWeakly consistent iteration
Best ForMulti-threaded caching, shared state
One-liner: Thread-safe HashMap using lock striping for high-concurrency reads and writes.

๐ŸŽฎ Interactive Visualizer

Watch how ConcurrentHashMap handles concurrent operations:

Loading visualizer...
Try these operations:
  1. See multiple threads accessing different segments
  2. Watch lock acquisition on writes
  3. Observe lock-free reads
  4. Compare with synchronized HashMap bottleneck

๐Ÿ”ง Key Operations

Creating

JAVA(8 lines)
Code
Loading syntax highlighter...

Basic Operations (Thread-Safe)

JAVA(13 lines)
Code
Loading syntax highlighter...

Atomic Compound Operations

JAVA(14 lines)
Code
Loading syntax highlighter...

Bulk Operations (Java 8+)

JAVA(13 lines)
Code
Loading syntax highlighter...

๐Ÿ“Š Complexity & Concurrency

OperationTimeThread Safety
get(key)O(1)Lock-free read
put(key, val)O(1)Per-bucket lock
remove(key)O(1)Per-bucket lock
putIfAbsentO(1)Atomic
compute*O(1)Atomic within bucket
size()O(n)Approximate

Lock Striping (Java 7)

Segments (each with own lock):
[Segment 0] โ†’ bucket โ†’ bucket โ†’ bucket
[Segment 1] โ†’ bucket โ†’ bucket โ†’ bucket
[Segment 2] โ†’ bucket โ†’ bucket โ†’ bucket
...

Concurrent writes to different segments don't block each other.

Node-Level Locking (Java 8+)

Buckets (synchronized on first node):
[0] โ†’ Node โ†’ Node โ†’ Node  โ† lock on first node
[1] โ†’ Node โ†’ Node         โ† separate lock
[2] โ†’ null                โ† no lock needed
...

Finer-grained: lock per bucket, not segment.

โœ… When to Use ConcurrentHashMap

Good Use Cases

  • Shared caches - read-heavy with occasional updates
  • Counters/stats - atomic increment with merge()
  • Concurrent config - shared configuration
  • Thread-safe lookup - replace synchronized HashMap

Avoid When

  • Single-threaded - HashMap is faster (no sync overhead)
  • Need null keys/values - CHM prohibits nulls
  • Need consistent iteration - iterator is weakly consistent
  • Full atomicity needed - compound ops may need external sync

๐Ÿ”„ ConcurrentHashMap vs Alternatives

FeatureHashMapHashtablesynchronizedMapConcurrentHashMap
Thread-safeNoYesYesYes
Null keysYesNoYesNo
Lock scopeN/AEntire mapEntire mapPer-bucket
PerformanceBestPoorPoorGood
RecommendedSingle threadNeverRarelyMulti-thread
JAVA(8 lines)
Code
Loading syntax highlighter...

๐Ÿงฉ Common Patterns

Thread-Safe Counter

JAVA(8 lines)
Code
Loading syntax highlighter...

Caching with computeIfAbsent

JAVA(7 lines)
Code
Loading syntax highlighter...

Check-Then-Act (Atomically)

JAVA(10 lines)
Code
Loading syntax highlighter...

โš ๏ธ Common Pitfalls

1. Using Null Keys/Values

JAVA(6 lines)
Code
Loading syntax highlighter...

2. Non-Atomic Check-Then-Act

JAVA(7 lines)
Code
Loading syntax highlighter...

3. Blocking in compute()

JAVA(8 lines)
Code
Loading syntax highlighter...

4. Relying on size() for Exact Count

JAVA(8 lines)
Code
Loading syntax highlighter...

5. Iterating with Modifications

JAVA(5 lines)
Code
Loading syntax highlighter...

๐ŸŽค Interview Tips

Q: How does ConcurrentHashMap achieve thread safety?
"

In Java 8+, it uses lock-free reads and synchronized blocks on individual buckets for writes. Each bucket's first node acts as a lock, allowing concurrent access to different buckets.

Q: Why doesn't ConcurrentHashMap allow null?
"

Null would be ambiguous: does get() returning null mean "key not present" or "value is null"? HashMap uses containsKey() to distinguish, but that's not atomic in CHM.

Q: What's weakly consistent iteration?
"

Iterators reflect the state of the map at some point during or after creation. They won't throw ConcurrentModificationException, but may or may not reflect concurrent updates.

Q: ConcurrentHashMap vs synchronized HashMap?
"

CHM allows concurrent reads without locking and uses fine-grained locks for writes (per-bucket). synchronizedMap locks the entire map for every operation, creating a bottleneck.


๐Ÿ“š Series Navigation


Visualizer: ConcurrentHashMap from @tomaszjarosz/react-visualizers