A notice board in an office corridor works this way. Any number of people can stand in front of it and read at the same time. When the office manager pins up a new notice, people step back for a moment, and nobody reads a page that is half pinned. The manager waits until nobody is reading, changes the board, and then everyone reads again.
Software has the same shape wherever a table is read far more often than it changes: a routing table, a price list, a server's configuration. Readers do not get in each other's way, because none of them changes anything. Only a change needs the table to itself.
The Read-Write Lock pattern guards such a table with two locks that work together: a read lock that many threads can hold at once, and a write lock that one thread holds alone. In this article we build the feature-flag store of an online shop twice. The first version uses one plain lock. The second uses Java's ReentrantReadWriteLock. Then we look at writer starvation, the upgrade deadlock, when the pattern does not pay, and two alternatives: an immutable snapshot swapped in one step, and StampedLock.
All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the plain-lock version, the rest from the finished design. Both projects run, and the outputs shown are what they print.
The flag store we are building
A flag such as dark-mode is either off, or on for a share of users, its rollout percentage. Every request asks the store about a few flags, and the page the browser loads asks for all of them. An admin changes flags a few times a day, often several together: the new checkout only works with the new payment page.
The store must:
- Answer any flag for any user, from many threads at once. A user lands in the same bucket from 0 to 99 every time, and gets the flag if the bucket is below the percentage.
- Answer an unknown flag with "off", not an error.
- Answer several flags at one version. A request never sees the new checkout switched on and the new payment page still off.
- Apply a change set as one step: all its flags change and the version goes up by one, or nothing changes.
- Let reads run together. A read waits only for a change, never for another read.
- Let a change in, even while reads keep arriving. A kill switch that waits for ever is useless.
- Refuse a bad change: a rollout outside 0 to 100, an empty change set, or one flag named twice.
- Publish: apply a change set and hand back every flag at exactly the version it made, for the servers at the edge to download.
This is the figure to draw first in an interview. It states the whole rule: any number of readers, or one writer, never both. Every later question is about who waits in this picture.
The first version: one lock for everything
The obvious store puts a ReentrantLock around every method. Here is the read that the browser's page makes, which evaluates all 2,004 flags for one user, and the write:
public Evaluation evaluateAll(String userId) { Objects.requireNonNull(userId, "userId"); lock.lock(); try { Map<String, Boolean> values = new HashMap<>(); for (Flag flag : flags.values()) { values.put(flag.name(), flag.isOnFor(userId)); } return new Evaluation(version, values); } finally { lock.unlock(); } } public long apply(ChangeSet changes) { lock.lock(); try { flags.putAll(changes.byName()); version++; return version; } finally { lock.unlock(); } }This store is correct: no reader sees half a change set, and the version always matches the flags. When reads are short and requests are few, it is also fast enough.
The program runs eight threads that each read all 2,004 flags 300 times, with no writer. Another thread notes the most threads it saw waiting:
8 readers, 300 reads each, nobody writing the plain lock lets in one thread at a time most threads waiting at one moment: 7
The exact count changes from run to run.
Reads wait for reads. Nothing in evaluateAll changes the table, yet the lock lets one thread in at a time. With eight request threads, a read can wait for seven other reads to finish first.
The wait grows with the read. One flag takes a moment, but all 2,004 flags for the browser take much longer, and every other request queues behind that read.
A change is no different from a read. The lock cannot tell the admin's rare change set from the lookups that happen on every request.
The idea
The pattern works like this:
- One lock object has two sides. The read side can be held by any number of threads at once. The write side can be held by one thread, and only while nobody holds the read side.
- Every method that only looks takes the read lock, and every method that changes anything takes the write lock.
- A writer waits for the readers inside to leave, and while it waits, a fair lock makes new readers queue behind it.
- A thread that holds the write lock may take the read lock and then let go of the write lock. That is a downgrade.
ReentrantReadWriteLocknever allows the other way, an upgrade.
The two sides are the read lock and the write lock. Threads that hold the read lock are readers, and the thread that holds the write lock is the writer. In Java, ReentrantReadWriteLock provides both, through readLock() and writeLock().
Building it, step by step
Step 1: one read-write lock over the whole table
FlagStore keeps the flags in a HashMap and a version number, and guards both with one ReentrantReadWriteLock. isEnabled takes the read lock:
public final class FlagStore implements FeatureFlags { // Fair: readers that arrive after a waiting writer queue behind it. private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock(); private final Map<String, Flag> flags = new HashMap<>(); // guarded by lock private long version = 1; // guarded by lock public FlagStore(List<Flag> initialFlags) { flags.putAll(new ChangeSet(initialFlags).byName()); } @Override public boolean isEnabled(String flagName, String userId) { Objects.requireNonNull(flagName, "flagName"); Objects.requireNonNull(userId, "userId"); readLock.lock(); try { Flag flag = flags.get(flagName); return flag != null && flag.isOnFor(userId); } finally { readLock.unlock(); } }Line 16 creates the lock, and the comments on lines 19 and 20 say what it guards: the map and the version, together. isEnabled holds the read lock from line 30 to line 35, so any number of request threads can be inside at once. The unlock sits in a finally, so a read that throws still lets go of the lock.
The rollout check lives in Flag, which knows nothing about locks:
/** True if this flag is on for this user. A user stays in the same bucket on every request. */ public boolean isOnFor(String userId) { return enabled && bucketOf(userId) < rolloutPercent; } /** A number from 0 to 99 for this user and this flag, the same on every server. */ public int bucketOf(String userId) { Objects.requireNonNull(userId, "userId"); return Math.floorMod((name + ":" + userId).hashCode(), 100); }Line 34 hashes the flag's name with the user's id and keeps the remainder from 0 to 99. Line 28 asks for a bucket below the percentage, so a 50% rollout covers buckets 0 to 49, and a user in bucket 50 does not get the flag.
What guards the table?
A ConcurrentHashMap and no lock
Each lookup is safe and never waits. But a change set writes several keys one after another, and a reader between two of them sees the new checkout on and the new payment page off. Nothing ties the version to the flags either. It is the right answer when every read touches one key.
One plain lock
This is the first version. It is correct and simple, and every read waits for every other read.
One read-write lock over the map and the versionOur pick
Reads hold the read lock and run together. A change set holds the write lock, so it is all or nothing for every reader. The cost is a lock with more bookkeeping than a plain one, which is waste when reads are short, and a rule to keep: every method that changes anything must take the write side.
What does a read of an unknown flag return?
Throw an exception
A typo in a flag name is caught at once. But code deployed before its flag exists then fails on every request.
OffOur pick
isEnabled returns false when flags.get finds nothing (line 33), and so does evaluate. A new feature stays hidden until its flag exists. The cost is that a misspelt flag looks exactly like a flag that is switched off.
Step 2: reads that see one version
A request that asks about the new checkout and the new payment page must get both answers from the same version. evaluate holds the read lock around the whole loop:
@Override public Evaluation evaluate(String userId, List<String> flagNames) { List<String> names = List.copyOf(flagNames); readLock.lock(); try { return Evaluation.of(version, flags, userId, names); } finally { readLock.unlock(); } } @Override public Evaluation evaluateAll(String userId) { readLock.lock(); try { return Evaluation.of(version, flags, userId, flags.keySet()); } finally { readLock.unlock(); } }Evaluation.of reads the version and every named flag, all while the caller holds the read lock:
/** The caller makes sure nobody changes flags while this runs. */ static Evaluation of(long version, Map<String, Flag> flags, String userId, Collection<String> flagNames) { Objects.requireNonNull(userId, "userId"); Map<String, Boolean> values = new HashMap<>(); for (String name : flagNames) { Flag flag = flags.get(name); values.put(name, flag != null && flag.isOnFor(userId)); } return new Evaluation(version, values); }No writer can get in between two of those reads, so the Evaluation holds one version and the flags of that version. Two separate isEnabled calls would not give this, because a change set could run between them.
Evaluation copies its map with Map.copyOf, so the caller holds an answer that no later change can alter. Snapshot copies the flags the same way, so nothing outside the store ever holds the live HashMap.
Step 3: a change set runs alone
apply takes the write lock, and applyLocked does the work:
@Override public long apply(ChangeSet changes) { Objects.requireNonNull(changes, "changes"); writeLock.lock(); try { return applyLocked(changes); } finally { writeLock.unlock(); } } private long applyLocked(ChangeSet changes) { flags.putAll(changes.byName()); version++; return version; }The write lock on line 63 waits until no thread holds the read lock, and while it is held, no reader gets in. Lines 118 and 119 change the flags and the version together, so a reader sees both before or both after.
The change set is checked before the lock is taken. ChangeSet's constructor refuses an empty list and a name that appears twice, and Flag's constructor refuses a rollout outside 0 to 100. A bad change is an IllegalArgumentException, because the admin page should have caught it first. The checks never hold up readers, and a change set that reaches apply cannot fail half way.
demo/RaceCheck.java runs one thread that keeps switching both checkout flags together while eight threads read them, against this store and against the snapshot store we meet later:
FlagStore (read-write lock) 8 readers x 20,000 reads, while one writer kept switching the writer got in during the run: true one flag on and the other off: 0 values that do not match their version: 0 a reader saw the version go back: 0 CopyOnWriteFlagStore (snapshot swap) 8 readers x 20,000 reads, while one writer kept switching the writer got in during the run: true one flag on and the other off: 0 values that do not match their version: 0 a reader saw the version go back: 0
No reader saw one flag on and the other off. Version 1 has both off and every change set flips both, so a version that is even must have both on. No answer broke that rule. With the lock calls deleted from FlagStore, the same check found tens of thousands of the 160,000 reads with one flag on and the other off.
Step 4: fair, so a change is not starved
A read-write lock has a danger that a plain lock does not. If readers keep arriving and their reads overlap, the count of readers inside may never fall to zero. A writer that waits for zero then waits for ever. This is writer starvation, and it is the reason requirement 6 exists.
demo/WriterStarvation.java shows it with a small hand-written lock that lets a reader in whenever no writer is writing:
@Override public synchronized void lockRead() throws InterruptedException { while (writing) { wait(); } readers++; } @Override public synchronized void unlockRead() { readers--; if (readers == 0) { notifyAll(); } } @Override public synchronized void lockWrite() throws InterruptedException { writersWaiting++; try { while (writing || readers > 0) { wait(); } } finally { writersWaiting--; } writing = true; }lockRead checks only writing (line 130), never whether a writer is waiting. The demo runs 40 readers in a relay: each reader stays inside until the next one is in, or for 100 milliseconds if none comes. A writer arrives just after the first reader. Then the same relay runs on Java's lock, in its default mode and in fair mode:
40 readers in a relay, a writer arriving after the first a lock that lets readers in while any reader is inside: the writer got in after 40 of 40 readers ReentrantReadWriteLock, default: the writer got in after 1 of 40 readers ReentrantReadWriteLock, fair: the writer got in after 1 of 40 readers
On the hand-written lock, the writer got in only after all 40 readers, because the count of readers never reached zero until the relay ran out. On a busy server, the relay never runs out. On both Java locks, the second reader queued behind the waiting writer, and the writer got in after the first reader.
Java's default lock has a rule of thumb inside it: a new reader steps aside if the first thread in the queue is a writer. That is a heuristic, not a promise. The documentation says a non-fair lock under constant contention may put a thread off indefinitely.
Fair or default?
The default
The order of entry is not specified, and threads may barge in ahead of others that are waiting. Throughput is normally higher. In practice a waiting writer usually gets in, but nothing promises it.
FairOur pick
Line 16 passes true. A thread that asks for the read lock waits if the write lock is held or a writer is waiting, so a writer waits only for the readers already inside. Threads get the lock roughly in the order they asked. With changes this rare, the queue is almost always empty, and a fair lock then lets readers straight in, as the default does. The cost is lower throughput when the queue is busy, because no thread may barge in ahead of it.
Step 5: a read lock cannot become a write lock
Sometimes a read finds that it has to write. Say a request asks about a flag nobody has defined, and the store wants to note the name for the admin page. The obvious code holds the read lock, sees the name is missing, and asks for the write lock. FlagStore never does this. demo/UpgradeTrap.java shows the trap on a bare lock:
/** Wrong: a thread that holds the read lock asks for the write lock. */ boolean noteByUpgrading(String flagName) throws InterruptedException { lock.readLock().lock(); try { if (unknownFlags.contains(flagName)) { return true; } // The write lock waits until no thread holds the read lock, and this thread holds it. // With writeLock().lock() this line would wait for ever; the timeout makes the trap visible. if (!lock.writeLock().tryLock(200, TimeUnit.MILLISECONDS)) { System.out.println("the write lock did not come within 200 ms"); return false; } try { unknownFlags.add(flagName); return true; } finally { lock.writeLock().unlock(); } } finally { lock.readLock().unlock(); } }The write lock waits until no thread holds the read lock, and this thread holds it, on line 39. So the thread waits for itself. With writeLock().lock(), it would wait for ever, and on a fair lock every thread that came after it would queue behind it. Line 46 uses tryLock with a 200 millisecond limit, so the demo can show the trap and carry on. Two threads that both hold the read lock and both ask for the write lock deadlock the same way, each waiting for the other.
The fix is to let go of the read lock, take the write lock, and check again:
/** Right: check under the read lock, then take the write lock and check again. */ void note(String flagName) { lock.readLock().lock(); try { if (unknownFlags.contains(flagName)) { return; } } finally { lock.readLock().unlock(); } lock.writeLock().lock(); try { if (!unknownFlags.contains(flagName)) { // another thread may have noted it in the gap unknownFlags.add(flagName); } } finally { lock.writeLock().unlock(); } }Between line 69 and line 71, the thread holds no lock, so another thread may note the same name first. Line 73 checks again under the write lock, which is the only check that counts.
The other direction is allowed. A thread that holds the write lock may take the read lock, because the lock knows the writer is this thread, and then let go of the write lock. That is a downgrade, and publish uses it:
/** Applies the changes and returns every flag at exactly the version they made. */ public Snapshot publish(ChangeSet changes) { Objects.requireNonNull(changes, "changes"); writeLock.lock(); try { applyLocked(changes); readLock.lock(); // downgrade: take the read lock before letting go of the write lock } finally { writeLock.unlock(); } try { return new Snapshot(version, flags); // other readers may come in now, but no writer } finally { readLock.unlock(); } }Line 77 takes the read lock while the write lock is still held, and line 79 lets go of the write lock. From then on, no writer can get in, because this thread still holds the read lock. Other readers may come in, unless a writer is already waiting. Line 82 builds a Snapshot, a copy of every flag, and that copy is exactly the version this change set made. Line 84 lets go of the read lock.
1. Holding the read lock, ask for the write lock the write lock did not come within 200 ms noted beta-search: false unknown flags: [] 2. Let go of the read lock, take the write lock, check again two threads noted beta-search, unknown flags: [beta-search] 3. Holding the write lock, take the read lock, then let go of the write lock holding the write lock: true, holding the read lock: true now only reading; another thread can read: true, can write: false
In part 1 the write lock never came. In part 2 two threads noted beta-search together, and the list holds it once. In part 3, after the downgrade, another thread could read but not write.
How does publish return exactly the version it made?
Copy under the write lock
This is correct, but every request waits while 2,004 flags are copied. The copy only reads, so holding readers out for it is waste.
Let go of the write lock, then take the read lock
Readers can come in during the copy. But a writer waiting in the queue can get in between the two calls, and the snapshot then holds someone else's change under our name.
Downgrade: take the read lock before letting go of the write lockOur pick
Readers can come in during the copy if no writer is waiting, and no writer gets in, so the copy is exactly our version. The cost is one more lock call, in the order shown, which a careless edit can swap.
The finished design
Here is one publish, traced through the locks:
The whole project is below. Click any class name in the code to open that class.
package flags; import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Feature flags read on every request and changed a few times a day. Any number * of threads may read at once; a change waits for them and then runs alone. */public final class FlagStore implements FeatureFlags { // Fair: readers that arrive after a waiting writer queue behind it. private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock(); private final Map<String, Flag> flags = new HashMap<>(); // guarded by lock private long version = 1; // guarded by lock public FlagStore(List<Flag> initialFlags) { flags.putAll(new ChangeSet(initialFlags).byName()); } @Override public boolean isEnabled(String flagName, String userId) { Objects.requireNonNull(flagName, "flagName"); Objects.requireNonNull(userId, "userId"); readLock.lock(); try { Flag flag = flags.get(flagName); return flag != null && flag.isOnFor(userId); } finally { readLock.unlock(); } } @Override public Evaluation evaluate(String userId, List<String> flagNames) { List<String> names = List.copyOf(flagNames); readLock.lock(); try { return Evaluation.of(version, flags, userId, names); } finally { readLock.unlock(); } } @Override public Evaluation evaluateAll(String userId) { readLock.lock(); try { return Evaluation.of(version, flags, userId, flags.keySet()); } finally { readLock.unlock(); } } @Override public long apply(ChangeSet changes) { Objects.requireNonNull(changes, "changes"); writeLock.lock(); try { return applyLocked(changes); } finally { writeLock.unlock(); } } /** Applies the changes and returns every flag at exactly the version they made. */ public Snapshot publish(ChangeSet changes) { Objects.requireNonNull(changes, "changes"); writeLock.lock(); try { applyLocked(changes); readLock.lock(); // downgrade: take the read lock before letting go of the write lock } finally { writeLock.unlock(); } try { return new Snapshot(version, flags); // other readers may come in now, but no writer } finally { readLock.unlock(); } } public Snapshot snapshot() { readLock.lock(); try { return new Snapshot(version, flags); } finally { readLock.unlock(); } } @Override public long version() { readLock.lock(); try { return version; } finally { readLock.unlock(); } } /** For monitoring: how many threads hold the read lock right now. */ public int readersInside() { return lock.getReadLockCount(); } /** For monitoring: about how many threads are waiting for either lock. */ public int threadsWaiting() { return lock.getQueueLength(); } private long applyLocked(ChangeSet changes) { flags.putAll(changes.byName()); version++; return version; }}demo/Main.java walks through the store:
1. dark-mode is on for 50% of users user-17: bucket 24, dark-mode true user-42: bucket 12, dark-mode true user-305: bucket 50, dark-mode false user-731: bucket 83, dark-mode false a flag nobody defined: false 2. One request reads both checkout flags at one version version 1: new-checkout false, new-payment-page false 3. An admin switches both on in one change set applied, now at version 2 version 2: new-checkout true, new-payment-page true 4. Changes the store refuses refused: rolloutPercent must be 0 to 100, was 120 refused: a change set needs at least one flag refused: flag dark-mode appears twice in one change set still at version 2 5. Eight threads each read all 2,004 flags, 300 times most readers inside at one moment: 8 most threads waiting at one moment: 0 6. publish: apply a change set and copy every flag at that version snapshot version 3, 4 flags, new-checkout false store version 3
Part 1 is requirement 1: with dark-mode at 50%, the users in buckets 24 and 12 get it, and the users in buckets 50 and 83 do not. A flag nobody defined is off (requirement 2). Parts 2 and 3 read both checkout flags at one version, before and after one change set that moved the version from 1 to 2 (requirements 3 and 4). Part 4 shows the three refusals, and the version stayed at 2 (requirement 7). Part 5 runs the same eight readers as the first version: several readers were inside at the same moment, and none waited (requirement 5). The number inside changes from run to run. Part 6 publishes a change set and gets back the flags of version 3 (requirement 8).
What it costs
Reads run together, but only reads. The lock helps exactly as much as reads outnumber and outlast writes. One write still stops every read for as long as it runs.
A writer waits for the slowest read inside. In our fair lock, new readers queue behind that writer, so one long read can hold up every request for its length.
The read lock is not free. Every reader updates a count shared by all readers, so on a short read the lock's own work can be as much as the read it guards.
The rule lives in the code, not the type. Nothing stops a later method from changing the map under the read lock. A reviewer has to check that every write takes the write side.
When a plain lock or a plain map is better
Short reads. If every read is one HashMap lookup, the plain lock in the first version is held for so short a time that the waits hardly matter.
Frequent writes. Readers then spend their time waiting for writers anyway.
Reads that secretly write. A read that changes anything, a hit count, a "last used" time, a moved list node, needs the write lock, and then nothing runs together. The LRU cache page explains why its get is exactly this case.
Reads of one key. If no read needs two keys at one version, a ConcurrentHashMap needs no lock of ours at all:
private final Map<String, Flag> flags = new ConcurrentHashMap<>(); public boolean isEnabled(String flagName, String userId) { Flag flag = flags.get(flagName); // never waits, even during a write return flag != null && flag.isOnFor(userId);} public void apply(List<Flag> changes) { for (Flag flag : changes) { flags.put(flag.name(), flag); // a reader can see some of these and not others }}The logging framework page uses a read-write lock for a different job: appends share the read lock, and close takes the write lock to keep them out.
Read-write lock, snapshot swap or StampedLock?
Two alternatives belong in the same answer.
A snapshot swap keeps every flag in an immutable Snapshot and points at the current one through an AtomicReference. Readers take whatever snapshot is current and never wait. A writer copies the table, changes the copy, and swaps it in:
@Override public Evaluation evaluateAll(String userId) { Snapshot snapshot = current.get(); // read once: one version for the whole answer return snapshot.evaluate(userId, snapshot.flags().keySet()); } @Override public long apply(ChangeSet changes) { Objects.requireNonNull(changes, "changes"); Map<String, Flag> changed = changes.byName(); while (true) { Snapshot old = current.get(); Map<String, Flag> copy = new HashMap<>(old.flags()); copy.putAll(changed); Snapshot next = new Snapshot(old.version() + 1, copy); if (current.compareAndSet(old, next)) { return next.version(); } // another writer swapped first: copy its snapshot and try again } }Line 41 reads the reference once, so the whole answer comes from one version. Lines 51 to 53 build a new snapshot, and line 54 swaps it in only if no other writer swapped first. Otherwise the loop tries again on the newer snapshot, so no change is lost. RaceCheck ran this store too, with the same result. The cost is a full copy of the table on every change set, and a reader may finish on a snapshot that has just been replaced. Its answer may be out of date, but never half of two. The same idea also works with a volatile field and writers that take a lock. Immutability explains why a shared object that never changes needs no lock.
StampedLock adds an optimistic read. A reader takes a stamp without locking, reads the fields into locals, and asks whether any write happened since. If one did, it reads again under a real read lock:
private final StampedLock lock = new StampedLock();private long version = 1; // guarded by lockprivate int rolloutPercent; // guarded by lock Rollout read() { long stamp = lock.tryOptimisticRead(); // no lock taken, only a stamp long seenVersion = version; int seenPercent = rolloutPercent; if (!lock.validate(stamp)) { // a write happened: read again properly stamp = lock.readLock(); try { seenVersion = version; seenPercent = rolloutPercent; } finally { lock.unlockRead(stamp); } } return new Rollout(seenVersion, seenPercent);}The optimistic part can read a mix of old and new values before validate rejects it, so it suits a few plain fields, not a HashMap that a writer may be resizing. A StampedLock can try an upgrade with tryConvertToWriteLock, which fails instead of waiting. It is not reentrant, has no conditions, and a thread that asks for its write lock while already holding it deadlocks itself.
| Plain lock | Read-write lock | Snapshot swap | StampedLock | |
|---|---|---|---|---|
| Does a read wait for other reads? | Yes | No | No | No |
| Does a read wait for a write? | Yes | Yes | No; it reads the old snapshot | Only if the write overlapped it |
| Cost of a write | Change in place | Change in place, after the readers leave | Copy the whole table | Change in place |
| Several fields at one version? | Yes | Yes | Yes | Yes, after validate |
| The usual bug | A method that skips the lock | A write under the read lock | Reading the reference twice in one answer | Using values before validate |
| Fits | Short reads | Long reads, rare writes | Small tables, very rare writes | A few fields read very often |
A short way to say it: a read-write lock makes a writer wait for the readers, and a snapshot swap makes the readers never wait for the writer.
In an interview
The pattern appears in questions about a configuration service, a feature-flag or rules engine, a price list, a cache with rare invalidation, and "implement a read-write lock".
A good order for presenting it:
- Say how often each side happens. "Every request reads the flags, and an admin changes them a few times a day."
- Draw who may be inside: many readers, or one writer. Name what one read must see consistently.
- Then write it: the two sides of
ReentrantReadWriteLock, afinallyaround every release, and the change set under the write lock. Then say fair or not, and why. - Offer the alternative: a snapshot swapped through an
AtomicReference, and when it beats the lock.
Common mistakes:
- A write under the read lock. A counter or a "last seen" time updated by a read corrupts the map, and no test that runs one thread catches it.
- Upgrading. Asking for the write lock while holding the read lock waits for ever.
- Checking under the read lock and acting under the write lock without checking again. Another thread may have acted in the gap.
- Two locked calls where one is needed. Two separate
isEnabledcalls can straddle a change set. - A read-write lock around a short read. The bookkeeping can cost more than the wait it saves.
Summary
- Use a read-write lock when a table is read far more often than it changes, and reads are long enough to be worth running together.
- Every method that only reads takes the read lock, every method that changes anything takes the write lock, and every release sits in a
finally. - Read several fields under one read lock to see one version, and apply a change set under one write lock so nobody sees half of it.
- Choose fair mode when a write must get in under constant reads, and never ask for the write lock while holding the read lock.
- Downgrade, by taking the read lock before letting go of the write lock, to read exactly what you wrote while letting other readers in.
- For small tables with very rare writes, an immutable snapshot swapped through an
AtomicReferenceis simpler, and readers never wait.