Phase 1: Requirements & Use Cases
Interviewer: "Design a thread-safe hash map."
Candidate: "To confirm scope: we're building a concurrent hash map that supports safe concurrent reads and writes from multiple threads — think Java's
ConcurrentHashMapat the class level. We're NOT building a distributed key-value store. This is a single-process, in-memory map with concurrency guarantees."Interviewer: "What use cases are you targeting?"
Candidate: "The core use cases are:
get(key)— read a value by key, ideally lock-freeput(key, value)— insert or update a key-value pairremove(key)— delete a keycontainsKey(key)— check for existenceresize— grow the internal table when load factor is exceedediterate— weakly consistent traversal without ConcurrentModificationException"Interviewer: "What's your target concurrency model?"
Candidate: "High read concurrency with lock-free gets, and fine-grained locking for writes to minimize contention. I'll follow the Java 8
ConcurrentHashMapapproach: CAS for inserting into empty buckets, synchronized on the bucket's head node for collision writes. This avoids a global lock entirely."WHY: A global lock serializes all operations — it's correct but kills throughput under concurrent writes. Per-bucket locking allows N threads to write to N different buckets simultaneously.
In the full tutorial
- Phase 2: Object Modeling
- Phase 3: Class Design & Relationships
- Phase 4: Design Patterns Application
- Phase 5: Key Implementation
- Phase 6: Extensibility & Trade-offs