Skip to content

Instantly share code, notes, and snippets.

@maxmalakhov
Created July 27, 2016 10:00
Show Gist options
  • Save maxmalakhov/7b7e2c78fa32765f7e3a2bd48d324b3f to your computer and use it in GitHub Desktop.
Save maxmalakhov/7b7e2c78fa32765f7e3a2bd48d324b3f to your computer and use it in GitHub Desktop.
public class ReadWriteLock{
private int readers = 0;
private int writers = 0;
private int writeRequests = 0;
public synchronized void lockRead() throws InterruptedException{
while(writers > 0 || writeRequests > 0){
wait();
}
readers++;
}
public synchronized void unlockRead(){
readers--;
notifyAll();
}
public synchronized void lockWrite() throws InterruptedException{
writeRequests++;
while(readers > 0 || writers > 0){
wait();
}
writeRequests--;
writers++;
}
public synchronized void unlockWrite() throws InterruptedException{
writers--;
notifyAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment