1 15 16 package EDU.oswego.cs.dl.util.concurrent; 17 18 19 37 38 public class FIFOReadWriteLock implements ReadWriteLock { 39 40 46 protected final FIFOSemaphore entryLock = new FIFOSemaphore(1); 47 48 54 protected volatile int readers; 55 56 65 protected int exreaders; 66 67 protected void acquireRead() throws InterruptedException { 68 entryLock.acquire(); 69 ++readers; 70 entryLock.release(); 71 } 72 73 protected synchronized void releaseRead() { 74 85 86 if (++exreaders == readers) 87 notify(); 88 } 89 90 protected void acquireWrite() throws InterruptedException { 91 entryLock.acquire(); 94 95 int r = readers; 98 99 try { 100 synchronized(this) { 101 while (exreaders != r) 102 wait(); 103 } 104 } 105 catch (InterruptedException ie) { 106 entryLock.release(); 107 throw ie; 108 } 109 } 110 111 protected void releaseWrite() { 112 entryLock.release(); 113 } 114 115 protected boolean attemptRead(long msecs) throws InterruptedException { 116 if (!entryLock.attempt(msecs)) 117 return false; 118 119 ++readers; 120 entryLock.release(); 121 return true; 122 } 123 124 protected boolean attemptWrite(long msecs) throws InterruptedException { 125 long startTime = (msecs <= 0)? 0 : System.currentTimeMillis(); 126 127 if (!entryLock.attempt(msecs)) 128 return false; 129 130 int r = readers; 131 132 try { 133 synchronized(this) { 134 while (exreaders != r) { 135 long timeLeft = (msecs <= 0)? 0: 136 msecs - (System.currentTimeMillis() - startTime); 137 138 if (timeLeft <= 0) { 139 entryLock.release(); 140 return false; 141 } 142 143 wait(timeLeft); 144 } 145 return true; 146 } 147 } 148 catch (InterruptedException ie) { 149 entryLock.release(); 150 throw ie; 151 } 152 } 153 154 156 protected class ReaderSync implements Sync { 157 public void acquire() throws InterruptedException { 158 acquireRead(); 159 } 160 public void release() { 161 releaseRead(); 162 } 163 public boolean attempt(long msecs) throws InterruptedException { 164 return attemptRead(msecs); 165 } 166 } 167 168 protected class WriterSync implements Sync { 169 public void acquire() throws InterruptedException { 170 acquireWrite(); 171 } 172 public void release() { 173 releaseWrite(); 174 } 175 public boolean attempt(long msecs) throws InterruptedException { 176 return attemptWrite(msecs); 177 } 178 } 179 180 protected final Sync readerSync = new ReaderSync(); 181 protected final Sync writerSync = new WriterSync(); 182 183 public Sync writeLock() { return writerSync; } 184 public Sync readLock() { return readerSync; } 185 186 } 187 | Popular Tags |