Sub topic 18
Read-Write Locks for Read-Heavy Data
Some shared data is read often but changed rarely, such as a price list, a settings table, or a cache. A normal lock lets only one thread in at a time, so readers wait for each other even though reading changes nothing. A read-write lock fixes this.
What a Read-Write Lock Is
A read-write lock is a lock with two parts:
- The read lock can be held by many threads at once, as long as no thread is writing.
- The write lock can be held by only one thread, and only when no thread holds the read lock.
Several readers can share the data safely. A writer gets the data to itself.
In Java, the interface is ReadWriteLock. The usual class that implements it is ReentrantReadWriteLock. "Reentrant" means a thread that already holds a lock can lock it again without blocking itself, the same as with ReentrantLock.
| Who holds it now | Another reader asks | A writer asks |
|---|---|---|
| Nobody | Allowed | Allowed |
| One or more readers | Allowed | Waits |
| One writer | Waits | Waits |
A Worked Example
This price table lets many threads look up prices at the same time. Changing a price locks everyone else out.
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class PriceTable {
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Map<String, Integer> prices = new HashMap<>();
public Integer get(String item) {
rwLock.readLock().lock();
try {
return prices.get(item);
} finally {
rwLock.readLock().unlock();
}
}
public void set(String item, int price) {
rwLock.writeLock().lock();
try {
prices.put(item, price);
} finally {
rwLock.writeLock().unlock();
}
}
public static void main(String[] args) throws InterruptedException {
PriceTable table = new PriceTable();
table.set("apple", 3);
Runnable reader = () -> {
for (int i = 0; i < 1000; i++) {
table.get("apple");
}
};
Thread r1 = new Thread(reader);
Thread r2 = new Thread(reader);
Thread w = new Thread(() -> table.set("apple", 4));
r1.start();
r2.start();
w.start();
r1.join();
r2.join();
w.join();
System.out.println("apple costs " + table.get("apple"));
}
}Each lock() call is paired with an unlock() in a finally block. A finally block always runs, even if the code before it throws an exception, so the lock is always released.
When to Use One
A read-write lock does more bookkeeping than a plain lock. It is worth it only when:
- reads happen far more often than writes, and
- each read takes long enough that readers would otherwise pile up waiting.
For a small counter or a map that is written often, a plain lock or a ConcurrentHashMap is usually simpler and just as fast.
Exercise
In PriceTable, two threads are inside get() and a third thread calls set(). What happens to the third thread, and why?
Show answer
The third thread waits. The write lock is granted only when no thread holds the read lock, so set() blocks until both readers finish get() and release their read locks. Then it gets the write lock and updates the map alone.
Exercise
A method holds the read lock, sees a missing price, and then calls writeLock().lock() before releasing the read lock. What goes wrong?
Show answer
The thread deadlocks with itself. The write lock waits until every reader leaves, but this thread is still a reader. The fix is to call readLock().unlock() first, then writeLock().lock(), and check the price again because another thread may have added it in between.