1 23 24 29 42 43 48 49 50 package com.sun.enterprise.util.sync; 51 52 import java.lang.InterruptedException ; 53 import java.util.LinkedList ; 54 import java.util.logging.Logger ; 56 import java.util.logging.Level ; 57 import com.sun.logging.LogDomains; 58 60 100 101 102 public class RWLock { 103 104 static Logger _logger=LogDomains.getLogger(LogDomains.UTIL_LOGGER); 106 int currentReaders; 108 int pendingReaders; 109 int currentWriters; 110 Queue writerQueue = new Queue(); 111 112 117 public synchronized void acquireReadLock() { 118 if (currentWriters == 0 && writerQueue.size() == 0) { 119 ++currentReaders; 120 } else { 121 ++pendingReaders; 122 try { 123 wait(); 124 } catch(InterruptedException ie) { 125 } 126 } 127 } 128 129 134 public void acquireWriteLock() { 135 Object lock = new Object (); 136 137 synchronized(lock) { 138 synchronized(this) { 139 if (writerQueue.size() == 0 && currentReaders == 0 && 140 currentWriters == 0) { 141 ++currentWriters; 142 _logger.log(Level.FINE," RW: incremented WriterLock count"); 146 return; 148 } 149 writerQueue.enQueue(lock); 150 _logger.log(Level.FINE," RW: Added WriterLock to queue"); 154 } 156 try { 157 lock.wait(); 158 } catch(InterruptedException ie) { 159 } 160 } 161 } 162 163 167 public synchronized void releaseReadLock() { 168 if (--currentReaders == 0) 169 notifyWriters(); 170 } 171 172 178 public synchronized void releaseWriteLock() { 179 --currentWriters; 180 if (pendingReaders > 0) 181 notifyReaders(); 182 else 183 notifyWriters(); 184 } 185 186 private void notifyReaders() { 187 currentReaders += pendingReaders; 188 pendingReaders = 0; 189 notifyAll(); 190 } 191 192 private void notifyWriters() { 193 if (writerQueue.size() > 0) { 194 Object lock = writerQueue.deQueueFirst(); 195 ++currentWriters; 196 synchronized(lock) { 197 lock.notify(); 198 } 199 } 200 } 201 202 class Queue extends LinkedList { 203 204 public Queue() { 205 super(); 206 } 207 208 public void enQueue(Object o) { 209 super.addLast(o); 210 } 211 212 public Object deQueueFirst() { 213 return super.removeFirst(); 214 } 215 216 } 217 218 } 219 220 | Popular Tags |