Design a Concurrent HashMap (Thread-Safe HashMap)
HardConcurrencyConcurrencyData StructuresHashingBucket LockingRead-Write Lock
Problem Statement
Design a thread-safe HashMap from scratch that supports concurrent reads and writes with fine-grained locking — similar to Java's ConcurrentHashMap with segment/bucket-level locking.
Requirements
Functional Requirements
put(key, value)— insert or update a key-value pairget(key)→ value or null if not founddelete(key)— remove a keycontainsKey(key)— booleansize()— approximate count of entrieskeys()— snapshot of all current keys- Thread-safe: multiple readers and writers operating concurrently without data corruption
- Load factor and rehashing: when entries exceed threshold, rehash to double capacity
- Handle hash collisions via chaining (linked list) or open addressing
Non-Functional Requirements
- Fine-grained locking: lock per bucket (not global lock)
- Reads can be concurrent (ReadWriteLock per bucket)
- High throughput for read-heavy workloads
Key Entities
- Entry<K, V>: key, value, next (for chaining)
- Bucket: list of entries + ReentrantReadWriteLock
- ConcurrentHashMap<K, V>: array of Buckets, capacity, loadFactor
getBucketIndex(key): hash(key) % capacityput,get,deletewith bucket-level lockingrehash(): doubles capacity, redistributes all entries (global write lock during rehash)
Constraints
- Default capacity: 16 buckets
- Load factor: 0.75 — rehash when (size / capacity) > loadFactor
- Bucket-level ReadWriteLock: multiple concurrent reads per bucket allowed
- Rehashing requires global write lock to prevent corrupt state during resize
!Constraints
- Default capacity 16, load factor 0.75
- Per-bucket ReentrantReadWriteLock: concurrent reads allowed; writes are exclusive per bucket
- Rehashing requires global write lock (briefly blocks all operations)
- Collision handling via chaining (linked list per bucket)
- size() is an approximate count (eventual consistency under concurrent writes)
Output
Run or submit your code to see output here.