Multithreading: ReadWriteLock separates read and write access

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.

Code
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);
Output
Read under the read lock: 42
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms