ReadWriteLock for read-heavy data
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Reading shared data does not change it, so two readers can safely work at the same time. Only a writer needs the data to itself. A read-write lock uses exactly this rule: many readers together, or one writer alone.
Many readers or one writer
A ReadWriteLock is a pair of locks on the same data: a shared read lock that many threads can hold together, and an exclusive write lock that only one thread can hold, with no readers inside.
A ReadWriteLock is a pair of locks: readLock() and writeLock(). The read lock is shared: any number of threads can hold it at once. The write lock is exclusive: while a thread holds it, nobody else can hold either lock.
Example 1 · Three readers inside together, the writer kept out
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadersTogetherDemo { static final ReentrantReadWriteLock rw = new ReentrantReadWriteLock(); static volatile boolean checked = false;
public static void main(String[] args) throws InterruptedException { Thread[] readers = new Thread[3]; for (int i = 0; i < 3; i++) { readers[i] = new Thread(() -> { rw.readLock().lock(); try { while (!checked) { // keep reading the timetable Thread.sleep(1); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { rw.readLock().unlock(); } }, "reader-" + (i + 1)); readers[i].start(); }
while (rw.getReadLockCount() < 3) { // wait until all readers are inside Thread.sleep(1); } System.out.println("Readers holding the read lock: " + rw.getReadLockCount()); boolean writerIn = rw.writeLock().tryLock(); System.out.println("Writer could enter now? " + writerIn); if (writerIn) { rw.writeLock().unlock(); } checked = true; // let the readers finish
for (Thread r : readers) { r.join(); } boolean got = rw.writeLock().tryLock(); System.out.println("Writer could enter after readers left? " + got); if (got) { rw.writeLock().unlock(); } }}Readers holding the read lock: 3 Writer could enter now? false Writer could enter after readers left? true
What this code does
- All three readers hold the read lock at the same moment; none of them waits for another. Each stays inside until
mainhas finished checking, so the output is the same on every run. - While they are inside, the write lock is not available, so
tryLock()returnsfalse. - Once every reader has left, the writer gets the lock at once.
Example 2 · Slow reads: one lock versus a read lock
import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadSpeedDemo { static long timeFourReaders(Lock lock) throws InterruptedException { Thread[] readers = new Thread[4]; long start = System.nanoTime(); for (int i = 0; i < 4; i++) { readers[i] = new Thread(() -> { lock.lock(); try { Thread.sleep(100); // one slow read } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { lock.unlock(); } }, "reader-" + (i + 1)); readers[i].start(); } for (Thread r : readers) { r.join(); } return (System.nanoTime() - start) / 1_000_000; }
public static void main(String[] args) throws InterruptedException { long plain = timeFourReaders(new ReentrantLock()); long shared = timeFourReaders(new ReentrantReadWriteLock().readLock()); System.out.println("4 readers, one ReentrantLock: " + plain + " ms"); System.out.println("4 readers, shared read lock: " + shared + " ms"); }}4 readers, one ReentrantLock: 452 ms 4 readers, shared read lock: 108 ms
What this code does
- With one
ReentrantLock, the four 100 ms reads happen one after another: a little over 400 ms in total, because starting threads also takes time. - With the read lock, all four read at the same time: a little over 100 ms. Your exact numbers will differ from run to run.
readLock()returns a normalLock, so the same method works with both.
The three pairings:
- Reader and reader: can run together.
- Reader and writer: one waits for the other.
- Writer and writer: one waits for the other.
So a writer waits until all readers have left, and readers wait while a writer is inside. Each half is used with the usual lock, try, finally pattern. This helps when reads are much more common than writes and each read takes a while. Exam results, train timetables and app settings are read thousands of times for every change.
ReentrantReadWriteLock for a settings cache
ReentrantReadWriteLock is the standard ReadWriteLock class, in java.util.concurrent.locks. Like ReentrantLock, it is reentrant and can be made fair with new ReentrantReadWriteLock(true).
Example 3 · A settings cache with ReentrantReadWriteLock
import java.util.HashMap;import java.util.Map;import java.util.TreeMap;import java.util.concurrent.locks.ReentrantReadWriteLock;
class AppSettings { private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock(); private final Map<String, String> values = new HashMap<>();
String get(String key) { rw.readLock().lock(); try { return values.getOrDefault(key, "not set"); } finally { rw.readLock().unlock(); } }
void put(String key, String value) { rw.writeLock().lock(); try { values.put(key, value); } finally { rw.writeLock().unlock(); } }
Map<String, String> snapshot() { rw.readLock().lock(); try { return new TreeMap<>(values); // a sorted copy, safe to use later } finally { rw.readLock().unlock(); } }}
public class SettingsCacheDemo { public static void main(String[] args) throws InterruptedException { AppSettings settings = new AppSettings(); settings.put("theme", "light"); settings.put("language", "English");
Thread admin = new Thread(() -> { settings.put("theme", "dark"); settings.put("maxUploadMb", "25"); }, "admin");
Thread[] users = new Thread[2]; for (int u = 0; u < 2; u++) { users[u] = new Thread(() -> { for (int i = 0; i < 10_000; i++) { settings.get("theme"); // light or dark, depending on timing } }, "user-" + (u + 1)); }
admin.start(); for (Thread t : users) { t.start(); } admin.join(); for (Thread t : users) { t.join(); } System.out.println("Settings now: " + settings.snapshot()); System.out.println("Language: " + settings.get("language")); System.out.println("Font size: " + settings.get("fontSize")); }}Settings now: {language=English, maxUploadMb=25, theme=dark}
Language: English
Font size: not setWhat this code does
- Two user threads read the theme 10,000 times each under the shared read lock; the admin thread changes settings under the write lock.
- Whether a read sees
lightordarkdepends on timing, so the readers print nothing. The final settings are the same on every run. snapshot()copies the map into aTreeMapunder the read lock, so the caller gets sorted data it can use without any lock.
The usual design wraps a plain collection, such as a HashMap. Every method that only reads takes readLock(); every method that changes the map takes writeLock(). The map itself is never shared directly. A method that returns data should return a copy made under the read lock, not the map itself. Otherwise the caller would read the map later without any lock.
A read lock cannot be upgraded to a write lock
Upgrading means taking the write lock while you still hold the read lock. ReentrantReadWriteLock does not allow it. The write lock waits until every reader has left, and that includes you, so writeLock().lock() waits forever. writeLock().tryLock() simply returns false.
Example 4 · The upgrade trap, and the release-then-check-again fix
import java.util.HashMap;import java.util.Map;import java.util.concurrent.locks.ReentrantReadWriteLock;
class ResultCache { private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock(); private final Map<String, String> results = new HashMap<>(); private int databaseLoads = 0;
boolean tryToUpgrade() { rw.readLock().lock(); try { // writeLock().lock() here would wait forever: it waits for all readers, including us boolean got = rw.writeLock().tryLock(); if (got) { rw.writeLock().unlock(); } return got; } finally { rw.readLock().unlock(); } }
String get(String roll) { rw.readLock().lock(); try { String r = results.get(roll); if (r != null) { return r; } } finally { rw.readLock().unlock(); // release before asking to write }
rw.writeLock().lock(); try { String r = results.get(roll); if (r == null) { databaseLoads++; r = "Roll " + roll + ": PASS"; // pretend database lookup results.put(roll, r); } return r; } finally { rw.writeLock().unlock(); } }
int loads() { rw.readLock().lock(); try { return databaseLoads; } finally { rw.readLock().unlock(); } }}
public class UpgradeTrapDemo { public static void main(String[] args) { ResultCache cache = new ResultCache(); System.out.println("Write lock while holding the read lock? " + cache.tryToUpgrade()); System.out.println(cache.get("21CS042")); System.out.println(cache.get("21CS042")); System.out.println("Database loads: " + cache.loads()); }}Write lock while holding the read lock? false Roll 21CS042: PASS Roll 21CS042: PASS Database loads: 1
What this code does
- Inside the read lock,
writeLock().tryLock()returnsfalse. Alock()call in the same place would hang the thread for good, with no error. getreleases the read lock, takes the write lock, and looks in the map again, because another thread may have loaded the same roll number in the gap.- The second call finds the result under the read lock, so the database is used only once.
Example 5 · Downgrading: write lock to read lock without a gap
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class DowngradeDemo { static final ReentrantReadWriteLock rw = new ReentrantReadWriteLock(); static int ticketPrice = 450;
public static void main(String[] args) { rw.writeLock().lock(); ticketPrice = 520; // change under the write lock rw.readLock().lock(); // allowed: take the read lock too rw.writeLock().unlock(); // now only the read lock is held try { System.out.println("Write locked? " + rw.isWriteLocked()); System.out.println("Read locks held: " + rw.getReadLockCount()); System.out.println("Price I just set: " + ticketPrice); } finally { rw.readLock().unlock(); } System.out.println("After unlock, read locks held: " + rw.getReadLockCount()); }}Write locked? false Read locks held: 1 Price I just set: 520 After unlock, read locks held: 0
What this code does
- The thread takes the read lock before letting go of the write lock, so no writer can slip in between.
- Other readers can now enter, while this thread keeps reading the value it just wrote.
- The opposite order (read, then write) is the upgrade from Example 4, which is not allowed.
The correct way is to release the read lock, take the write lock, and check again. Another thread may have done the same change while you held no lock. The other direction, downgrading, is allowed: while holding the write lock you may take the read lock, then release the write lock. You keep reading with no gap in which a writer could change the data.
Find the bug
Spot the read-write lock bug
Select the line that is wrong.
This should update the price, but the thread hangs forever. Which line is wrong?
Round 1 of 2When a plain lock is faster
A read-write lock has extra bookkeeping. It must count readers and handle two kinds of waiters, so each lock and unlock costs more than with a ReentrantLock or synchronized.
That cost pays off only when readers really overlap. In these cases a plain lock is usually as fast or faster:
- Each read is tiny, such as reading one
int: the lock costs more than the read. - Writes are frequent: readers keep waiting for writers anyway.
- Few threads read at the same time, so there is little to share.
- A ready-made structure fits, such as
ConcurrentHashMap(covered in the Concurrent Collections module).
StampedLock, which offers optimistic reads, but it is not reentrant and is harder to use correctly.Next step
Check your understanding
12 quick questions