Design Pattern

Read-Write Lock

Clean Java-only production-ready implementation.


What Problem It Solves

Many shared structures are read far more often than they are written. A routing table, a feature flag map, a cache of user profiles, the children of a directory and the suggestion list of a trie node all change rarely and are consulted constantly. A plain mutex treats every access the same, so two threads that only look at the data still take turns.

The cost is easy to count. Suppose 8 threads each need the lock for 100 microseconds to read an entry. With a mutex they run one after another and the last thread finishes after about 800 microseconds. If readers may share the lock, all 8 can run together and the batch takes about 100 microseconds on 8 cores. A writer still needs the structure to itself, so it waits for the readers already inside and then runs alone.

A read-write lock gives you exactly that split. It has a shared mode for readers and an exclusive mode for writers, and it guarantees that a reader never sees the half finished state of a writer. It earns its place when reads dominate, the critical section is long enough to matter and contention is real. That condition is stricter than it sounds, which is why the cost section below tells you to measure.

The Rules and the Invariant

The lock has two modes. Any number of threads may hold the read lock at the same time. Only one thread may hold the write lock, and while it does no reader may hold the lock at all. The invariant the lock must preserve at every instant is that either the writer count is 0 and the reader count is any number, or the writer count is exactly 1 and the reader count is 0. Every correct implementation is a way of keeping that sentence true while threads arrive and leave in any order.

Lock currently held byA new reader asksA new writer asks
NobodyGrantedGranted
One or more readersGranted or made to wait, depending on the fairness policyWaits until every reader has left
One writerWaitsWaits

Inside, the lock needs very little state. It keeps a count of active readers, a flag for an active writer and usually a count of waiting writers, all protected by one ordinary mutex with a condition variable or a wait queue. The lock calls read those fields and either update them or block. The unlock calls update them and wake the waiters who can now proceed. Those fields only decide who may enter. The protected data is a separate thing that you touch while holding the right mode.

Fairness, Starvation and a Worked Timeline

The rules above do not say who goes first when readers and writers are both waiting. That choice is the lock policy, and every answer has a starvation problem of its own.

PolicyRuleWho can starveGood fit
Reader preferenceA new reader enters whenever only readers hold the lock, even if a writer is waitingWriters, because while at least one reader is always inside the reader count never reaches 0Read traffic that arrives in bursts and writes that can afford to wait
Writer preferenceA new reader waits while any writer is waiting or activeReaders, because a steady stream of writers keeps the writer queue from ever emptyingData where fresh writes matter and writers are rare
FairThreads are served in arrival order, and the readers at the front of the queue enter togetherNobody, because every wait is bounded by the work queued ahead of itWhen neither starvation is acceptable and some lost throughput is fine

Worked timeline

Take 4 readers and 2 writers. Readers hold the lock for 10 ticks and writers for 3. The diagram shows the same arrivals under all three policies, with a dot for waiting and a hash for holding the lock.

Loading...
Ticks each thread waited before it got the lock
PolicyW1W2R2R3R4
Reader preference169000
Writer preference8112108
Fair811975

Under reader preference, R2 to R4 walk straight in past the waiting W1, so no reader ever waits and W1 waits 16 ticks. If one more reader kept arriving every 5 ticks, the overlap would never break and W1 would wait forever. That is writer starvation. Under writer preference, W1 blocks R2 to R4 at the door, so it waits only for R1 to finish, which is 8 ticks. W2 then jumps ahead of the three waiting readers and waits 1 tick. Those readers wait 12, 10 and 8 ticks, and if writers kept arriving every few ticks they would wait forever. That is reader starvation. Under the fair policy arrival order decides. W1 still waits 8 ticks, but R2 to R4 arrived before W2, so they enter together at tick 13 and W2 waits 11 ticks. Nobody waits longer than the work that was queued before them.

Real libraries sit in different places on this table. Java ReentrantReadWriteLock in its default non fair mode promises no particular order, but its implementation makes a new reader wait when the thread at the head of the queue is a writer, which keeps a stream of fresh readers from holding writers out in practice. A heavily contended non fair lock can still postpone some threads. Passing true to the constructor selects fair mode, which serves threads in approximately arrival order. Go sync.RWMutex blocks new readers as soon as a writer has called Lock. The hand-built locks later on this page all use writer preference, because it is the simplest policy that cannot starve a writer.

Why You Cannot Upgrade, and the Downgrade That Works

An upgrade means holding the read lock and asking for the write lock without releasing the read lock first. It looks harmless, for example when you read a value, find it missing and want to insert it. It deadlocks as soon as two threads try it at the same time, because the write lock waits for every reader to leave and each upgrader is itself one of those readers.

StepThread AThread BReaders counted
1Takes the read lockNot started1
2Reads the cache and sees a missTakes the read lock and sees the same miss2
3Asks for the write lock and waits for the count to reach 0Still holding its read lock2
4Still waitingAsks for the write lock and waits for the count to reach 02

At step 4 neither thread can make progress. A will not release its read lock until it gets the write lock, and B is in the same position, so the count stays at 2 forever. Java ReentrantReadWriteLock does not try to support the upgrade at all. A thread that holds the read lock and calls writeLock().lock() blocks permanently, even when it is the only reader. The cache driver on this page proves it with a timed tryLock that returns false.

The safe replacement

Release the read lock, take the write lock and then check the condition again. The second check is not optional, because another writer may have run in the gap between the two locks and already done the work. The Java cache tab does this in getOrLoad. Eight threads miss on the same key at once, they queue for the write lock, and the loader runs exactly once because each one re-checks the map after it gets the lock. Without the re-check the loader could run up to 8 times and later results would overwrite earlier ones.

The downgrade that is allowed

The other direction is safe. Take the write lock, acquire the read lock while still holding it, and then release the write lock. Acquiring the read lock cannot block, because while you hold the write lock nobody else holds anything. After the release you hold only the read lock, so you can read back what you just wrote and no other writer can slip in between. The replaceAll method in the Java cache tab uses it to return a key list that is guaranteed to match the data it just installed. The hand-built locks are not reentrant, so they cannot downgrade. A lockRead call made while the same thread holds the write lock would wait on itself.

Reentrancy

A reentrant lock lets the thread that holds it acquire it again without blocking on itself. For a read-write lock there are four combinations and they do not behave alike.

Thread already holdsAsks forResult in ReentrantReadWriteLock
WriteWriteAllowed, and the hold count goes up
WriteReadAllowed, and this is the first half of a downgrade
ReadReadAllowed, even when a writer is queued, because the lock counts read holds per thread
ReadWriteBlocks forever, which is the upgrade deadlock

The read then read case is the subtle one. Under writer preference a nested read must not wait behind a queued writer, because that writer is waiting for the outer read to finish and the outer read is waiting for the nested one. That is a deadlock with a single thread in it. ReentrantReadWriteLock avoids it by tracking read holds per thread and letting such a thread through. Go sync.RWMutex keeps no such record, and its documentation says recursive read locking is prohibited. The hand-built locks on this page are not reentrant, so a nested lockRead can deadlock if a writer queues up between the two calls. The usual cure is structural. Public methods take the lock and private helpers assume it is already held.

Two LLD blueprints rely on the reentrant cases. In File System (Unix-like) the Java createFile takes the global write lock and then calls mkdir, which takes the write lock again, and resolvePath, which takes the read lock while the write lock is held. In Follower / Following System the Java isMutual takes the read lock and calls isFollowing, which takes the read lock again.

How the Hand-Built Lock Works

All three hand-built locks keep the same three pieces of state and apply the same two admission rules. A reader may enter only when no writer is active and no writer is waiting. A writer may enter only when no writer is active and no readers are active. Only the waiting mechanism differs. Java uses synchronized with wait and notifyAll. Python uses a threading.Condition with wait and notify_all. TypeScript keeps two queues of promise resolvers and hands the lock on by calling the resolver at the front of the right queue.

The Java and Python versions re-test their condition in a while loop after every wake up, because one release wakes several waiters at once and only some of them may proceed. They use notifyAll rather than a single notify because one wait set holds both readers and writers. A single wake up could land on a reader that must keep waiting, and the signal would be lost while a runnable writer sleeps on. The TypeScript version needs neither, since it decides who goes next and resolves exactly those promises.

Trace of the policy check

Every hand-built driver ends with the same scenario. The main thread holds a read lock, a writer queues up behind it, and then a late reader arrives. The table follows the lock state through the scenario.

StepEventActive readersWaiting writersWriter activeOutcome
1Main takes the read lock10noGranted
2Writer asks for the write lock11noWaits because a reader is inside
3Late reader asks for the read lock11noWaits because a writer is queued, even though only a reader holds the lock
4Main releases the read lock01noWaiters are woken and the writer is the only one that can proceed
5Writer enters00yesThe late reader stays blocked while a writer is active
6Writer releases the write lock00noLate reader enters

Under reader preference the late reader would have walked in at step 3, so the recorded order would start with it. Under this lock the order is always main releases, writer, late reader.

What the drivers print and why it proves the guarantee

Each of the three hand-built drivers prints three lines. The first runs 4 readers that must all wait for each other while still inside the read section, using a barrier in Java and Python and a shared promise in TypeScript. The wait only ends if all 4 hold the lock at once, so the line reads 4 of 4 when readers overlap, and a plain mutex would hit the 2 second timeout and print less. The second runs 6 reader loops and 3 writer loops against two integers, left and right, which a writer increments in two steps with a pause in between. Probes check that no writer is inside while a reader is, that a writer is always alone, and that a reader never sees the two integers differ. The expected line is zero violations with both integers at 150, which is 3 writers times 50 writes. When the locking is removed, the same probe reports a large number of violations in all three languages. The third line is the policy trace above.

The Cost: Measure Before You Reach for It

A read-write lock is not a faster mutex. It does more work on every acquire and release, because it has to update a reader count, check for waiting writers and wake the right waiters. Even a pure read acquire writes to shared memory, since the reader count lives in one place. On a multi-core machine many readers incrementing the same counter bounce its cache line between cores, so a read heavy workload scales less well than the picture of eight independent readers suggests.

That overhead is only worth paying when the critical section is long enough for overlap to matter. For a few nanoseconds of work, such as a single hash map lookup, a plain mutex or a concurrent map usually wins, because its bookkeeping is smaller than the read-write lock's. As a rough guide a read-write lock starts to pay off when the read section takes around a microsecond or more, reads outnumber writes by a wide margin and many threads genuinely contend. Those are rules of thumb and not guarantees. Measure with your real read to write ratio, your real section length and your real thread count, for example with JMH in Java, and keep the plain mutex if the numbers do not clearly favour the read-write lock.

Alternatives and How to Choose

The read-write lock is one of several ways to serve a read heavy structure, and the others are often simpler or faster.

OptionHow it worksWins whenCosts
Plain mutexOne thread at a time, readers and writers alikeCritical sections are short or reads and writes are mixedReaders queue behind each other
Read-write lockShared mode for readers and exclusive mode for writersRead sections are long, reads dominate and threads really contendMore bookkeeping per call, a starvation policy to choose and no upgrade
Copy on writeA writer copies the whole structure, changes the copy and swaps it in, as Java CopyOnWriteArrayList doesWrites are very rare, the data is small and readers must never blockEvery write copies everything, so writes are O(n) and memory spikes briefly
Immutable snapshotBuild a new immutable version off to the side and publish it with one atomic reference store, and readers grab the reference and use it with no lockWrites are serialized by one thread or a small lock, and readers can tolerate a version that is a moment oldThe writer rebuilds the structure and readers may see stale data
StampedLock optimistic readA reader takes a stamp without locking, copies the fields it needs into locals and calls validate(stamp). If a writer intervened it retries or falls back to a real read lockRead sections are tiny and writes are rare, because an optimistic read writes nothing to shared memoryNot reentrant, no condition support, and you must not act on the values until validation passes. tryConvertToWriteLock can attempt an upgrade that fails instead of deadlocking
Concurrent collectionConcurrentHashMap locks or uses compare and swap on small parts of the mapYou only need map operations on single keysCompound operations over several entries are not atomic

A sensible order is to start with a plain mutex or a concurrent collection and to add a read-write lock only when profiling shows readers queueing on a long read section. If the reads are so frequent that the lock's own counter becomes hot, move to an immutable snapshot or an optimistic read. The snapshot idea is the in-process cousin of how databases let readers proceed without blocking writers, which Transaction Isolation and MVCC explains. A read-write lock also only protects threads inside one process. Across processes you need a distributed lock, as in Distributed Lock Manager, or a design where one owner serializes the writes.

Where Read-Write Lock Appears in LLD Problems

These problems use a read-write lock in their Java blueprints. The right column says what to notice, and one row is a deliberate warning about misuse.

ProblemWhat the lock guardsWhat to notice
File System (Unix-like)Each File and Directory holds a ReentrantReadWriteLock, and FileSystem has a global ReadWriteLockFile.read, Directory.getChildren and resolvePath share the read lock, while File.write, addChild, mkdir and createFile take the write lock. createFile also takes the read lock inside the write lock.
In-Memory Cache (LRU/LFU)The InMemoryCache map and its eviction strategy, behind a ReentrantReadWriteLockBoth get and put take the write lock, because get reorders recency and may remove an expired entry. A read lock there would let two readers corrupt the eviction order.
In-Memory Key-Value StoreInMemoryKVStore.globalLock over the committed global mapAfter checking the thread's own transaction, get reads the global map under the read lock. Non-transactional set and delete, and the outermost commit, take the write lock.
Follower / Following SystemFollowService.rwLock over the two mirrored adjacency maps and the count cachesfollow and unfollow take the write lock because they update both maps and the counts together. Every query, such as isFollowing, isMutual and getFollowerCount, takes the read lock.
Search Engine with TrieThe suggestion list inside each TrieNodegetSuggestions takes the read lock and returns a copy, so the caller never iterates a list that a writer is changing. addSuggestion takes the write lock.
In-Memory SQL DatabaseThe rows, schema and indexes of one Tableselect and getRawRows take the read lock, while addColumn, insert and delete take the write lock.
Pastebin (LLD)The paste store inside PasteServicegetPaste reads under the read lock. When it finds an expired paste it releases the read lock, takes the write lock and checks again before deleting, which is the safe replacement for an upgrade.

Common Interview Traps

TrapWhy it bitesFix
Taking the read lock around code that mutates stateReaders run together, so two of them can change the same structure at once. LRU recency updates, lazy expiry deletes and hit counters all look like reads and are writesTake the write lock on those paths, as InMemoryCache.get does in the cache problem, or make the small mutation thread safe on its own with an atomic counter
Upgrading a read lock to a write lockTwo upgraders each wait for the other to leave and both wait foreverRelease the read lock, take the write lock and re-check, or use StampedLock.tryConvertToWriteLock, which can fail instead of hanging
Not re-checking after release and reacquireBetween the two locks another thread may have done the work, so you load twice or overwrite a newer valueRepeat the check under the write lock, as getOrLoad does in the Java cache tab
Ignoring starvationReader preference lets a stream of readers hold a writer out forever, and writer preference can do the same to readersName the policy you chose and why, and use a fair lock when neither side may starve, accepting the throughput cost
Nested read lock under writer preferenceThe inner read waits behind a queued writer that is itself waiting for the outer read, so the thread deadlocks with itselfUse a lock that counts read holds per thread, such as ReentrantReadWriteLock, or let public methods take the lock and private helpers assume it is held
Forgetting to release on every pathAn exception between lock and unlock leaves the lock held, and every later writer blocks foreverRelease in finally in Java and TypeScript and use a with block in Python, as the withRead and reading helpers and the cache tab on this page do
Returning the protected collection itselfThe caller iterates it after the lock is gone while a writer changes it, which gives a torn view or a ConcurrentModificationExceptionReturn a copy or an immutable view made while holding the lock, as TrieNode.getSuggestions does
Assuming a read-write lock is always fasterThe extra bookkeeping can cost more than the overlap saves when the critical section is tinyMeasure with the real read to write ratio, and prefer a plain mutex or a concurrent map for short sections
Thinking JavaScript needs no lock because it is single threadedTwo async functions interleave at every await, so a reader can run between a writer's two updatesGuard the section with an async read-write lock or a promise queue, and keep the await points inside the guarded section
Holding the lock across slow work such as a network callReaders and writers pile up behind the slow section, and with writer preference every new reader waits as wellKeep sections short and load outside the lock when a duplicate load is harmless, or track in-flight loads per key when the load must happen once

How to Present in an Interview

"Reads of this structure outnumber writes by something like a hundred to one, and each read walks a list, so a plain mutex would make readers queue behind each other. I'll use a read-write lock with writer preference so a steady stream of readers cannot starve a writer. Reads take the read lock and return a copy, writes take the write lock, and anywhere I'm tempted to upgrade I release the read lock, take the write lock and re-check. I would also benchmark it against a plain mutex or a copy on write snapshot, because for tiny critical sections the simpler lock can win."

When NOT to Use a Read-Write Lock

  • Writes are frequent, or reads and writes are about equally common. Writers serialize anyway and you pay the extra bookkeeping for nothing.
  • The critical section is tiny, such as a single map lookup. A plain mutex or a concurrent map is usually cheaper.
  • The "reads" also mutate state, such as LRU recency, lazy expiry or statistics. They need the write lock, so the sharing you wanted never happens.
  • The algorithm needs to upgrade in the middle of an operation. Restructure it, or use StampedLock and handle a failed conversion.
  • The contenders are in different processes. A lock in memory cannot protect them, so use a distributed lock or give each key a single owner.

Implementation Flavors

1. Hand-built lock in Java

SimpleReadWriteLock is a writer preference lock built from synchronized, wait and notifyAll. It is not reentrant and it has no downgrade. Use it to explain the mechanism in an interview, and use the library class in production code.

2. ReentrantReadWriteLock guarding a cache

This is the choice for real code. get takes the read lock and put takes the write lock. getOrLoad shows the release, lock and re-check replacement for an upgrade, and replaceAll shows the downgrade. The loader runs under the write lock, which guarantees a single load but makes every reader of the cache wait while it runs. A production cache tracks in-flight loads per key instead, so that only callers of the same key wait. The driver starts 8 threads that miss on the same key and shows the loader running once, then shows a timed tryLock for the write lock failing while the thread holds the read lock, and finally runs a downgrade and confirms the lock is idle afterwards.

3. Async lock in TypeScript

JavaScript runs one task at a time, so a synchronous block can never be interrupted and a plain object has no data race. The danger is interleaving across await points. A writer that updates one field, awaits a database call and then updates a second field leaves a window in which a reader on the same event loop sees the half finished state. AsyncReadWriteLock closes that window. It keeps two queues of promise resolvers, and readLock and writeLock return a promise that resolves to a release function once the caller is admitted. The release function is safe to call twice, and withRead and withWrite release in a finally block.

4. Python with threading.Condition

The standard library has no read-write lock, so you build one on a Condition, which pairs a mutex with a wait queue. reading() and writing() are context managers that release on every path. In the default CPython build the global interpreter lock stops threads from running bytecode at the same instant, but the interpreter can still switch threads between two statements and during any sleep or I/O call, so the interleaving problems are the same.

// --- WRITER PREFERENCE READ-WRITE LOCK, BUILT FROM synchronized / wait / notifyAll ---
// Rule: many readers OR one writer. A new reader also waits while a writer is queued,
// so a steady stream of readers cannot starve writers. The lock is NOT reentrant.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class SimpleReadWriteLock {
    private int activeReaders = 0;
    private int waitingWriters = 0;
    private boolean writerActive = false;

    public synchronized void lockRead() throws InterruptedException {
        while (writerActive || waitingWriters > 0) wait();
        activeReaders++;
    }

    public synchronized void unlockRead() {
        if (activeReaders == 0) throw new IllegalStateException("read lock not held");
        activeReaders--;
        if (activeReaders == 0) notifyAll();
    }

    public synchronized void lockWrite() throws InterruptedException {
        waitingWriters++;
        try {
            while (writerActive || activeReaders > 0) wait();
        } catch (InterruptedException e) {
            waitingWriters--;
            notifyAll(); // readers blocked on waitingWriters must re-check
            throw e;
        }
        waitingWriters--;
        writerActive = true;
    }

    public synchronized void unlockWrite() {
        if (!writerActive) throw new IllegalStateException("write lock not held");
        writerActive = false;
        notifyAll();
    }

    public synchronized int waitingWriters() { return waitingWriters; }
}

public class Main {
    static final SimpleReadWriteLock lock = new SimpleReadWriteLock();
    static final AtomicInteger readersInside = new AtomicInteger();
    static final AtomicInteger writersInside = new AtomicInteger();
    static final AtomicInteger violations = new AtomicInteger();
    static int left = 0, right = 0; // guarded by lock, a writer moves both in two steps

    static void readOnce() throws InterruptedException {
        lock.lockRead();
        try {
            readersInside.incrementAndGet();
            if (writersInside.get() != 0 || left != right) violations.incrementAndGet();
            Thread.sleep(1);
            if (writersInside.get() != 0 || left != right) violations.incrementAndGet();
            readersInside.decrementAndGet();
        } finally {
            lock.unlockRead();
        }
    }

    static void writeOnce() throws InterruptedException {
        lock.lockWrite();
        try {
            if (writersInside.incrementAndGet() != 1 || readersInside.get() != 0) violations.incrementAndGet();
            left++;
            Thread.sleep(1); // a reader that slipped in here would see left != right
            right++;
            writersInside.decrementAndGet();
        } finally {
            lock.unlockWrite();
        }
    }

    interface Job { void run() throws Exception; }

    static Thread start(Job job) {
        Thread t = new Thread(() -> {
            try { job.run(); } catch (Exception e) { System.out.println("worker failed: " + e); }
        });
        t.start();
        return t;
    }

    public static void main(String[] args) throws Exception {
        // 1. Overlap: 4 readers wait for each other INSIDE the read section.
        //    The barrier only opens if all 4 hold the lock at once. A mutex would time out.
        CyclicBarrier together = new CyclicBarrier(4);
        AtomicInteger met = new AtomicInteger();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            threads.add(start(() -> {
                lock.lockRead();
                try {
                    together.await(2, TimeUnit.SECONDS);
                    met.incrementAndGet();
                } finally {
                    lock.unlockRead();
                }
            }));
        }
        for (Thread t : threads) t.join();
        System.out.println("1. readers inside together: " + met.get() + " of 4");

        // 2. Exclusion: 6 readers and 3 writers hammer the same two fields.
        threads.clear();
        for (int i = 0; i < 6; i++) {
            threads.add(start(() -> { for (int n = 0; n < 100; n++) readOnce(); }));
        }
        for (int i = 0; i < 3; i++) {
            threads.add(start(() -> { for (int n = 0; n < 50; n++) writeOnce(); }));
        }
        for (Thread t : threads) t.join();
        System.out.println("2. violations: " + violations.get() + ", left=" + left + ", right=" + right);

        // 3. Policy: a reader that arrives while a writer is queued must wait behind it.
        List<String> order = Collections.synchronizedList(new ArrayList<>());
        lock.lockRead(); // main holds a read lock
        Thread writer = start(() -> { lock.lockWrite(); order.add("writer"); lock.unlockWrite(); });
        while (lock.waitingWriters() == 0) Thread.sleep(5);
        Thread late = start(() -> { lock.lockRead(); order.add("late reader"); lock.unlockRead(); });
        Thread.sleep(100); // the late reader had every chance to barge in
        order.add("main releases");
        lock.unlockRead();
        writer.join();
        late.join();
        System.out.println("3. order: " + order);
    }
}

💬Review

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...