A thread holding a ReentrantReadWriteLock write lock can acquire its read lock before releasing the write lock, preserving read protection across the transition.
Java ReentrantReadWriteLock downgrade: publish then keep a read lock
Avoid an unlocked gap
A writer may need to update a report and then inspect the committed value while excluding other writers. Acquire the read lock before releasing the write lock. If the write lock is released first, another writer may intervene before the read begins. The fixture prints the new revision while a read hold remains active.
A read-to-write upgrade is different and is not generally available by simply acquiring the write lock while holding a read lock. Release and retry with a version check, or use a design with a single owner. Optimistic reads offer another policy with explicit validation.
Release every hold
Each acquisition needs its own finally path. Leaking a read hold blocks future writers even after the update is complete. Keep I/O and callbacks outside the critical section when their duration is not bounded.
Working program
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class PricingRevisionGate {
public static void main(String[] args) {
ReentrantReadWriteLock guard = new ReentrantReadWriteLock();
int[] revision = {47};
guard.writeLock().lock();
try {
revision[0] = 82;
guard.readLock().lock();
} finally {
guard.writeLock().unlock();
}
try {
System.out.println("revision=" + revision[0]);
System.out.println("read holds=" + guard.getReadHoldCount());
} finally {
guard.readLock().unlock();
}
System.out.println("read holds=" + guard.getReadHoldCount());
}
}Output
revision=82
read holds=1
read holds=0Cost and ownership
The transition adds one lock acquisition without copying the report. Throughput depends on contention and how long readers hold the lock; a long read can delay every writer. The program owns one lock and one revision cell.
Common Mistakes
- Do not release the write lock before taking the read lock when a gap is forbidden.
- Do not assume a read lock can be upgraded to a write lock.
- Do not forget to release the downgraded read hold.
Read next
Java ReentrantLock: protect a complete state transition, Java StampedLock optimistic reads: validate before publishing state, Java conditions: protected predicates and timed waiting, volatile counter lost update.
