1 24 25 package org.objectweb.cjdbc.common.util; 26 27 import java.util.ArrayList ; 28 29 44 public class ReadPrioritaryFIFOWriteLock 45 { 46 47 private int activeReaders; 48 49 50 private boolean activeWriter; 51 52 53 private int waitingReaders; 54 55 56 private int waitingWriters; 57 58 private Object readSync; 59 private ArrayList writeWaitingQueue; 60 61 64 public ReadPrioritaryFIFOWriteLock() 65 { 66 activeReaders = 0; 67 activeWriter = false; 68 waitingReaders = 0; 69 waitingWriters = 0; 70 readSync = new Object (); 71 writeWaitingQueue = new ArrayList (); 72 } 73 74 80 public void acquireRead() throws InterruptedException 81 { 82 synchronized (this) 83 { 84 if ((waitingWriters == 0) && !activeWriter) 85 { activeReaders++; 87 return; 88 } 89 } 90 91 synchronized (readSync) 93 { 94 synchronized (this) 99 { 100 if (!activeWriter) 101 { activeReaders++; 103 return; 104 } 105 } 106 107 waitingReaders++; 108 try 109 { 110 readSync.wait(); 111 } 112 catch (InterruptedException ie) 113 { 114 waitingReaders--; throw ie; 116 } 117 waitingReaders--; 118 } 119 synchronized (this) 120 { 121 activeReaders++; 122 } 123 } 124 125 128 public synchronized void releaseRead() 129 { 130 activeReaders--; 131 if ((activeReaders == 0) && (waitingWriters > 0)) 132 { Object thread = writeWaitingQueue.remove(0); 134 synchronized (thread) 135 { 136 thread.notify(); 137 activeWriter = true; 138 waitingWriters--; 139 } 140 } 141 } 142 143 149 public void acquireWrite() throws InterruptedException 150 { 151 synchronized (Thread.currentThread()) 152 { 153 synchronized (this) 154 { 155 if ((activeReaders == 0) && !activeWriter) 156 { 157 activeWriter = true; 158 return; 159 } 160 else 161 { 162 waitingWriters++; 163 writeWaitingQueue.add(Thread.currentThread()); 164 } 165 } 166 try 167 { 168 Thread.currentThread().wait(); 169 } 170 catch (InterruptedException ie) 171 { 172 releaseWrite(); 173 throw ie; 174 } 175 } 176 } 177 178 181 public void releaseWrite() 182 { 183 activeWriter = false; 184 185 synchronized (this) 187 { 188 if (waitingWriters > 0) 189 { Object thread = writeWaitingQueue.remove(0); 191 synchronized (thread) 192 { 193 thread.notify(); 194 activeWriter = true; 195 waitingWriters--; 196 } 197 return; 198 } 199 } 200 201 synchronized (readSync) 207 { 208 if (waitingReaders > 0) 209 readSync.notifyAll(); 210 } 211 } 212 213 218 public final synchronized boolean isReadLocked() 219 { 220 return activeReaders > 0; 221 } 222 223 228 public final synchronized boolean isWriteLocked() 229 { 230 return activeWriter; 231 } 232 } | Popular Tags |