CKTIS / Java
util.concurrent.locks.ReentrantReadWriteLock: practical reference
util.concurrent.locks.ReentrantReadWriteLock: practical reference: ReentrantReadWriteLock provides a shared read lock and an exclusive write lock with reentrancy.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.util.concurrent.locks.ReentrantReadWriteLockReentrantReadWriteLock provides a shared read lock and an exclusive write lock with reentrancy.
Use it for read-mostly state when multiple readers can safely proceed together.
Upgrading from a read lock to the write lock is unsupported; release the read lock and recheck state after acquiring write.
A writer can downgrade by taking the read lock first; only the write lock creates a Condition, and untimed tryLock ignores fairness.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var lock = new java.util.concurrent.locks.ReentrantReadWriteLock();
lock.writeLock().lock();
try { System.out.println(lock.isWriteLockedByCurrentThread()); } finally { lock.writeLock().unlock(); }
}
}
Result
true
The example exercises the documented element in a small deterministic program and compares exact standard output.