/********************************************************/
//
// The Read Write Monitor Class - version 3
//
class ReadWriteVs3 implements ReadWrite {

    private protected int readers =0;
    private protected boolean writing = false;
    private protected int waitingW = 0; // no of waiting Writers.
    private protected boolean readersturn = false;

    synchronized public void acquireRead() {
        while (writing || (waitingW>0 && !readersturn)) {
            try{ wait(); } catch(InterruptedException e){}
        }
        ++readers;
      }

    synchronized public void releaseRead() {
        --readers;
        readersturn=false;
        if(readers==0) notifyAll();
    }

    synchronized public void acquireWrite() {
        while (readers>0 || writing) {
            ++waitingW;
            try{ wait(); } catch(InterruptedException e){}
            --waitingW;
        }
        writing = true;
      }

    synchronized public void releaseWrite() {
        writing = false;
        readersturn=true;
        notifyAll();
    }

 }
