ReentrantReadWriteLock Write Read Downgrade

Refresh under a write lock, then take the read lock before releasing the write lock — the documented downgrade that keeps writers out with no unlocked gap.

JavaResilience

Code

snippet
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheRefresher {

    private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
    private static String cached = "stale";

    public static void main(String[] args) {
        // 写锁内完成修改,再降级为读锁发布结果
        LOCK.writeLock().lock();
        try {
            cached = "fresh";
            // downgrade:先拿读锁,再放写锁,中间没有无锁窗口;
            // 反方向(读锁升级写锁)文档明确不允许
            LOCK.readLock().lock();
        } finally {
            LOCK.writeLock().unlock();
        }
        try {
            // 此刻仍持有读锁:读者之间共享,写者仍进不来
            System.out.println("read under downgraded lock: " + cached);
            System.out.println("read hold count: " + LOCK.getReadHoldCount());
        } finally {
            LOCK.readLock().unlock();
        }
        System.out.println("write locked: " + LOCK.isWriteLocked());
    }
}

How the snippet works

ReentrantReadWriteLock Write Read Downgrade reduces to the class CacheRefresher and the function main.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The one signature that matters here is public static void main(String[] args)

Output lines are prefixed (read under downgraded lock:, read hold count:, write locked:), so the effect of each step stands out plainly.

Key statements

LOCK.writeLock().unlock();
LOCK.readLock().unlock();
LOCK.writeLock().lock();

Interactive Tools for This Topic

FAQ

What does ReentrantReadWriteLock Write Read Downgrade print when run?
Running the file directly is enough — expect labeled output lines such as `read under downgraded lock:`, `read hold count:`, `write locked:`.