Skip to content
javahacks.dev
Concurrency

How to Use ReadWriteLock and StampedLock in Java Code

Use ReentrantReadWriteLock when reads outnumber writes and StampedLock for optimistic reads, with the traps of lock upgrades, reentrancy and measuring first.

7 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, IntelliJ IDEA, Linux, Spring and JUnit5 logos.

A cache in front of a slow lookup gets read ten thousand times a second and written twice a minute. Put a plain synchronized around it and the readers queue behind each other for no reason, because two threads reading the same map never conflict. A read-write lock exists for exactly that shape of workload, and StampedLock goes a step further by letting readers skip the lock entirely. Both are easy to misuse, and the misuses deadlock or return torn data, so this post builds each one, breaks it on purpose and then says when a plain lock beats both. The examples assume JDK 25.

The problem a read-write lock solves

A mutual exclusion lock allows one thread at a time. That is correct for writes, but wasteful for reads, since concurrent reads of unchanging data are safe. A ReadWriteLock keeps two locks that share state: any number of threads can hold the read lock together, and the write lock is exclusive against readers and other writers.

It only pays off when two conditions hold at once. Reads must outnumber writes by a wide margin, and a read must take long enough that contention on the lock matters. A read that takes 20 nanoseconds is dominated by the cost of acquiring the lock, and a read-write lock is slower to acquire than a plain one because it maintains more state.

ReentrantReadWriteLock in a working cache

This is the standard shape: a map guarded by one read-write lock, with reads under the read lock and mutations under the write lock.

src/main/java/dev/javahacks/locks/PriceCache.javajava
package dev.javahacks.locks;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class PriceCache {

    private final Map<String, Long> prices = new HashMap<>();
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public Long get(String sku) {
        lock.readLock().lock();
        try {
            return prices.get(sku);
        } finally {
            lock.readLock().unlock();
        }
    }

    public void put(String sku, long cents) {
        lock.writeLock().lock();
        try {
            prices.put(sku, cents);
        } finally {
            lock.writeLock().unlock();
        }
    }

    public int size() {
        lock.readLock().lock();
        try {
            return prices.size();
        } finally {
            lock.readLock().unlock();
        }
    }
}

The try/finally is not decoration. If get throws and the unlock is skipped, the read lock is held forever and the next writer waits for ever. Every lock acquisition needs its release in a finally, the same rule as for ReentrantLock covered in using ReentrantLock and condition variables.

A small harness shows the behavior. Eight readers and one writer share the cache:

src/main/java/dev/javahacks/locks/CacheDemo.javajava
package dev.javahacks.locks;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

public class CacheDemo {

    public static void main(String[] args) throws Exception {
        PriceCache cache = new PriceCache();
        cache.put("A-100", 1999);
        LongAdder reads = new LongAdder();

        try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int r = 0; r < 8; r++) {
                pool.submit(() -> {
                    long end = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(200);
                    while (System.nanoTime() < end) {
                        cache.get("A-100");
                        reads.increment();
                    }
                });
            }
            pool.submit(() -> {
                for (int i = 0; i < 20; i++) {
                    cache.put("A-100", 1999 + i);
                }
            });
        }
        System.out.println("final price = " + cache.get("A-100"));
    }
}
Text
final price = 2018

The final value is deterministic because the single writer finishes with 1999 + 19. The read count varies per machine, which is why it is not printed.

Two rules that decide whether it deadlocks

Downgrading is allowed. Upgrading is not. A thread holding the write lock can acquire the read lock, then release the write lock, and keep reading without a gap another writer could use. A thread holding a read lock that asks for the write lock waits for all readers to leave, including itself, and never gets it.

src/main/java/dev/javahacks/locks/UpgradeDeadlock.javajava
package dev.javahacks.locks;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class UpgradeDeadlock {

    public static void main(String[] args) {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

        lock.readLock().lock();
        System.out.println("holding read lock");
        // The next line never returns: the write lock waits for this thread's own read lock.
        lock.writeLock().lock();
        System.out.println("unreachable");
    }
}
Text
holding read lock

The process then hangs. A thread dump (jcmd <pid> Thread.print) shows the main thread parked in ReentrantReadWriteLock$WriteLock.lock. The fix is to release the read lock first and then take the write lock, and to re-check the condition after, since another thread may have changed the state in the gap:

java
public Long computeIfAbsent(String sku, java.util.function.LongSupplier loader) {
    lock.readLock().lock();
    try {
        Long cached = prices.get(sku);
        if (cached != null) {
            return cached;
        }
    } finally {
        lock.readLock().unlock();
    }
    lock.writeLock().lock();
    try {
        // Another writer may have filled it while no lock was held.
        return prices.computeIfAbsent(sku, k -> loader.getAsLong());
    } finally {
        lock.writeLock().unlock();
    }
}

The second rule is fairness. The default is non-fair, so a steady stream of readers can starve a writer. new ReentrantReadWriteLock(true) queues requests roughly in arrival order, and costs throughput. Turn it on only when a measured writer wait is the problem.

StampedLock and the optimistic read

StampedLock (since Java 8) returns a long "stamp" with every acquisition and adds a third mode. An optimistic read takes no lock at all. You read the fields, then ask whether a write happened in between. If one did, you throw the values away and retry under a real read lock.

src/main/java/dev/javahacks/locks/Point.javajava
package dev.javahacks.locks;

import java.util.concurrent.locks.StampedLock;

public class Point {

    private double x;
    private double y;
    private final StampedLock sl = new StampedLock();

    public void move(double dx, double dy) {
        long stamp = sl.writeLock();
        try {
            x += dx;
            y += dy;
        } finally {
            sl.unlockWrite(stamp);
        }
    }

    public double distanceFromOrigin() {
        long stamp = sl.tryOptimisticRead();
        double curX = x;
        double curY = y;
        if (!sl.validate(stamp)) {
            stamp = sl.readLock();
            try {
                curX = x;
                curY = y;
            } finally {
                sl.unlockRead(stamp);
            }
        }
        return Math.sqrt(curX * curX + curY * curY);
    }
}

The order inside distanceFromOrigin matters. Copy the fields into locals first, validate second, and only then use the locals. If you compute with x and y directly after validation, a writer can change them between your two reads and you get a point that never existed, such as the new x with the old y.

Optimistic reads write nothing to shared memory, so many reader cores do not fight over one cache line. That is where StampedLock can beat ReentrantReadWriteLock by a large margin on read-mostly data with short critical sections. The memory-visibility reasoning behind validate is the same one explained in the Java memory model and happens-before.

StampedLock rules that bite

PropertyReentrantReadWriteLockStampedLock
ReentrantYesNo
Conditions (await/signal)Write lock onlyNone
Optimistic readNoYes
Upgrade read to writeDeadlockstryConvertToWriteLock, may fail
Works with virtual threadsYesYes, but see below

Not reentrant means a method that holds the write lock and calls another method that takes it will block on itself. There is no exception and no timeout, just a hung thread. Keep the locked region flat: no calls out to code you do not control, and no calls to your own other locked methods.

The stamp also has to be handed back to the matching unlock. Passing a stale stamp to unlockRead throws IllegalMonitorStateException at best and corrupts the lock state at worst. Keep each stamp in a local variable that lives for exactly one try/finally.

A last trap: do not interrupt a thread blocked in readLock() or writeLock() and expect it to stop. These methods ignore interrupts and can leave the CPU spinning. Use readLockInterruptibly() where cancellation matters.

Choosing between three options

Start from the simplest correct tool and move only when a measurement says to.

  1. A ConcurrentHashMap or an immutable snapshot swapped through an AtomicReference needs no explicit lock at all, and covers most caches.
  2. synchronized or ReentrantLock is right when the critical section is a few instructions, because acquisition cost dominates.
  3. ReentrantReadWriteLock fits read-heavy data where a read takes real time, such as scanning a list or formatting output.
  4. StampedLock fits tiny, read-mostly value objects where you control every access path and can accept non-reentrancy.

Write the benchmark with JMH, not a loop around System.nanoTime(), and run it with the thread count your service actually uses. The result on a laptop with 4 cores says little about a 64 core server, where cache-line contention changes the ranking. The official behavior of each class is in the ReentrantReadWriteLock and StampedLock Javadoc. For the cost of plain monitors under load, see synchronized blocks, monitors and lock contention.

Where this does not apply

If writes are frequent, a read-write lock is a slower mutex. If the guarded structure is already a concurrent collection, adding a lock on top removes the thing that made it fast. If the code runs on a single core container with -XX:ActiveProcessorCount=1, there is no parallel reading to win. And if a reader can block on I/O while holding the lock, every writer waits for that I/O, so copy the data out under the lock and do the slow work after releasing it.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.