ReadWriteLock
A ReadWriteLock is a pair of locks: many threads may hold the read lock together, but the write lock is exclusive. Use it when reads dominate and the critical section is large enough that the extra bookkeeping pays off.
Detailed Explanation
synchronized and ReentrantLock are exclusive. If twenty threads only read a cache, they still queue. ReadWriteLock (usually ReentrantReadWriteLock) lets those twenty overlap. A writer waits until readers drain, then runs alone. New readers wait while a writer is in line or running, depending on fairness and the implementation's policy.
You acquire rw.readLock().lock() around reads and rw.writeLock().lock() around writes, always in finally. The read lock is reentrant for the same thread. A thread that holds the write lock can acquire the read lock (downgrade). The reverse, upgrade from read to write, is not supported and deadlocks if you try: you would wait for yourself to drop the read lock.
Fairness is a constructor flag. Non-fair mode can let writers barge and reduce writer starvation or, in other schedules, let readers starve writers. Measure. The JDK implementation is not a magic speedup on a tiny int. The lock's state machine costs more than a synchronized increment.
You reach for a read-write lock when a shared structure is read often, written rarely, and the read work is heavier than a map lookup (copying a snapshot, walking a tree). You keep ConcurrentHashMap when the structure is a map; it is already concurrent. You keep a single exclusive lock when writes are common or the section is a few field reads.
The cost of holding the read lock while calling out to code that wants the write lock is a deadlock. The cost of a long-held read lock is writers paused until every reader leaves. Keep sections short. Do not perform I/O under either lock unless that I/O is the resource you are protecting.
StampedLock is a later, more fragile alternative with optimistic reads. Do not start there.
Code Examples
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Snapshot {
private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
private String value = "init";
public String read() {
rw.readLock().lock();
try {
return value;
} finally {
rw.readLock().unlock();
}
}
public void write(String v) {
rw.writeLock().lock();
try {
value = v;
} finally {
rw.writeLock().unlock();
}
}
public static void main(String[] args) {
Snapshot s = new Snapshot();
s.write("ok");
System.out.println(s.read()); // prints: ok
}
}Common Gotchas
Upgrading read → write deadlocks
drop the read lock first, or take the write lock from the start.
A cheap read plus a `ReadWriteLock` can be slower than `synchronized`
profile.
Downgrade write → read is allowed
acquire read, then release write, if you need to.
Do not call into foreign code that might want the write lock while you hold the
Do not call into foreign code that might want the write lock while you hold the read lock