import java.io.*; class RWLock { private int lockVal; public RWLock( int pVal) { lockVal = pVal; } public RWLock () { lockVal = 0; } public RWLock(RWLock pt) { lockVal = pt.getLockVal(); } public int getLockVal () { return lockVal; } public String toString() { String str = "lockVal: " + lockVal; return str; } public synchronized boolean setReadLock() { if (lockVal < 0) return false; else { lockVal++; return true; } } public synchronized boolean clearReadLock() { if (lockVal <= 0) return false; else { lockVal--; return true; } } public synchronized boolean setWriteLock() { if (lockVal != 0) return false; else { lockVal = -1; return true; } } public synchronized boolean clearWriteLock() { if (lockVal != -1) return false; else { lockVal = 0; return true; } } public static void main (String[] args) { RWLock rwl1 = new RWLock (); System.out.println ("rwl1 = " + rwl1); System.out.print ("Setting read lock on rwl1: "); if (rwl1.setReadLock()) System.out.println ("success rwl1 = " + rwl1); else System.out.println ("fail rwl1 = " + rwl1); System.out.print ("Setting write lock on rwl1: "); if (rwl1.setWriteLock()) System.out.println ("success rwl1 = " + rwl1); else System.out.println ("fail rwl1 = " + rwl1); System.out.print ("Setting read lock on rwl1: "); if (rwl1.setReadLock()) System.out.println ("success rwl1 = " + rwl1); else System.out.println ("fail rwl1 = " + rwl1); System.out.print ("Clearing read lock on rwl1: "); if (rwl1.clearReadLock()) System.out.println ("success rwl1 = " + rwl1); else System.out.println ("fail rwl1 = " + rwl1); System.out.print ("Clearing write lock on rwl1: "); if (rwl1.clearWriteLock()) System.out.println ("success rwl1 = " + rwl1); else System.out.println ("fail rwl1 = " + rwl1); System.out.print ("Clearing read lock on rwl1: "); if (rwl1.clearReadLock()) System.out.println ("success rwl1 = " + rwl1); else System.out.println ("fail rwl1 = " + rwl1); System.out.println (); RWLock rwl2 = new RWLock (); System.out.println ("rwl2 = " + rwl2); System.out.print ("Setting write lock on rwl2: "); if (rwl2.setWriteLock()) System.out.println ("success rwl2 = " + rwl2); else System.out.println ("fail rwl2 = " + rwl2); System.out.print ("Setting read lock on rwl2: "); if (rwl2.setReadLock()) System.out.println ("success rwl2 = " + rwl2); else System.out.println ("fail rwl2 = " + rwl2); System.out.print ("Setting write lock on rwl2: "); if (rwl2.setWriteLock()) System.out.println ("success rwl2 = " + rwl2); else System.out.println ("fail rwl2 = " + rwl2); System.out.print ("Clearing write lock on rwl2: "); if (rwl2.clearWriteLock()) System.out.println ("success rwl2 = " + rwl2); else System.out.println ("fail rwl2 = " + rwl2); System.out.print ("Clearing read lock on rwl2: "); if (rwl2.clearReadLock()) System.out.println ("success rwl2 = " + rwl2); else System.out.println ("fail rwl2 = " + rwl2); } }