ReadWrite monitor

ReadWrite monitor

class ReadWrite {

private protected int readers = 0;

private protected boolean writing = false;

// Inv: [(readers>=0 and !writing) or (readers==0 and writing)]

synchronized public void acquireRead() {

while (writing) {… wait(); …}

++readers;

}

synchronized public void releaseRead() {

--readers; if(readers==0) notify(); // [readers==0]

}

synchronized public void acquireWrite() {

while (readers>0 || writing) {… wait(); …}

writing = true;

}

synchronized public void releaseWrite() {

writing = false; notifyAll(); // [!writing]

}

}

Demo

Previous slide Next slide Back to the first slide View Graphic Version