A ReadWriteLock is a more advanced synchronization mechanism in Java that improves performance in read-heavy multithreaded applications.
Let’s dive in step by step:
📘 What is ReadWriteLock?
A ReadWriteLock allows:
- Multiple threads to read simultaneously (as long as no one is writing)
- Only one thread to write at a time (and blocks all readers)
📌 It splits access into a read lock and a write lock, optimizing concurrency when reads are frequent and writes are rare.
✅ Interface & Implementation
Java provides ReadWriteLock as an interface and its main implementation:
ReadWriteLock lock = new ReentrantReadWriteLock();
Lock readLock = lock.readLock();
Lock writeLock = lock.writeLock();
🧠 Why Use It?
- Using a normal
ReentrantLock(orsynchronized) means all threads are blocked, even if they just want to read. - With
ReadWriteLock, multiple readers don’t block each other.
🔧 Example
import java.util.concurrent.locks.*;
public class SharedData {
private int data = 0;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
public void write(int value) {
writeLock.lock();
try {
data = value;
System.out.println("Wrote: " + value);
} finally {
writeLock.unlock();
}
}
public int read() {
readLock.lock();
try {
System.out.println("Read: " + data);
return data;
} finally {
readLock.unlock();
}
}
}
🧪 Behavior
| Scenario | Allowed? |
|---|---|
| Multiple readers | ✅ Yes |
| Reader + Writer | ❌ No |
| Multiple writers | ❌ No |
| Writer blocks all others | ✅ Yes |
⚠️ Caveats
- Be careful of starvation: a constant stream of readers can block writers.
- Use
ReentrantReadWriteLock(true)for fairness to prevent that.
new ReentrantReadWriteLock(true); // Fair mode
🧠 When to Use
Use ReadWriteLock when:
- You have many threads reading, few writing
- You want to maximize concurrency without sacrificing thread safety