Thread-Safe Concurrent HashMap
HardConcurrencyLock StripingConcurrentHashMapRead-Write LockHash TableSegmented Locking
Problem Statement
Implement a high-concurrency thread-safe HashMap using lock striping (segmented locking). The map is divided into N segments, each protected by its own ReentrantReadWriteLock. This allows multiple threads to read and write to different segments concurrently, dramatically reducing contention compared to a single global lock.
class StripedHashMap<K, V> {
public StripedHashMap(int initialCapacity, int concurrencyLevel) {}
public V get(K key) {}
public V put(K key, V value) {}
public V remove(K key) {}
public boolean containsKey(K key) {}
public int size() {} // Approximate (sum across segments)
public V putIfAbsent(K key, V value) {}
public V computeIfAbsent(K key, Function<K,V> mappingFn) {}
public void clear() {}
}
Key Entities
- Segment array: Array of N
Segment<K,V>objects (default N=16 matching Java's ConcurrentHashMap). - Segment: Each is a small HashMap + ReentrantReadWriteLock.
- Stripe function:
segmentIndex = (key.hashCode() >>> segmentShift) & segmentMask. - Resize logic: Per-segment resize when load factor threshold exceeded.
Requirements
- Concurrent reads within the same segment must not block each other.
- A write in one segment must not block reads/writes in other segments.
putIfAbsent()andcomputeIfAbsent()must be atomic (check + insert is one critical section).size()is allowed to be approximate (sum of per-segment counts).- Handle hash collisions via chaining or open addressing.
Asked at: Google, Amazon, Microsoft, Facebook, Oracle, Uber, LinkedIn
!Constraints
- concurrencyLevel determines the number of segments (rounds up to next power of 2).
- Load factor for per-segment resize: 0.75.
- Keys and values are non-null.
- No use of Java's ConcurrentHashMap or Hashtable internally.
- Segment count is fixed after construction (no global rehashing).
Output
Run or submit your code to see output here.