import java.util.concurrent.Semaphore;
public class ReaderWriterLock {
public ReaderWriterLock() {
readers = 0;
readLock = new Semaphore(1);
readWriteLock = new Semaphore(1);
}
public void writeLock() throws InterruptedException {
readWriteLock.acquire();
}
public void writeUnlock() throws InterruptedException {
readWriteLock.release();
}
public void readLock() throws InterruptedException {
readLockUnlock.acquire();
if(readers == 0) {
readWriteLock.acquire();
}
readers++;
readLockUnlock.release();
}
public void readUnlock() throws InterruptedException {
assert readers > 0;
readLockUnlock.acquire();
readers--;
if(readers == 0) {
readWriteLock.release();
}
readLockUnlock.release();
}
private Semaphore readLock;
private Semaphore readWriteLock;
private int readers;
}