Readers-Writers Problem

Hard
ConcurrencyReadWriteLockSemaphoreMutexStarvationFairness

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:

  1. Readers-Preference: No reader waits if the resource is open for reading (risk: writer starvation).
  2. Writers-Preference: No writer waits longer than necessary once queued (risk: reader starvation).
  3. 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 readerCount variable.
  • writerSemaphore / Condition: Signals waiting writers when readers drain.

Requirements

  1. Multiple readers can hold the read lock concurrently.
  2. A writer waits for all current readers to finish before acquiring the write lock.
  3. No reader starts reading once a writer is waiting (writers-preference variant).
  4. 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.