ReadWriteLock for Reader-Writer Scenarios
Use ReadWriteLock to allow concurrent reads while ensuring exclusive writes in a cache.
The Reader-Writer Problem
Multiple threads can safely read shared data simultaneously. But writing requires exclusive access — no concurrent reads or writes. A ReadWriteLock models this: multiple concurrent readers OR one exclusive writer.
import java.util.concurrent.locks.*;
ReadWriteLock rwLock = new ReentrantReadWriteLock();
Lock readLock = rwLock.readLock();
Lock writeLock = rwLock.writeLock();Read Lock: Shared Access
Multiple threads can hold the read lock simultaneously as long as no thread holds the write lock:
class ReadableCache {
private final Map<String, String> cache = new HashMap<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
String get(String key) {
lock.readLock().lock();
try {
return cache.get(key); // concurrent reads OK
} finally {
lock.readLock().unlock();
}
}
}All lessons in this course
- ReentrantLock vs synchronized
- ReadWriteLock for Reader-Writer Scenarios
- Atomic Variables: Lock-Free Updates
- StampedLock and Optimistic Reads