Sweaty Imposter

Read-Write Lock

TechniqueConcurrencyMidSeniorUpdated
Allow many concurrent readers OR one exclusive writer, but never both, boosts throughput on read-heavy state.

When to Use Read-Write Lock

Shared state with read:write ratio greater than ~10:1 and non-trivial critical sections. Wrong choice for short critical sections, the rwlock bookkeeping costs more than a plain mutex.

In Practice

Java's ReentrantReadWriteLock and StampedLock, Linux kernel rwsem, pthread pthread_rwlock_t. Used inside many in-memory caches and the JDK's ConcurrentSkipListMap ancestor structures.

Sketch

Java

private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
private Map<String, String> cache = new HashMap<>();

public String get(String k) {
    rw.readLock().lock();
    try { return cache.get(k); }
    finally { rw.readLock().unlock(); }
}

public void put(String k, String v) {
    rw.writeLock().lock();
    try { cache.put(k, v); }
    finally { rw.writeLock().unlock(); }
}

How Read-Write Lock Comes Up in Interviews

Scenario

An in-memory route cache is read by 64 request threads thousands of times per second and updated by a config-refresh thread every 30 seconds. A plain mutex is bottlenecking reads. What's the right primitive?

Read-write locks let all 64 readers proceed in parallel and only block during the rare write. Thread-local would defeat the purpose (each thread has its own cache, no shared truth). A semaphore doesn't distinguish reads from writes.

For an even more read-skewed pattern, copy-on-write or RCU (read-copy-update) wins, readers don't even touch a lock. Senior bonus: rwlock can starve writers under continuous read load; StampedLock gives optimistic reads to mitigate this.