CKTIS / Java
ReadWriteLock — separate read and write locks
ReadWriteLock exposes associated read and write locks: multiple readers can share access, while writing requires exclusive access. Learn readLock() and writeLock(), visibility guarantees, and safe lock release.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
ReadWriteLock rw = new ReentrantReadWriteLock();
Lock read = rw.readLock();
Lock write = rw.writeLock();
read.lock();
try {
// Read protected state.
} finally {
read.unlock();
}
write.lock();
try {
// Modify protected state.
} finally {
write.unlock();
}java.util.concurrent.locks.ReadWriteLock is an interface for a pair of associated locks. ReadWriteLock.readLock() returns a Lock for reading, and ReadWriteLock.writeLock() returns one for writing; calling these methods does not acquire a lock. Multiple readers can operate concurrently when there is no writer; writing is exclusive.
Call lock() on the returned object before the protected section, and unlock() in finally, placing lock() before try. All accesses to protected state must follow the same protocol. Do not modify state under the read lock. Successfully acquiring the read lock makes changes published by an earlier release of the associated write lock visible.
A typical implementation is ReentrantReadWriteLock. Its default mode does not guarantee fair ordering. Do not attempt to acquire the write lock while still holding the read lock: this implementation does not support that upgrade. After releasing the read lock and acquiring the write lock, recheck the condition because the state may have changed. These implementation policies are not additional guarantees of the interface.
Consider this approach for frequent reads and less frequent writes, but overhead can outweigh the benefits; measure performance. The example protects value and deterministically prints 42. Sequential calls in main demonstrate API usage, not parallel execution or correctness under every thread interleaving.
Examples
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Main {
private final ReadWriteLock rw = new ReentrantReadWriteLock();
private int value;
public int get() {
Lock read = rw.readLock();
read.lock();
try {
return value;
} finally {
read.unlock();
}
}
public void set(int next) {
Lock write = rw.writeLock();
write.lock();
try {
value = next;
} finally {
write.unlock();
}
}
public static void main(String[] args) {
Main cell = new Main();
cell.set(42);
System.out.println(cell.get());
}
}Result
42
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.