A ReentrantReadWriteLock lets any number of readers hold the read lock together, but a writer needs the exclusive write lock. Here a write under writeLock() is followed by a read under readLock(), each properly paired with unlock in a finally block.
ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
int[] shared = { 0 };
rw.writeLock().lock();
try {
shared[0] = 42;
} finally {
rw.writeLock().unlock();
}
rw.readLock().lock();
int snapshot;
try {
snapshot = shared[0];
} finally {
rw.readLock().unlock();
}
System.out.println("Read under the read lock: " + snapshot);
Read under the read lock: 42
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27