0Pricing
Java Academy · Lesson

ReadWriteLock for Reader-Writer Scenarios

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

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();
        }
    }
}

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