CKTIS / Java
Read-write locks: readLock(), writeLock(), lock(), and unlock()
Several threads can read shared data at once, but writing requires exclusive access. Selecting a lock does not acquire it.
Version: Java SE 21
Syntax
// java.util.concurrent.locks.ReadWriteLock
Lock readLock();
Lock writeLock();
// java.util.concurrent.locks.Lock
void lock();
void unlock();In Java SE 21, ReadWriteLock and Lock are interfaces in java.util.concurrent.locks. The ReadWriteLock.readLock/writeLock methods return the associated Lock objects; they do not acquire them. Use one shared ReadWriteLock instance for the state: take its read lock for read-only operations and its write lock for changes. Several threads can hold the read lock at once. While one thread holds the write lock, no other thread can acquire either lock.
The Lock.lock/unlock methods take no arguments and return void. Call lock() before entering try: if the lock is unavailable, the thread waits to acquire it. Call unlock() on the same Lock in finally so it is released even if the protected code throws. The example uses no-argument tryLock(), which does not wait: it returns true if it acquired the lock and false otherwise. Release only after a successful acquisition.
After the write lock is released, a thread that later acquires the associated read lock sees the updates made under the write lock. The locks cannot protect code that accesses the state without using them.
With ReentrantReadWriteLock, the thread must match each acquisition with one unlock(); releasing a lock it does not hold throws IllegalMonitorStateException. Do not try to acquire the write lock while holding only the read lock: lock() will not return. Release the read lock, acquire the write lock, and recheck the state because it may have changed in between. In the other direction, you can acquire the read lock while still holding the write lock and then release the write lock.
Examples
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockDemo {
private final ReadWriteLock rw = new ReentrantReadWriteLock();
private final Lock read = rw.readLock();
private final Lock write = rw.writeLock();
private int value = 0;
public static void main(String[] args) throws InterruptedException, ExecutionException {
new ReadWriteLockDemo().run();
}
private void run() throws InterruptedException, ExecutionException {
read.lock();
try {
System.out.println("read lock held: " + probeFromAnotherThread());
} finally {
read.unlock();
}
write.lock();
try {
value = 10;
System.out.println("write lock held: " + probeFromAnotherThread());
} finally {
write.unlock();
}
int snapshot;
read.lock();
try {
snapshot = value;
} finally {
read.unlock();
}
System.out.println("read after write: " + snapshot);
}
private String probeFromAnotherThread() throws InterruptedException, ExecutionException {
FutureTask<String> probe = new FutureTask<>(() -> {
String snapshot = "blocked";
if (read.tryLock()) {
try {
snapshot = Integer.toString(value);
} finally {
read.unlock();
}
}
return "reader=" + snapshot + ", writer=" + canAcquireNow(write);
});
new Thread(probe).start();
return probe.get();
}
private static boolean canAcquireNow(Lock lock) {
if (!lock.tryLock()) {
return false;
}
try {
return true;
} finally {
lock.unlock();
}
}
}Result
read lock held: reader=0, writer=false write lock held: reader=blocked, writer=false read after write: 10
While the main thread holds the read lock, a second thread reads `0` but cannot acquire the write lock. After the main thread sets `10` and while it still holds the write lock, both attempts by the second thread fail. Once the write lock is released, a protected read gives `10`. `FutureTask.get()` keeps that order without sleeps.
Related lessons
- Java · Lesson 29 · Advanced · Version: 2