Readers-Writers Problem
HardConcurrencyReadWriteLockSemaphoreMutexStarvationFairness
Problem Statement
Design a Readers-Writers lock that allows a shared database/resource to be accessed by:
- Multiple readers simultaneously (no modification).
- Only one writer at a time (exclusive access — no concurrent readers or writers).
Implement the three classic variants:
- Readers-Preference: No reader waits if the resource is open for reading (risk: writer starvation).
- Writers-Preference: No writer waits longer than necessary once queued (risk: reader starvation).
- Fair (No Starvation): Neither readers nor writers starve; FIFO order respected.
class ReadWriteLock {
public ReadWriteLock() {}
public void lockRead() throws InterruptedException {}
public void unlockRead() {}
public void lockWrite() throws InterruptedException {}
public void unlockWrite() {}
}
Key Entities
- readerCount: Tracks active readers (guarded by a mutex).
- resourceMutex: Exclusive lock on the resource itself.
- readerMutex: Protects the
readerCountvariable. - writerSemaphore / Condition: Signals waiting writers when readers drain.
Requirements
- Multiple readers can hold the read lock concurrently.
- A writer waits for all current readers to finish before acquiring the write lock.
- No reader starts reading once a writer is waiting (writers-preference variant).
- Implement upgrade/downgrade (read → write lock) as a bonus.
Asked at: Google, Amazon, Microsoft, Uber, LinkedIn, Oracle, Samsung
!Constraints
- Up to 100 reader threads and 10 writer threads concurrently.
- Read operations are assumed to be non-modifying.
- Write operations have exclusive access — no readers or other writers.
- Solution must not use Java's built-in ReentrantReadWriteLock.
Output
Run or submit your code to see output here.