1 23 24 28 29 package com.sun.jts.CosTransactions; 30 import java.lang.InterruptedException ; 31 import java.util.LinkedList ; 32 import java.util.logging.Logger ; 33 import java.util.logging.Level ; 34 import com.sun.logging.LogDomains; 35 36 37 77 78 79 public class RWLock { 80 81 int currentReaders; 82 int pendingReaders; 83 int currentWriters; 84 87 static Logger _logger = LogDomains.getLogger(LogDomains.TRANSACTION_LOGGER); 88 89 Queue writerQueue = new Queue(); 90 95 public synchronized void acquireReadLock() { 96 if (currentWriters == 0 && writerQueue.size() == 0) { 97 ++currentReaders; 98 } else { 99 ++pendingReaders; 100 try { 101 wait(); 102 } catch(InterruptedException ie) { 103 _logger.log(Level.FINE,"Error in acquireReadLock",ie); 104 } 105 } 106 } 107 108 113 public void acquireWriteLock() { 114 Object lock = new Object (); 115 116 synchronized(lock) { 117 synchronized(this) { 118 if (writerQueue.size() == 0 && currentReaders == 0 && currentWriters == 0) { 119 ++currentWriters; 120 return; 123 } 124 writerQueue.enQueue(lock); 125 } 128 try { 129 lock.wait(); 130 } catch(InterruptedException ie) { 131 _logger.log(Level.FINE,"Error in acquireWriteLock",ie); 132 } 133 } 134 } 135 136 142 public boolean isWriteLocked() 143 { 144 return currentWriters > 0 ; 145 } 146 147 152 public synchronized void releaseReadLock() { 153 if (--currentReaders == 0) 154 notifyWriters(); 155 } 156 157 163 public synchronized void releaseWriteLock() { 164 --currentWriters; 165 if (pendingReaders > 0) 166 notifyReaders(); 167 else 168 notifyWriters(); 169 } 170 private void notifyReaders() { 171 currentReaders += pendingReaders; 172 pendingReaders = 0; 173 notifyAll(); 174 } 175 176 private void notifyWriters() { 177 if (writerQueue.size() > 0) { 178 Object lock = writerQueue.deQueueFirst(); 179 ++currentWriters; 180 synchronized(lock) { 181 lock.notify(); 182 } 183 } 184 } 185 186 class Queue extends LinkedList { 187 188 public Queue() { 189 super(); 190 } 191 192 public void enQueue(Object o) { 193 super.addLast(o); 194 } 195 196 public Object deQueueFirst() { 197 return super.removeFirst(); 198 } 199 200 } 201 202 } 203 204 205 206 | Popular Tags |