Optimization for Read-Heavy Workloads
A standard Mutex (mutual exclusion lock) is a blunt instrument: it allows exactly one thread inside the protected region at a time, regardless of what that thread intends to do. This is safe but unnecessarily restrictive when most threads only want to read shared data.
Reading shared data is inherently safe to do in parallel — two threads reading the same variable simultaneously cannot corrupt it. The problem only arises when at least one thread is writing. A Reader-Writer Lock (ReadWriteLock) exploits this distinction.
The Scenario — A DNS Cache:
- Reads: 99.9% of requests look up an IP address for a hostname. These are pure reads. Running 1,000 of them in parallel is perfectly safe.
- Writes: 0.1% of requests update or invalidate a cache entry. These require exclusive access.
How ReadWriteLock Works:
| Lock Type | Who Can Hold It | Effect on Others |
|---|---|---|
| Read Lock (Shared) | Multiple threads simultaneously | Other readers proceed freely; writers block |
| Write Lock (Exclusive) | Exactly one thread | All readers and all other writers block |
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.HashMap;
import java.util.Map;
public class DnsCache {
private final Map<String, String> cache = new HashMap<>();
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
// Many threads can call this simultaneously
public String lookup(String hostname) {
rwLock.readLock().lock();
try {
return cache.get(hostname);
} finally {
rwLock.readLock().unlock();
}
}
// Only one thread at a time; blocks all readers during update
public void update(String hostname, String ip) {
rwLock.writeLock().lock();
try {
cache.put(hostname, ip);
} finally {
rwLock.writeLock().unlock();
}
}
}
When to use it:
Only when reads vastly outnumber writes — typically a 10:1 ratio or higher. The ReadWriteLock has more internal bookkeeping than a simple Mutex. If writes are frequent, the write lock constantly blocks readers anyway, and you pay the overhead of the complex lock without gaining any parallelism. In that case, a simple Mutex is faster and simpler.
Key Point: Reader-Writer locks are a targeted optimization, not a universal upgrade. Profile your read/write ratio before reaching for one. In write-heavy or balanced workloads, the added complexity of ReadWriteLock produces worse performance than a plain Mutex.