← Lessons

quiz vs the machine

Silver1040

Concurrency

The Concurrent Hash Map

How a hash map serves many readers and writers at once without a single global lock.

4 min read · intro · beat Silver to climb

The problem with one big lock

A hash map shared across threads needs protection, but wrapping every operation in one global lock means only a single thread touches the map at a time. Under heavy traffic that lock becomes a queue, and your many cores sit idle waiting their turn.

Splitting the contention

A concurrent hash map breaks the table into independent regions so threads working on different keys rarely collide:

  • The key is hashed, and the high bits select a region while the low bits select a bucket inside it
  • Each region carries its own lock, so two writes to different regions proceed in parallel
  • Reads often need no lock at all because entries are published with safe visibility

The idea is that the chance two random keys land in the same region is small, so most operations run unobstructed.

Visibility still matters

Even lock free reads must see a fully constructed entry. Implementations publish nodes through a memory barrier so a reader never observes a half built value or a stale next pointer.

Key idea

A concurrent hash map trades one global lock for many region locks, so independent keys are served in parallel while reads stay nearly lock free.

Check yourself

Answer to earn rating on the learn ladder.

1. Why does a single global lock hurt a shared hash map?

2. How do independent writes proceed in parallel?