Skip to content

Latest commit

 

History

History
46 lines (33 loc) · 1.25 KB

File metadata and controls

46 lines (33 loc) · 1.25 KB

Read-Write Lock

Requirement

Design a lock which lets multiple readers read at the same time, but only one writer write at a time.

Notes

  • it is possible for a writer to starve and never get a chance to acquire the write lock since there could always be at least one reader which has the read lock acquired.
  • wait() always must be called inside a loop read more

Code

 public synchronized void acquireReadLock() throws InterruptedException {
        while (isWriteLocked) {
            wait();
        }
        readers++;
    }

    public synchronized void releaseReadLock() throws InterruptedException {
        while (readers == 0) {
            wait();
        }
        readers--;
        notify();
    }

    public synchronized void acquireWriteLock() throws InterruptedException {
        while (isWriteLocked && readers != 0) {
            wait();
        }
        isWriteLocked = true;
    }

    public synchronized void releaseWriteLock() {
        isWriteLocked = false;
        notify();
    }
  

return to main page