Sub topic 18
Read-Write Locks for Read-Heavy Data
Why One Lock Can Be Too Strict
A plain lock, such as synchronized or ReentrantLock, lets only one thread in at a time. That is safe, but sometimes it is stricter than it needs to be.
Think of a price list in a shop's app. Hundreds of threads read prices every second, and an admin changes a price only a few times a day. Reading does not change anything. So two readers looking at the list at the same moment cannot break it. With a plain lock, though, every reader still waits in line behind every other reader.
A read-write lock fixes this. It is a lock with two parts:
- A read lock. Many threads can hold it at the same time, as long as no thread is writing.
- A write lock. Only one thread can hold it, and only when no other thread holds either lock.
Data that is read-heavy is read much more often than it is changed. For that kind of data, a read-write lock lets readers run side by side and still keeps writers safe.
The Rules in One Table
The table shows whether a thread can get the lock it asks for, based on what other threads already hold.
| Already held by other threads | Asking for read lock | Asking for write lock |
|---|---|---|
| Nothing | Yes | Yes |
| One or more read locks | Yes | No, must wait |
| A write lock | No, must wait | No, must wait |
Readers share with readers, and nobody shares with a writer. The write lock is exclusive, meaning one holder at a time. The read lock is shared, meaning many holders at once.
ReadWriteLock and ReentrantReadWriteLock
Java puts this idea in the package java.util.concurrent.locks.
ReadWriteLockis an interface, a list of methods a class promises to provide. It has two methods:readLock()andwriteLock(). Each one returns a normalLockobject.ReentrantReadWriteLockis the class most people use. "Reentrant" means a thread that already holds a lock can lock it again without blocking itself, just likesynchronizedandReentrantLock.
You use each part like a ReentrantLock: call lock(), do the work inside try, and call unlock() in finally.
A Worked Example: A Shared Price Table
This class keeps prices in a HashMap. A HashMap is not thread-safe by itself, so every access goes through the read-write lock. The main method starts one writer and three readers to show it working.
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 Map<String, Integer> prices = new HashMap<>();
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
public Integer get(String item) {
rwLock.readLock().lock();
try {
return prices.get(item);
} finally {
rwLock.readLock().unlock();
}
}
public void put(String item, int price) {
rwLock.writeLock().lock();
try {
prices.put(item, price);
} finally {
rwLock.writeLock().unlock();
}
}
public int priceOrAdd(String item, int defaultPrice) {
rwLock.readLock().lock();
try {
Integer p = prices.get(item);
if (p != null) {
return p;
}
} finally {
rwLock.readLock().unlock();
}
rwLock.writeLock().lock();
try {
Integer p = prices.get(item); // check again: another thread may have added it
if (p == null) {
prices.put(item, defaultPrice);
p = defaultPrice;
}
return p;
} finally {
rwLock.writeLock().unlock();
}
}
public static void main(String[] args) throws InterruptedException {
PriceTable table = new PriceTable();
table.put("apple", 100);
Thread writer = new Thread(() -> {
for (int i = 1; i <= 5; i++) {
table.put("apple", 100 + i);
}
});
Runnable readTask = () -> {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ " sees apple = " + table.get("apple"));
}
};
Thread r1 = new Thread(readTask, "reader-1");
Thread r2 = new Thread(readTask, "reader-2");
Thread r3 = new Thread(readTask, "reader-3");
writer.start();
r1.start();
r2.start();
r3.start();
writer.join();
r1.join();
r2.join();
r3.join();
System.out.println("Final apple = " + table.get("apple"));
System.out.println("Pear = " + table.priceOrAdd("pear", 80));
}
}When you run it, the readers print values between 100 and 105, in an order that changes from run to run. Every value they print is a real price that the table actually held. After all threads finish, the final price is always 105, and pear is added with price 80.
Here is what each method does:
gettakes the read lock, so many threads can call it at once.puttakes the write lock, so it waits until all readers leave. While it holds the lock, new readers wait.priceOrAddreads first. If the item is missing, it lets go of the read lock, takes the write lock, and checks again before adding.
The second check matters. Between releasing the read lock and getting the write lock, another thread might add the same item. Without the second check, you would get the check-then-act race from earlier chapters.
Edge Cases and Gotchas
Going down is allowed
The opposite direction works. A thread holding the write lock may also take the read lock, then release the write lock. This is called downgrading. It lets a writer finish an update and then keep reading the data without letting another writer in between.
Always unlock in finally
If code inside the lock throws an exception and you skip unlock(), the lock stays held forever. Every other thread that wants it will wait forever. Put unlock() in a finally block every time.
Unlock the same part you locked
readLock().lock() must be paired with readLock().unlock(), and the write lock with the write lock. Mixing them up throws an IllegalMonitorStateException, which is the error Java raises when a thread releases a lock it does not hold.
Fairness
new ReentrantReadWriteLock() creates a non-fair lock. A non-fair lock does not promise to serve waiting threads in arrival order. It is usually faster. new ReentrantReadWriteLock(true) creates a fair lock, which gives the lock to the thread that has waited longest. A fair lock stops any one thread from waiting too long, but it is slower. Start with the default and switch to fair only if you see writers waiting much too long.
It is not always faster
A read-write lock does more bookkeeping than a plain lock. If each read is tiny, like reading one field, or if writes are frequent, the extra cost can make it slower than synchronized. It pays off when reads are many, take some time, and writes are rare.
When to Choose It
| Situation | Good choice |
|---|---|
| Reads and writes about equally common | `synchronized` or `ReentrantLock` |
| Many reads, rare writes, data is a map | `ConcurrentHashMap` |
| Many reads, rare writes, custom data structure | `ReentrantReadWriteLock` |
| Data never changes after creation | An immutable object, no lock needed |
For a simple map, ConcurrentHashMap is often the easier and faster tool. Use a read-write lock when you protect something more complex, such as several fields that must change together.
Exercise
A thread holds the read lock of a ReentrantReadWriteLock and then calls writeLock().lock() on the same lock. What happens, and how do you fix it?
Show answer
The thread blocks forever. The write lock waits until no thread holds the read lock, and this thread is itself still holding the read lock. To fix it, release the read lock first, then take the write lock, and check the data again, because another thread may have changed it in between.
Exercise
Your app has a settings object that 50 threads read constantly. It is updated once an hour, and each update changes three fields together. Which tool fits best: synchronized, ConcurrentHashMap, or ReentrantReadWriteLock? Why?
Show answer
ReentrantReadWriteLock. Reads are far more common than writes, so letting readers share the lock removes waiting between them. The three fields must change together, so a single map-entry update from ConcurrentHashMap does not cover the whole change, while the write lock keeps all three updates together. Another good option is to replace the whole settings object with a new immutable one.