Custom ConcurrentHashMap implementation

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-12-24

Problem Statement

Design and implement a thread-safe hash map (ConcurrentHashMap) in C++/Java that allows concurrent access with minimal contention. The focus is on object-oriented design, concurrency control, and modularity.


✅ Functional Requirements


1.Core Operations
•put(K key, V value) → Insert or update a key-value pair.
•get(K key) → Retrieve the value for a key.
•remove(K key) → Remove a key-value pair.
•containsKey(K key) → Check if a key exists.
•size() → Return number of entries.
2.Concurrency Support
•Allow multiple threads to read and write concurrently without corrupting the map.
•Minimize locking overhead using strategies like:
•Bucket-level locks (segment locks)
•Fine-grained locking
•Lock-free operations (optional)
3.Hashing & Buckets
•Internally store key-value pairs in buckets (linked list or tree for collisions).
•Each bucket should manage its own lock for concurrency.
4.Optional Features
•Iterators that support weak consistency.
•Automatic resizing / rehashing of buckets.
•Support for custom hash functions.


🔐 Constraints & Assumptions


•Language: C++ or Java.
•Thread-safe operations are mandatory.
•Focus on LLD, not fully optimized performance for huge datasets.
•Assume standard hashCode() / equals() methods exist for keys.
•Avoid global locks to reduce contention.


🧱 Key Components & Classes


1.ConcurrentHashMap Class
1 2template <typename K, typename V> 3class ConcurrentHashMap { 4private: 5 vector<Bucket*> buckets; 6 int bucketCount; 7 mutex globalLock; // optional for initialization/resizing 8public: 9 void put(K key, V value); 10 V get(K key); 11 void remove(K key); 12 bool containsKey(K key); 13 int size(); 14};
1.Bucket Class
1 2template <typename K, typename V> 3class Bucket { 4private: 5 list<pair<K,V>> entries; 6 mutex bucketLock; 7public: 8 void put(K key, V value); 9 V get(K key); 10 void remove(K key); 11};
1.Hash Function / Utility
•Map key to bucket index.


🔄 Example Workflow


1.Thread A calls put("Alice", 25) → hash → bucket 3 → acquire bucket lock → insert/update entry → release lock.
2.Thread B calls get("Alice") → hash → bucket 3 → acquire bucket lock → read entry → release lock.
3.Multiple threads accessing different buckets can proceed concurrently.


🧪 Expected Deliverables


•Class diagram showing ConcurrentHashMap, Bucket, and locking strategy.
•Implementation of core methods with thread-safety.
•Test cases:
•Concurrent put and get
•Concurrent remove operations
•Check size consistency under concurrent updates
•Optional: resizing under high load


💡 Discussion Points


•Trade-offs: coarse-grained vs fine-grained locking.
•Performance impact of locking strategy on throughput.
•Iterators: weakly consistent vs fully consistent.
•How to extend to distributed concurrent hash map.


Solution

Comments