1 50 package org.apache.avalon.excalibur.concurrent; 51 52 69 public class ReadWriteLock 70 { 71 74 private int m_numReadLocksHeld = 0; 75 76 79 private int m_numWaitingForWrite = 0; 80 81 84 private Object m_lock = new Object (); 85 86 89 public ReadWriteLock() 90 { 91 } 92 93 100 public void acquireRead() 101 throws InterruptedException 102 { 103 synchronized( m_lock ) 104 { 105 while( !( m_numReadLocksHeld != -1 && m_numWaitingForWrite == 0 ) ) 106 { 107 m_lock.wait(); 108 } 109 m_numReadLocksHeld++; 110 } 111 } 112 113 119 public void aquireRead() 120 throws InterruptedException 121 { 122 acquireRead (); 123 } 124 125 126 133 public void acquireWrite() 134 throws InterruptedException 135 { 136 synchronized( m_lock ) 137 { 138 m_numWaitingForWrite++; 139 try 140 { 141 while( m_numReadLocksHeld != 0 ) 142 { 143 m_lock.wait(); 144 } 145 m_numReadLocksHeld = -1; 146 } 147 finally 148 { 149 m_numWaitingForWrite--; 150 } 151 } 152 } 153 154 160 public void aquireWrite() 161 throws InterruptedException 162 { 163 acquireWrite (); 164 } 165 166 172 public void release() 173 { 174 synchronized( m_lock ) 175 { 176 if( m_numReadLocksHeld == 0 ) 177 { 178 throw new IllegalStateException ( "Attempted to release an unlocked ReadWriteLock." ); 179 } 180 181 if( m_numReadLocksHeld == -1 ) 182 { 183 m_numReadLocksHeld = 0; 184 } 185 else 186 { 187 m_numReadLocksHeld--; 188 } 189 190 m_lock.notifyAll(); 191 } 192 } 193 194 199 public boolean tryAcquireRead() 200 { 201 synchronized( m_lock ) 202 { 203 if( m_numReadLocksHeld != -1 && m_numWaitingForWrite == 0 ) 204 { 205 m_numReadLocksHeld++; 206 return true; 207 } 208 else 209 { 210 return false; 211 } 212 } 213 } 214 215 220 public boolean tryAquireRead() 221 { 222 return tryAcquireRead(); 223 } 224 225 230 public boolean tryAcquireWrite() 231 { 232 synchronized( m_lock ) 233 { 234 if( m_numReadLocksHeld == 0 ) 235 { 236 m_numReadLocksHeld = -1; 237 return true; 238 } 239 else 240 { 241 return false; 242 } 243 } 244 } 245 246 251 public boolean tryAquireWrite() 252 { 253 return tryAcquireWrite(); 254 } 255 256 260 263 protected synchronized int getNumReadLocksHeld() { 264 return m_numReadLocksHeld; 265 } 266 267 270 protected synchronized int getNumWaitingForWrite() { 271 return m_numWaitingForWrite; 272 } 273 } 274 | Popular Tags |