Course contentsShow
← Computer Science
Lesson 2583 of 2,87257. Concurrency FundamentalsFree lesson

Striped Locking for Hash Maps

Using multiple locks to partition a hash map for improved concurrency while maintaining consistency.

Striped Locking for Hash Maps

What you'll learn: How to improve hash map concurrency by dividing it into independently locked segments instead of using one giant lock.

The Problem with Single-Lock Hash Maps

When multiple threads access a concurrent hash map protected by a single lock, they all wait in line—even if they're working on completely different parts of the map. This creates a bottleneck that defeats the purpose of concurrency.

What Is Striped Locking?

Striped locking partitions your hash map into multiple regions (often called "stripes" or "segments"), each protected by its own lock. When a thread needs to access a key, it only locks the stripe containing that key, not the entire map.

Think of it like a library with multiple checkout desks instead of one: patrons checking out books on different floors don't wait for each other.

How It Works

The hash function determines which stripe owns a particular key. For example, with 16 stripes, key_hash % 16 tells you which lock to acquire. Operations on keys in stripe 0 don't block operations on keys in stripe 7.

Key benefits:

  • Multiple threads can read/write simultaneously in different stripes
  • Reduced lock contention compared to a single lock
  • Still maintains consistency within each stripe

Trade-offs:

  • Operations spanning multiple stripes (like size calculation or iteration) become complex
  • More memory overhead for multiple locks
  • Must carefully choose stripe count—too few limits concurrency, too many wastes memory

This approach sits between coarse-grained locking (one lock for everything) and fine-grained locking (one lock per bucket), balancing performance with complexity.

Key Takeaway: Striped locking improves hash map concurrency by dividing the map into independently locked segments, allowing multiple threads to operate simultaneously on different regions while maintaining per-stripe consistency.