Design a Read-Write Lock

Medium
ConcurrencyConcurrencyLocksReaders-Writers ProblemFairnessSynchronization

Problem Statement

Design a custom Read-Write Lock that allows multiple concurrent readers or exactly one exclusive writer — with no starvation of writers when readers keep arriving (fair implementation).

Requirements

Functional Requirements

  • readLock() — acquire read lock; blocks only if a writer holds or is waiting
  • readUnlock() — release read lock
  • writeLock() — acquire write lock; blocks until all current readers finish and no other writer holds
  • writeUnlock() — release write lock
  • Multiple concurrent readers allowed
  • Writer gets exclusive access
  • Writer fairness: once a writer is waiting, new readers do not jump ahead (no writer starvation)
  • Reentrant option (bonus): same thread can acquire read lock multiple times

Non-Functional Requirements

  • Implemented using synchronized + wait/notify or ReentrantLock + Condition
  • No deadlocks
  • Writer preference to prevent starvation

Key Entities

  • ReadWriteLock: activeReaders (int), waitingWriters (int), activeWriter (boolean), lock (Object)
    • readLock(): synchronized; while(activeWriter || waitingWriters > 0) wait(); activeReaders++
    • readUnlock(): synchronized; activeReaders--; if 0, notifyAll()
    • writeLock(): synchronized; waitingWriters++; while(activeReaders > 0 || activeWriter) wait(); waitingWriters--; activeWriter=true
    • writeUnlock(): synchronized; activeWriter=false; notifyAll()

Constraints

  • No reader starvation (readers eventually get the lock when no writer is active)
  • No writer starvation (writer preference: new readers wait if writers are queued)
  • Deadlock-free: never wait while holding another lock
  • notifyAll() used on unlock to wake all waiting threads

!Constraints

- Writer preference: new readers wait if any writer is waiting - Multiple concurrent readers allowed when no writer is active or waiting - Exactly one writer at a time; no readers while writer is active - notifyAll() on every unlock to prevent missed signals - No deadlocks — acquire at most one lock at a time
Output

Run or submit your code to see output here.