Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Java Java and Cryptography Mastery Series — Extended Java Programming Java Tutorial Module 19 - Advanced Collections and Concurrency

Java ReadWriteLock for Many Readers One Writer

Reviewed & accurate
AI Summary

Introduction

The Java ReadWriteLock interface joined the JDK in Java 5 (2004) as part of JSR 166, the original java.util.concurrent package. Its single implementation, ReentrantReadWriteLock, separates read and write acquisition so that multiple readers can hold the lock simultaneously while a single writer holds it exclusively. The pattern is decades old in database engines and file systems; Java's version brings it to general-purpose concurrent programming.

For a Java learner, the java readwritelock primitive is the right tool when a data structure is read far more often than it is written, and reads can safely proceed concurrently. The classic example is an in-memory cache or a configuration map: many threads read, but writes are rare. This post walks through the read-write separation mechanics, demonstrates a thread-safe cache, and shows the optional fairness mode that prevents writer starvation.

What is Java ReadWriteLock?

The Java ReadWriteLock interface exposes two methods: readLock returns a Lock for shared acquisition, and writeLock returns a Lock for exclusive acquisition. Multiple threads can hold the read lock at the same time; only one thread can hold the write lock, and no thread can hold the read lock while the write lock is held. The ReentrantReadWriteLock implementation also supports reentrancy: a thread holding the read lock can acquire it again; a thread holding the write lock can acquire either; a thread holding the read lock cannot upgrade to the write lock without first releasing.

Conceptually, ReadWriteLock trades throughput on the read path for overhead on both paths. Acquiring the read lock requires a CAS or counter increment that records the count of active readers; releasing requires a decrement and a possible writer wake-up. For workloads dominated by reads, the savings from concurrent reads dominate the overhead; for write-heavy workloads, plain ReentrantLock is usually faster because it avoids the reader counter bookkeeping.

The interface distinguishes fairness modes. A non-fair ReentrantReadWriteLock allows reader barging: if a reader arrives while a writer is waiting, the reader can join the existing reader set rather than queue behind the writer. A fair lock requires readers to queue behind any waiting writer, which prevents writer starvation but reduces reader throughput under contention.

How Java ReadWriteLock Works - Step by Step

Step 1: Construction. You write new ReentrantReadWriteLock for a non-fair lock, or new ReentrantReadWriteLock(true) for fair. The lock packs its state into a single int: the high 16 bits count readers, the low 16 bits count writers (which is 0 or 1 because only one writer can hold at a time).

Step 2: readLock().lock. The calling thread atomically increments the reader count. If the write lock is held by another thread or the fair queue is non-empty (in fair mode), the caller parks on the wait queue.

Step 3: readLock().unlock. The reader count is decremented. If it reaches zero and a writer is waiting, the writer is woken.

Step 4: writeLock().lock. The caller checks that the reader count is zero and the writer slot is free (or that the caller already holds the write lock for reentrancy). If both conditions hold, the writer slot is set. Otherwise, the caller parks.

Step 5: writeLock().unlock. The writer slot is cleared and any waiting readers (or one waiting writer, in fair mode) are woken. The readers all proceed concurrently.

Step 6: Reentrancy. A reader holding the read lock can acquire it again; the count increments. A writer holding the write lock can acquire either lock; this is the only way to downgrade (write to read) without losing exclusivity in between. Read-to-write upgrades are not supported because they would deadlock when two readers both tried to upgrade.

Java Program for ReadWriteLock

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function;

public class ReadWriteLockDemo {

    static final class ThreadSafeCache<K, V> {
        private final Map<K, V> data = new HashMap<>();
        private final ReadWriteLock lock = new ReentrantReadWriteLock();

        V get(K key) {
            lock.readLock().lock();
            try {
                return data.get(key);
            } finally {
                lock.readLock().unlock();
            }
        }

        V put(K key, V value) {
            lock.writeLock().lock();
            try {
                return data.put(key, value);
            } finally {
                lock.writeLock().unlock();
            }
        }

        V computeIfAbsent(K key, Function<K, V> loader) {
            lock.readLock().lock();
            try {
                V cached = data.get(key);
                if (cached != null) return cached;
            } finally {
                lock.readLock().unlock();
            }
            V loaded = loader.apply(key);
            lock.writeLock().lock();
            try {
                V existing = data.get(key);
                if (existing != null) return existing;
                data.put(key, loaded);
                return loaded;
            } finally {
                lock.writeLock().unlock();
            }
        }

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

    public static void main(String[] args) throws InterruptedException {
        ThreadSafeCache<String, Integer> cache = new ThreadSafeCache<>();
        cache.put("one", 1);
        cache.put("two", 2);

        Runnable reader = () -> {
            for (int i = 0; i < 3; i++) {
                Integer v = cache.get("one");
                System.out.println(Thread.currentThread().getName()
                        + " read one=" + v);
            }
        };

        Thread r1 = new Thread(reader, "R1");
        Thread r2 = new Thread(reader, "R2");
        Thread r3 = new Thread(reader, "R3");
        r1.start(); r2.start(); r3.start();
        r1.join(); r2.join(); r3.join();

        cache.computeIfAbsent("three", k -> 3);
        System.out.println("after computeIfAbsent, size=" + cache.size());
    }
}

Code Explanation - Line by Line

The ThreadSafeCache class wraps a HashMap with a ReadWriteLock. The lock is non-fair by default, which is appropriate for read-heavy caches where reader barging is desired. The HashMap itself is not thread-safe; the lock provides all the visibility and mutual exclusion required.

The get method acquires the read lock, reads the value, and releases the lock in a finally. Because the read lock is shared, multiple threads can call get at the same time and all proceed concurrently; the only cost is the per-call reader count increment and decrement. The visibility guarantee is that writes made under the write lock are visible to readers under the read lock, because the lock acquisition forms a happens-before relationship.

The put method acquires the write lock, performs the put, and releases. While the write lock is held, no reader can acquire the read lock, so the put sees a consistent state and the readers see a consistent state after the write lock is released.

The computeIfAbsent method implements a double-checked read pattern: it first checks the cache under the read lock, and only if the value is missing does it load the value outside any lock and then write it under the write lock. The write-lock branch re-checks the cache before writing, because another thread may have inserted the value between the read-lock check and the write-lock acquisition. This pattern is the standard way to avoid holding the write lock during a slow loader.

The main method spawns three reader threads that each read the same key three times. Because the read lock is shared, the three threads run concurrently rather than serialising. The main thread then calls computeIfAbsent, which loads and stores the value for "three" because the cache did not have it.

Sample Input and Output

Input:
  cache seeded with {one=1, two=2}; 3 reader threads each read "one" 3 times
  computeIfAbsent "three" with loader that returns 3

Output (reader thread interleaving will vary):
  R1 read one=1
  R2 read one=1
  R3 read one=1
  R1 read one=1
  R2 read one=1
  R3 read one=1
  R1 read one=1
  R2 read one=1
  R3 read one=1
  after computeIfAbsent, size=3

The three reader threads see consistent values of one=1 throughout; the computeIfAbsent call adds "three"=3, leaving the cache with three entries.

Common Mistakes to Avoid

Mistake 1: Forgetting to release the read lock. Like ReentrantLock, every readLock().lock must be paired with a readLock().unlock in a finally. A common bug is to call lock, return early, and forget to unlock.

Mistake 2: Trying to upgrade from read lock to write lock. Holding the read lock and then calling writeLock().lock deadlocks because the write lock waits for the read count to drop to zero, which never happens while the caller holds the read lock. To upgrade, release the read lock first, then acquire the write lock, then re-check the state under the write lock.

Mistake 3: Holding the read lock during a long operation. Read locks are not free; they keep the writer waiting. A long-running operation under the read lock starves writers and can stall the whole system. Hold the read lock for the minimum time needed to read the data.

Mistake 4: Using ReadWriteLock for write-heavy workloads. The reader counter overhead makes ReadWriteLock slower than plain ReentrantLock when writes are frequent. Use ReadWriteLock when reads significantly outnumber writes; otherwise prefer a plain lock.

Real-World Applications

In-memory caches. The most common use case: a HashMap wrapped in a ReadWriteLock, exactly as shown in the demo. Many open-source caches (Caffeine's older versions, Guava Cache's older versions) used this pattern before moving to striped locks.

Configuration stores. A configuration map that is read by every thread on every request but written only by an admin reload benefits enormously from read-write separation; reads stay concurrent, and the reload waits for in-flight reads before swapping the map.

Read-mostly indexes. Search indexes that are queried many times per second but rebuilt occasionally use ReadWriteLock to keep the read path lock-free-ish while the rebuild holds the write lock.

Directory listings. File system APIs use read-write locks to allow concurrent directory reads while a rename or delete holds the write lock; the pattern is the same as for in-memory caches, just at the file system layer.

Thread-local snapshots. Some libraries use ReadWriteLock to coordinate a "publish a new snapshot" operation with concurrent "read the current snapshot" operations; the writer publishes under the write lock, and the readers see the new snapshot under the read lock.

Conclusion

ReadWriteLock separates shared reads from exclusive writes, allowing many readers to proceed concurrently while a single writer holds the lock. It is the right choice for read-heavy workloads where the cost of the reader counter is offset by the throughput of concurrent reads. The next topics worth studying are StampedLock for optimistic reads that bypass the reader counter entirely, ReentrantLock for plain mutual exclusion, and the Condition interface for multi-condition coordination.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments