Thread-Safe Maps, Cache Sharding and Batch Processing Models
System DesignModel answerLast updated
Explain how Java's concurrent hash map stays safe under contention, how to shard a session cache without mass reshuffling, and when batch map-reduce beats SQL joins.
This is a three-part conceptual question. Answer each part with mechanisms and concrete numbers, not slogans.
Part 1: Thread-safe maps in Java
- Describe how Java's
ConcurrentHashMapstays correct under many simultaneous readers and writers without putting one lock around the whole structure. Cover how reads, inserts, and resizes work. - You want to use your own class as a key in this map. What must hold for its
equals()andhashCode()implementations, and what goes wrong if those rules are broken?
Part 2: Sharding a session cache
You are building a distributed cache for user session data on 10 nodes.
- Keys are assigned with
node = hash(user_id) % num_nodes. What is the main problem when a node is added or removed? Quantify it if you can. - Propose a placement scheme that moves far less data when the cluster changes. Explain how it works and which parameters affect how evenly load is spread.
Part 3: Processing models
Compare the MapReduce programming model with relational SQL joins. Describe a situation where you would choose a MapReduce-style batch job over a complicated SQL query running on a sharded database.
Hints
Hint 1
Think about the granularity of synchronization: what is the smallest unit that must be locked for a write, and which operations need no lock at all?
Hint 2
A key's hash picks the bucket and equality is checked inside it. Ask what happens to a lookup if two equal keys land in different buckets, or if a key's fields change after insertion.
Hint 3
For modulo placement, compute the fraction of keys for which h mod 10 equals h mod 11. For the alternative, picture nodes and keys on a circle and ask which keys are affected when one node appears.
Hint 4
For Part 3, compare who decides the execution plan, how data is moved between machines, and what happens to a job when a worker dies halfway.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: How the concurrent map works
Lock the bucket, not the map
Older synchronized maps wrap every call in one monitor, so all threads queue up. The concurrent map shrinks the unit of locking.
Java 7 and earlier (segments). The table was split into segments (16 by default). Each segment had its own lock and its own small hash table, so up to 16 writers could proceed in parallel. Reads mostly avoided locks by relying on volatile fields.
Java 8 and later (CAS plus per-bin locks).
- Reads take no lock. Table slots are read with volatile semantics, and node value and next-pointer fields are volatile, so a reader always sees a fully published node.
- Insert into an empty bin uses a single compare-and-swap on the slot. No lock.
- Insert into a non-empty bin synchronizes on the head node of that bin only. Two threads contend only if they hit the same bucket.
- Treeification. A bin with 8 or more entries (when the table has at least 64 slots) becomes a red-black tree, turning worst-case lookup from O(n) into O(log n).
- Cooperative resizing. Migrated bins are marked with a forwarding node. Writers that meet one help move chunks of the table, and readers are redirected to the new table.
- Striped counters (similar to
LongAdder) track size, so there is no single hot counter. - Atomic per-key compound operations:
putIfAbsent,compute,computeIfAbsent,merge. Writinggetfollowed byputis a race and a classic mistake. - Iterators are weakly consistent (no
ConcurrentModificationException), and null keys and values are rejected so anullfromgetalways means "absent".
Rules for a custom key
- Contract: equal objects must have equal hash codes. The hash picks the bucket and
equalsruns inside it. If equal keys hash differently, lookups go to the wrong bucket and miss data that is present. equalsmust be an equivalence relation: reflexive, symmetric, transitive, consistent, and false fornull. Otherwise results depend on which object is the receiver.- Stability: fields used by
hashCode/equalsmust not change while the object is in the map. A mutated key stays in the bucket for its old hash and becomes unreachable, a silent leak. Prefer immutable keys (final fields, or a record). - Distribution: spread hashes well. The map mixes high bits into low bits but cannot fix a constant hash. Implementing
Comparablealso helps tree bins order colliding keys.
Part 2: Session cache placement
Why modulo fails
A key stays put going from 10 to 11 nodes only if h mod 10 == h mod 11. For uniform h that is 10 out of every 110 values, about 1/11 of keys. So roughly 91% of keys move. Removing a node is similarly bad. For sessions this means a miss storm, a thundering herd on the backing store, possible forced logouts if the cache holds the only copy, and heavy rebalancing traffic exactly when the cluster is already changing.
Consistent hashing
- Hash both nodes and keys onto a ring (for example 0 to 2^64 - 1).
- A key belongs to the first node clockwise from its position.
- Adding a node claims only the arc between it and its predecessor, so about K/N keys move, all from one neighbor. Removing a node passes its arc to its successor.
- For availability, replicate each session onto the next R distinct physical nodes clockwise.
What controls uniformity:
- Virtual nodes per machine (v). The most important knob. With one point per node, arcs vary a lot and the busiest node can carry several times the average. Imbalance falls roughly as 1/sqrt(v); 100 to 200 vnodes typically gives about +/-5 to 10%.
- Hash quality. Use a fast uniform hash such as Murmur3 or xxHash.
- Weights. Give bigger machines proportionally more vnodes.
- Key skew. A few very hot users overload a node regardless of placement; mitigate with hot-key replication or a local near cache.
Alternatives: rendezvous (highest-random-weight) hashing, which needs no ring but costs O(N) per lookup, and jump consistent hash, which uses no memory but only supports numbered buckets.
import bisect, hashlib
class Ring:
def __init__(self, vnodes=150):
self.vnodes, self.ring, self.owner = vnodes, [], {}
@staticmethod
def _h(s):
return int.from_bytes(hashlib.md5(s.encode()).digest()[:8], "big")
def add(self, node):
for i in range(self.vnodes):
p = self._h(f"{node}#{i}")
bisect.insort(self.ring, p)
self.owner[p] = node
def remove(self, node):
for i in range(self.vnodes):
p = self._h(f"{node}#{i}")
self.ring.remove(p)
del self.owner[p]
def get(self, key):
i = bisect.bisect_right(self.ring, self._h(key)) % len(self.ring)
return self.owner[self.ring[i]]
Lookup is O(log(Nv)). With a list, add and remove cost O(Nv) per point because of insertion and removal; a balanced tree (for example Java's TreeMap.ceilingEntry) fixes that.
Part 3: MapReduce vs SQL joins
| SQL join | MapReduce | |
|---|---|---|
| Style | Declarative; an optimizer picks hash, merge, or nested-loop joins and uses indexes | Imperative; you write map and reduce functions and the framework handles the shuffle |
| Join mechanics | Planner-chosen, often index-assisted | Reduce-side join (shuffle both inputs by key) or map-side broadcast join for a small table |
| Data | Structured, schema-enforced | Any format: logs, text, blobs |
| Latency | Interactive | Batch, minutes to hours |
| Fault handling | Query usually restarts | Failed tasks are re-run individually |
Prefer a MapReduce-style batch job when:
- The data is huge, raw, or semi-structured (clickstream logs, session dumps) and loading it into the database first is wasteful.
- The logic is not expressible in SQL, such as custom parsing, sessionization, or iterative or ML-style transforms.
- A multi-way join across shards would force heavy cross-shard shuffling and overload the production database; an offline job scans files sequentially and does not compete with live traffic.
- The workload is a periodic full scan where throughput matters more than latency, and tolerance of worker failures is important.
Prefer SQL when queries are interactive, selective, index-friendly, and the data already lives in a relational store.
Common mistakes
- Saying the map "locks per segment" without distinguishing Java 7 from Java 8+.
- Using
getthenputinstead of an atomic compound method. - Mutable keys.
- Claiming consistent hashing gives perfect balance without virtual nodes.
- Forgetting replication, or that hot keys defeat any placement scheme.