ReadWriteLock in Java Explained
-
Last Updated: October 7, 2026
-
By: javahandson
-
Series

Learn how ReadWriteLock in Java lets many threads read at once while writes stay exclusive. Covers read vs write locks, downgrading, and write starvation.
If your program reads shared data far more often than it writes it, a normal lock is doing more work than it should. That is exactly the gap ReadWriteLock in Java fills. It lets many threads read at the same time, while still keeping writes safe and exclusive. In this guide we will go slow, use plain language, and build the idea from the ground up.
We will assume you already know basic explicit locking. If terms like lock() and unlock() feel new, read the Locks in Java: ReentrantLock vs synchronized article first, then come back here. This piece builds directly on top of it.
Think about a simple cache. It holds some data in memory. Most of the time, threads just look things up. Once in a while, something changes and a thread updates it.
Reading does not change anything. So two threads reading the same value at the same time is totally safe. Nothing breaks. There is no race, no corruption, no surprise.
Now here is the problem with a plain lock. A synchronized block or a single ReentrantLock treats every thread the same way. It does not care whether a thread wants to read or write. Only one thread gets in at a time. Everyone else waits.
So imagine ten threads that only want to read. With one lock, nine of them sit idle while one reads. That is wasteful. Those nine reads were harmless and could have run together.
Let us say reading takes 50 milliseconds. With a single lock and ten readers, they run one by one. The last reader finishes after half a second. But if all ten read together, everyone finishes in about 50 milliseconds. Same safety, much less waiting.

This is the core insight. We do not need to block readers from other readers. We only need to block readers when a writer is busy, and block writers from everyone. That single idea is what ReadWriteLock gives us.
Say you run a web service. It keeps a map of country codes to tax rates in memory. Every incoming request reads from this map to calculate a price. That is thousands of reads per second.
How often does the tax rate change? Maybe once a day, when an admin updates it. So the ratio here is huge. You might get a million reads for every single write.
With a plain lock, every request waits its turn to read one number. Under load, that lock becomes a bottleneck. Threads pile up behind it even though they only want to peek. A read-write split removes that pileup almost entirely, because reads flow through together.
This pattern shows up everywhere. Pricing tables, feature flags, routing rules, DNS-style lookups. Whenever the data is read constantly and changed rarely, you are looking at a natural fit for a read-write lock.
In Java, ReadWriteLock is an interface. It lives in the java.util.concurrent.locks package. The idea behind it is simple. Instead of one lock, it hands you two.
The interface itself is tiny. It just has two methods, one to get each lock.
public interface ReadWriteLock {
Lock readLock();
Lock writeLock();
}Each of those returns a normal Lock object. So you already know how to use them. You call lock() to acquire and unlock() to release, just like with ReentrantLock.
ReadWriteLock is only the contract. The class you actually create is ReentrantReadWriteLock. The name tells you two things. It is reentrant, so the same thread can grab the same lock again without deadlocking itself. And it splits access into read and write.
import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; ReadWriteLock rwLock = new ReentrantReadWriteLock(); Lock readLock = rwLock.readLock(); Lock writeLock = rwLock.writeLock();
That is the whole setup. One object, two views on it. Readers use readLock. Writers use writeLock. The lock handles the rest.
What the Lock Tracks Internally
You do not need to read the source to get the idea. Behind the scenes, the lock keeps a count. It remembers how many threads currently hold the read lock. It also remembers whether a writer holds the write lock.
When a reader arrives, the lock checks one thing. Is a writer active right now? If no writer is active, it bumps the reader count and lets the thread in. If a writer is active, the reader waits.
When a writer arrives, the check is stricter. The writer can enter only when the reader count is zero and no other writer holds it. Otherwise it waits in line. This simple bookkeeping is what makes the whole read-write contract work.
Let us build a tiny thread-safe store. It keeps a single number. Many threads can read it together. Only one thread can change it at a time.
import java.util.concurrent.locks.*;
public class SharedCounter {
private int value = 0;
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock readLock = rwLock.readLock();
private final Lock writeLock = rwLock.writeLock();
public int read() {
readLock.lock(); // many readers allowed together
try {
return value;
} finally {
readLock.unlock(); // always release in finally
}
}
public void write(int newValue) {
writeLock.lock(); // only one writer, no readers
try {
value = newValue;
} finally {
writeLock.unlock();
}
}
}Notice the pattern. We always unlock inside a finally block. If the code throws an exception, the lock still gets released. Forgetting this is one of the most common bugs with explicit locks, so make it a habit.
The Same Idea as a Small Cache
Now let us make it feel real. Here is the tax-rate cache from our earlier scenario. Many threads look up rates. One admin thread updates them.
import java.util.*;
import java.util.concurrent.locks.*;
public class TaxRateCache {
private final Map<String, Double> rates = new HashMap<>();
private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock read = rwLock.readLock();
private final Lock write = rwLock.writeLock();
// Called thousands of times per second by request threads.
public Double getRate(String country) {
read.lock();
try {
return rates.get(country);
} finally {
read.unlock();
}
}
// Called rarely, when an admin changes a rate.
public void updateRate(String country, double rate) {
write.lock();
try {
rates.put(country, rate);
} finally {
write.unlock();
}
}
}Look at getRate. Under heavy traffic, many request threads call it at once. They all share the read lock, so they do not block each other. Only updateRate takes the exclusive write lock, and that runs rarely. This is the read-write pattern doing exactly what it was built for.
| 💡 Interview Insight A common question is: what does the ‘reentrant’ in ReentrantReadWriteLock mean? Answer plainly. It means a thread that already holds a lock can acquire it again without blocking on itself. A write holder can also take the read lock (downgrade). But a thread holding only the read lock cannot jump to the write lock, since that would cause a deadlock. |
Common Mistakes to Avoid
Two small slips cause most of the pain here. Both are easy to fix once you know them.
A write done while only holding the read lock defeats the entire point. Other readers may be looking at the data at the same moment. So double-check: does this method change anything? If yes, it needs the write lock.
The two locks follow a few clear rules. Once you learn them, the whole thing clicks. Let us walk through each case.
Here is a small table that puts it all together. Think of it as the truth table for the lock.
| A thread wants to… | Someone is reading | Someone is writing | Nobody holds the lock |
|---|---|---|---|
| Read | Allowed (join in) | Must wait | Allowed |
| Write | Must wait | Must wait | Allowed |
Read that table slowly. The only green light for a writer is an empty lock. Readers get two green lights, because they can share with each other.
Rules are easier to trust when you watch them play out. Let us follow four threads over time. Call them R1, R2 (readers), and W1, W2 (writers).
See the rhythm? Readers cluster and run together. Writers line up and go one at a time. A writer only moves once the lock is completely free. That is the whole behavior in one small story.
There is one neat trick worth knowing. A thread that holds the write lock can take the read lock, then let go of the write lock. This is called downgrading. It lets you finish a write and keep reading the fresh value without a gap where another writer could sneak in.
writeLock.lock();
try {
value = computeNewValue(); // write phase
readLock.lock(); // take read lock before releasing write
} finally {
writeLock.unlock(); // now downgraded to read-only
}
try {
use(value); // safe to read, no writer can enter mid-way
} finally {
readLock.unlock();
}Upgrading is the opposite, and it does not work. You cannot hold the read lock and then grab the write lock. The JDK will deadlock or block forever, because the writer waits for readers to leave, but you are the reader refusing to leave. So remember: downgrade is fine, upgrade is not.
| 💡 Interview Insight Interviewers love the upgrade trap. If someone asks ‘can I go from a read lock to a write lock while holding it?’, say no. Lock upgrading is not supported and causes a deadlock. You must release the read lock first, then acquire the write lock, accepting that another thread might change the data in between. |
ReadWriteLock is not a free upgrade. It is a trade. You gain read parallelism, but you pay more overhead per lock operation than a plain lock. So it helps only in the right conditions.
The sweet spot is data that is read a lot and written rarely. The reads should also take real time, long enough that running them in parallel actually saves something.
Now flip it around. If writes are frequent, the write lock keeps kicking everyone out. Readers barely get a chance to overlap. In that case you paid extra overhead for almost no gain.
For a tiny counter that is written often, a plain ReentrantLock, or an AtomicInteger, will usually beat ReadWriteLock. Simpler is faster here. Do not reach for the fancy tool out of habit.
Here is a quick way to choose. Match your access pattern to the row that fits.
| Your situation | Good choice | Why |
|---|---|---|
| Reads dominate, writes rare, reads take time | ReentrantReadWriteLock | Readers run in parallel, big win |
| Writes are frequent | ReentrantLock | Write lock would dominate anyway |
| Tiny critical section (one field) | ReentrantLock or synchronized | Less overhead for short work |
| Simple counter or flag | AtomicInteger / AtomicBoolean | Lock-free and very fast |
| Extreme read-heavy, Java 8+ | StampedLock | Optimistic reads take no lock |
No single lock is best for everything. The right answer depends on how your threads actually touch the data. When in doubt, start simple and measure before you upgrade.
| 💡 Interview Insight A sharp follow-up: ‘is ReadWriteLock always faster than a normal lock?’ The honest answer is no. It wins only for read-heavy workloads with reads that take meaningful time. For write-heavy or very short critical sections, its extra bookkeeping makes it slower than a plain ReentrantLock. Always match the lock to the access pattern. |
There is a real danger hiding in read-heavy systems. It is called write starvation. Let us see how it happens, step by step.
Picture a steady stream of readers. One reader holds the read lock. Before it finishes, two more readers arrive and also grab the read lock. A writer now wants in, but the lock is busy with readers, so it waits.
Then more readers keep coming. As long as at least one reader holds the lock, the writer stays blocked. If readers never fully clear out, the writer can wait a very long time. That is starvation. The writer is starved of its turn.
ReentrantReadWriteLock has a fairness setting. You turn it on by passing true to the constructor.
// Non-fair (default): higher throughput, but writers can starve ReadWriteLock unfair = new ReentrantReadWriteLock(); // Fair: threads are served roughly in arrival order ReadWriteLock fair = new ReentrantReadWriteLock(true);
In fair mode, threads are served roughly in the order they asked. So a waiting writer will not be jumped by a flood of newer readers forever. New readers queue behind the waiting writer instead.
But fairness is not free either. It lowers overall throughput, because the lock spends more effort ordering threads. So you trade some speed for the promise that writers get their turn. Measure both modes before you decide.
| 💡 Interview Insight Expect: ‘what is write starvation and how do you fix it?’ Say it clearly. In a read-heavy system, a constant stream of readers can keep the lock busy so a writer never gets in. The fix is to construct the lock in fair mode with new ReentrantReadWriteLock(true), which serves threads in arrival order. Mention the cost: fairness reduces throughput. |
ReadWriteLock is great, but Java 8 added something even faster for some cases: StampedLock. We will not cover it in full here, but it is worth knowing it exists.
StampedLock adds a third mode called optimistic reading. Instead of taking a read lock, a thread grabs a cheap stamp, reads the data, then checks if a writer interfered. If nobody wrote during the read, the result is valid and no lock was ever held. That makes reads extremely cheap when writes are rare.
So treat StampedLock as the next step once you are comfortable here. For a deep dive, look up the dedicated StampedLock article. For most everyday read-heavy needs, ReentrantReadWriteLock is still a solid, safe choice.
Here is one way to hold the two in your head. ReadWriteLock is pessimistic. A reader says, ‘I will take a lock first, just to be safe, then read.’
StampedLock, in its optimistic mode, flips that. The reader says, ‘I will just read, and check afterwards whether a writer touched the data.’ Most of the time no writer did, so the read was basically free. When a writer did interfere, the reader simply retries with a real lock.
That extra retry logic is the price. It makes your code a bit longer and trickier. So reach for StampedLock only when profiling says the read lock itself is your bottleneck. Until then, keep things simple.
A: ReadWriteLock is an interface in java.util.concurrent.locks that splits access into two locks: a shared read lock that many threads can hold together, and an exclusive write lock that only one thread can hold. It is designed for read-heavy workloads where reads greatly outnumber writes.
A: The read lock is shared, so multiple reader threads can hold it at the same time and run in parallel. The write lock is exclusive, so only one thread can hold it, and only when no reader holds the read lock. Read and write locks block each other, but readers never block other readers.
A: No. Lock upgrading is not supported in ReentrantReadWriteLock and causes a deadlock, because the writer waits for readers to leave while you are the reader refusing to leave. You must release the read lock first, then acquire the write lock, accepting that the data might change in between. Downgrading from write to read is allowed.
A: Write starvation happens in read-heavy systems when a constant stream of readers keeps the lock busy, so a waiting writer never gets its turn. You fix it by creating the lock in fair mode with new ReentrantReadWriteLock(true), which serves threads roughly in arrival order. The trade-off is lower overall throughput.
A: No. ReadWriteLock only wins for read-heavy workloads where reads take meaningful time, so parallel reads actually save something. For write-heavy workloads or very short critical sections, its extra bookkeeping makes it slower than a plain ReentrantLock. Always match the lock to the access pattern.
A: Consider StampedLock (Java 8+) for extremely read-heavy code where the read lock itself becomes the bottleneck. Its optimistic read mode often takes no lock at all, which is very cheap when writes are rare. The downsides are that it is not reentrant and you must validate the stamp after an optimistic read, so it is easier to misuse than ReentrantReadWriteLock.
Let us bring it all together. A single lock treats reads and writes the same, which wastes time when reads dominate. ReadWriteLock in Java fixes that by splitting access into a shared read lock and an exclusive write lock.
Many readers can run together. One writer runs alone. Read and write locks block each other, but readers never block fellow readers. You can downgrade from write to read, but never upgrade the other way.
Use it for read-heavy data with meaningful read work. Skip it for write-heavy or tiny operations. Watch out for write starvation, and switch to fair mode when writers need protection. When you outgrow it, StampedLock waits for you. Master these rules, and you will reach for the right lock with confidence.