0Pricing
Java Academy · Lesson

ReadWriteLock for Reader-Writer Scenarios

Use ReadWriteLock to allow concurrent reads while ensuring exclusive writes in a cache.

ReadWriteLock for Reader-Writer Scenarios is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Reader-Writer Problem

Multiple threads can safely read shared data simultaneously. But writing requires exclusive access — no concurrent reads or writes. A ReadWriteLock models this: multiple concurrent readers OR one exclusive writer.

import java.util.concurrent.locks.*;

ReadWriteLock rwLock = new ReentrantReadWriteLock();
Lock readLock  = rwLock.readLock();
Lock writeLock = rwLock.writeLock();

Read Lock: Shared Access

Multiple threads can hold the read lock simultaneously as long as no thread holds the write lock:

class ReadableCache {
    private final Map<String, String> cache = new HashMap<>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    
    String get(String key) {
        lock.readLock().lock();
        try {
            return cache.get(key); // concurrent reads OK
        } finally {
            lock.readLock().unlock();
        }
    }
}

Write Lock: Exclusive Access

Only one thread can hold the write lock at a time. All readers and other writers are blocked during a write:

class WritableCache extends ReadableCache {
    private final ReadWriteLock wLock = new ReentrantReadWriteLock();
    private final Map<String, String> data = new HashMap<>();
    
    void put(String key, String value) {
        wLock.writeLock().lock();
        try {
            data.put(key, value); // exclusive write
        } finally {
            wLock.writeLock().unlock();
        }
    }
}

Full Cache Example

A thread-safe cache where reads dominate and writes are rare:

class Cache<K,V> {
    private final Map<K,V> map = new HashMap<>();
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    
    V get(K key) {
        lock.readLock().lock();
        try { return map.get(key); }
        finally { lock.readLock().unlock(); }
    }
    
    void put(K key, V value) {
        lock.writeLock().lock();
        try { map.put(key, value); }
        finally { lock.writeLock().unlock(); }
    }
    
    int size() {
        lock.readLock().lock();
        try { return map.size(); }
        finally { lock.readLock().unlock(); }
    }
}

Lock Downgrading

ReadWriteLock supports lock downgrading: acquire write lock → acquire read lock → release write lock. This allows a thread to transition from exclusive write to shared read without releasing the lock:

ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
Lock r = rwl.readLock(), w = rwl.writeLock();

w.lock(); // acquire write
try {
    // modify data
    r.lock(); // acquire read WHILE holding write
} finally {
    w.unlock(); // release write, now holding read only
}
try {
    // safely read the just-written data
} finally {
    r.unlock();
}

Read Lock Does Not Upgrade

Lock upgrading (read → write) is NOT supported. If a thread holding a read lock tries to acquire the write lock, it deadlocks because the write lock waits for ALL readers, including itself:

// DEADLOCK: Do NOT do this
lock.readLock().lock();
try {
    lock.writeLock().lock(); // DEADLOCK — waits for readLock to release
} finally {
    lock.readLock().unlock();
}

When ReadWriteLock Helps

ReadWriteLock is beneficial when:

  • Reads significantly outnumber writes
  • Read operations take non-trivial time (e.g., complex queries)

It may hurt performance when writes are frequent (write lock blocks all readers) or when operations are very fast (overhead of two lock objects).

Comparing ReadWriteLock to synchronized

synchronized/ReentrantLock → only one thread at a time (even concurrent readers blocked).
ReadWriteLock → multiple concurrent readers, exclusive writer. Better read throughput in read-heavy scenarios.

// synchronized: only one thread reads at a time
synchronized String get(String key) { return cache.get(key); }

// ReadWriteLock: many threads can read simultaneously
String get2(String key) {
    lock.readLock().lock();
    try { return cache.get(key); }
    finally { lock.readLock().unlock(); }
}

Performance Considerations

Acquiring/releasing two lock objects adds overhead vs a single lock. Profile before assuming ReadWriteLock is faster. In read-heavy scenarios with long operations, the benefit is clear. For fast, write-heavy workloads, a simple ReentrantLock may be faster.

ConcurrentHashMap Alternative

For simple map operations, ConcurrentHashMap is often faster than a HashMap + ReadWriteLock because it uses internal segment-level locks with no global contention:

// Often better than HashMap + ReadWriteLock for simple operations:
Map<String, String> concurrent = new ConcurrentHashMap<>();
concurrent.put("key", "value"); // thread-safe, no explicit lock
String v = concurrent.get("key"); // thread-safe

ReadLock Fairness

By default, ReentrantReadWriteLock is non-fair (readers may starve writers). Use the fair constructor to prevent writer starvation:

// Fair: waiting writers are served before new readers
ReentrantReadWriteLock fairLock = new ReentrantReadWriteLock(true);
System.out.println(fairLock.isFair()); // true

Quick Check

In a read-heavy application, what is the key advantage of ReadWriteLock over a simple synchronized method?

Recap: ReadWriteLock

Key takeaways:

  • Multiple concurrent reads OR one exclusive write — not both
  • readLock.lock()/unlock() for shared reads
  • writeLock.lock()/unlock() for exclusive writes
  • Lock downgrading supported; upgrading (read→write) causes deadlock
  • Best for read-heavy with non-trivial operations; ConcurrentHashMap for simple maps

Frequently asked questions

Is the “ReadWriteLock for Reader-Writer Scenarios” lesson free?

Yes — the full text of “ReadWriteLock for Reader-Writer Scenarios” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “ReadWriteLock for Reader-Writer Scenarios”?

Use ReadWriteLock to allow concurrent reads while ensuring exclusive writes in a cache. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “ReadWriteLock for Reader-Writer Scenarios” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. ReentrantLock vs synchronized
  2. ReadWriteLock for Reader-Writer Scenarios
  3. Atomic Variables: Lock-Free Updates
  4. StampedLock and Optimistic Reads
← Back to Java Academy