ReentrantReadWriteLock maintains a pair of locks: one for read-only operations and one for write operations. Multiple threads can hold the read lock simultaneously (shared access), but the write lock is exclusive.
Code example of read-write lock behaviour
class Main { void main() { Cache cache = new Cache(); // Multiple readers can access simultaneously new Thread(() -> cache.read("key1")).start(); new Thread(() -> cache.read("key2")).start(); new Thread(() -> cache.read("key1")).start(); // Writer gets exclusive access new Thread(() -> cache.write("key3", "value3")).start(); }}class Cache { private Map<String, String> data = new HashMap<>(); private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); private Lock readLock = rwLock.readLock(); private Lock writeLock = rwLock.writeLock(); public String read(String key) { readLock.lock(); // Multiple threads can hold this try { System.out.println(Thread.currentThread().getName() + " reading"); return data.get(key); } finally { readLock.unlock(); } } public void write(String key, String value) { writeLock.lock(); // Exclusive access - blocks all readers and writers try { System.out.println(Thread.currentThread().getName() + " writing"); data.put(key, value); } finally { writeLock.unlock(); } }}
Lock Acquisition Rules
Multiple readers: Can hold the read lock simultaneously
Single writer: Write lock is exclusive - blocks all readers and writers
No mixed access: Cannot have readers and writers at the same time
When to Use
Best suited for read-heavy workloads where reads significantly outnumber writes.
If writes are frequent, the overhead of managing two locks may outweigh the benefits.
Consider using a simple ReentrantLock instead for write-heavy scenarios.
Fairness
Like ReentrantLock, supports an optional fairness parameter: new ReentrantReadWriteLock(boolean fair)
This prevents barging, reducing the probability of thread starvation.
However, it doesn’t prevent starvation as that ultimately depends on the OS thread scheduler.
Fair mode caveats:
Prevents writer starvation (readers won’t monopolise the lock indefinitely)
NOT Allowed: Read lock → Write lock (causes deadlock)
readLock.lock();writeLock.lock(); // DEADLOCK - this will block forever
Thread States
Built on AbstractQueuedSynchronizer (AQS) using park/unpark mechanisms.
Threads waiting for locks are in WAITING or TIMED_WAITING states (NEVER BLOCKED).