Phase 18 of 20 · Topic 18.4

Explicit Locks: ReentrantLock & ReentrantReadWriteLock

1Concept

`java.util.concurrent.locks.ReentrantLock` offers explicit lock control unavailable in synchronized: 1. `tryLock()` with timeouts (non-blocking lock acquisition); 2. Interruptible lock acquisition; 3. Fairness policies. `ReentrantReadWriteLock` allows multiple concurrent readers while enforcing exclusive access for writers.

2Architecture Diagram

ReentrantReadWriteLock:
Concurrent Readers:  [ Reader 1 ] [ Reader 2 ] [ Reader 3 ] ---> Granted ReadLock concurrently!
Exclusive Writer:    [ Writer 1 ]                              ---> Blocks all readers & writers!

3Code Example

Core Java
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ExplicitLockDemo {
    static class SharedCache {
        private String data = "Initial Data";
        private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

        public String read() {
            rwLock.readLock().lock(); // Shared lock: multiple threads can read concurrently
            try {
                return data;
            } finally {
                rwLock.readLock().unlock();
            }
        }

        public void write(String newData) {
            rwLock.writeLock().lock(); // Exclusive lock: blocks all readers and writers
            try {
                this.data = newData;
            } finally {
                rwLock.writeLock().unlock();
            }
        }
    }

    public static void main(String[] args) {
        SharedCache cache = new SharedCache();
        cache.write("Updated Enterprise Cache");
        System.out.println("Cache Read: " + cache.read());
    }
}

4Expected Output

Cache Read: Updated Enterprise Cache

5Key Takeaways

  • ALWAYS unlock explicit locks inside a `finally` block to prevent catastrophic lock leaks.
  • Use `ReentrantReadWriteLock` in read-heavy workloads (e.g. 95% reads, 5% writes) for massive throughput gains.
  • `tryLock(timeout, unit)` completely eliminates deadlock scenarios by timing out if a lock is contested.