It seems to me it would be easier to just let the first entering reader lock the mutex and the last exiting reader to unlock it. The writer will just do regular lock/unlock. So we can implement like this:
public class RWLock {
protected boolean locked;
protected int readerCount;
//These are regular mutex lock/unlock operations
protected synchronized void lock() {
while(locked) wait();
locked = true;
}
protected synchronized void unlock() {
locked = false;
notifyAll();
}
//Writer just does lock/unlock
public void writeLock() { lock(); }
public void writeUnlock() { unlock(); }
public synchronized void readLock() {
if (readerCount == 0)
lock();
readerCount++;
}
public synchronized void readUnlock() {
if (--readerCount == 0)
unlock();
}
}