1 22 23 package org.continuent.sequoia.controller.locks; 24 25 import java.util.ArrayList ; 26 27 42 public class ReadPrioritaryFIFOWriteLock 43 { 44 45 private int activeReaders; 46 47 48 private boolean activeWriter; 49 50 51 private int waitingReaders; 52 53 54 private int waitingWriters; 55 56 private Object readSync; 57 private ArrayList writeWaitingQueue; 58 59 62 public ReadPrioritaryFIFOWriteLock() 63 { 64 activeReaders = 0; 65 activeWriter = false; 66 waitingReaders = 0; 67 waitingWriters = 0; 68 readSync = new Object (); 69 writeWaitingQueue = new ArrayList (); 70 } 71 72 78 public void acquireRead() throws InterruptedException 79 { 80 synchronized (this) 81 { 82 if ((waitingWriters == 0) && !activeWriter) 83 { activeReaders++; 85 return; 86 } 87 } 88 89 synchronized (readSync) 91 { 92 synchronized (this) 97 { 98 if (!activeWriter) 99 { activeReaders++; 101 return; 102 } 103 } 104 105 waitingReaders++; 106 try 107 { 108 readSync.wait(); 109 } 110 catch (InterruptedException ie) 111 { 112 waitingReaders--; throw ie; 114 } 115 waitingReaders--; 116 } 117 synchronized (this) 118 { 119 activeReaders++; 120 } 121 } 122 123 126 public synchronized void releaseRead() 127 { 128 activeReaders--; 129 if ((activeReaders == 0) && (waitingWriters > 0)) 130 { Object thread = writeWaitingQueue.remove(0); 132 synchronized (thread) 133 { 134 thread.notify(); 135 activeWriter = true; 136 waitingWriters--; 137 } 138 } 139 } 140 141 147 public void acquireWrite() throws InterruptedException 148 { 149 synchronized (Thread.currentThread()) 150 { 151 synchronized (this) 152 { 153 if ((activeReaders == 0) && !activeWriter) 154 { 155 activeWriter = true; 156 return; 157 } 158 else 159 { 160 waitingWriters++; 161 writeWaitingQueue.add(Thread.currentThread()); 162 } 163 } 164 try 165 { 166 Thread.currentThread().wait(); 167 } 168 catch (InterruptedException ie) 169 { 170 releaseWrite(); 171 throw ie; 172 } 173 } 174 } 175 176 179 public void releaseWrite() 180 { 181 synchronized (this) 183 { 184 activeWriter = false; 185 if (waitingWriters > 0) 186 { Object thread = writeWaitingQueue.remove(0); 188 synchronized (thread) 189 { 190 thread.notify(); 191 activeWriter = true; 192 waitingWriters--; 193 } 194 return; 195 } 196 } 197 198 synchronized (readSync) 204 { 205 if (waitingReaders > 0) 206 readSync.notifyAll(); 207 } 208 } 209 210 215 public final synchronized boolean isReadLocked() 216 { 217 return activeReaders > 0; 218 } 219 220 225 public final synchronized boolean isWriteLocked() 226 { 227 return activeWriter; 228 } 229 } | Popular Tags |