When I look at this problem, I write a version here:
dWriteLock {
int readers = 0;
boolean isWriteLocked = false;
public synchronized void acquireReadLock() throws InterruptedException {
while (isWriteLocked) {
wait();
}
readers++;
notifyAll();
}
public synchronized void releaseReadLock() throws InterruptedException {
while (isWriteLocked || readers == 0) {
wait();
}
readers--;
notifyAll();
}
public synchronized void acquireWriteLock() throws InterruptedException {
while (isWriteLocked || readers > 0) {
wait();
}
isWriteLocked = true;
notifyAll();
}
public synchronized void releaseWriteLock() throws InterruptedException {
while (!isWriteLocked || readers > 0) {
wait();
}
isWriteLocked = false;
notifyAll();
}
}
The differences are I check if it is legal to release locks before return from release methods.
I assume that the given answer assumes that a thread will release the lock only after a lock is acquired. Otherwise, there is a bug that when a thread release the lock, the readers--
makes int readers
to be negative, and that does not make sense.
Course: Java Multithreading for Senior Engineering Interviews - Learn Interactively
Lesson: ReadWrite Lock - Java Multithreading for Senior Engineering Interviews