1 22 23 package org.gjt.sp.util; 24 25 import java.util.Vector ; 26 27 57 public class ReadWriteLock 58 { 59 public synchronized void readLock() 61 { 62 if (activeReaders != 0 || allowRead()) 65 { 66 ++activeReaders; 67 return; 69 } 70 ++waitingReaders; 71 while (!allowRead()) 72 { 73 try 74 { 75 wait(); 76 } 77 catch (InterruptedException e) 78 { 79 --waitingReaders; Log.log(Log.ERROR,this,e); 81 return; 82 } 83 } 84 --waitingReaders; 85 ++activeReaders; 86 readers.addElement(Thread.currentThread()); 87 } 89 public synchronized void readUnlock() 91 { 92 if(activeReaders == 0) 93 throw new InternalError ("Unbalanced readLock()/readUnlock() calls"); 94 95 --activeReaders; 96 notifyAll(); 98 } 100 public synchronized void writeLock() 102 { 103 if (writerThread != null) 104 { 105 if (Thread.currentThread() == writerThread) 107 { 108 ++lockCount; 110 return; 111 } 112 } 113 if (allowWrite()) 114 { 115 claimWriteLock(); 116 return; 117 } 118 119 ++waitingWriters; 120 while (!allowWrite()) 121 { 122 try 123 { 124 wait(); 125 } 126 catch (InterruptedException e) 127 { 128 --waitingWriters; 129 Log.log(Log.ERROR,this,e); 130 return; 131 } 132 } 133 --waitingWriters; 134 claimWriteLock(); 135 } 137 public synchronized void writeUnlock() 139 { 140 if(activeWriters != 1 || lockCount <= 0) 141 throw new InternalError ("Unbalanced writeLock()/writeUnlock() calls"); 142 143 if(Thread.currentThread() != writerThread) 144 throw new InternalError ("writeUnlock() from wrong thread"); 145 146 if (--lockCount == 0) 147 { 148 --activeWriters; 149 writerThread = null; 150 notifyAll(); 151 } 152 } 154 public synchronized boolean isWriteLocked() 156 { 157 return activeWriters == 1; 159 } 161 163 private int activeReaders; 165 private int activeWriters; 166 private int waitingReaders; 167 private int waitingWriters; 168 private Vector readers = new Vector (); 169 170 private Thread writerThread; 171 private int lockCount; 172 174 private final boolean allowRead() 176 { 177 return (Thread.currentThread() == writerThread) 178 || (waitingWriters == 0 && activeWriters == 0); 179 } 181 private final boolean allowWrite() 183 { 184 190 191 return activeReaders == 0 && activeWriters == 0; 192 } 194 private void claimWriteLock() 196 { 197 ++activeWriters; 198 writerThread = Thread.currentThread(); 200 lockCount = 1; 202 } 204 } 206 | Popular Tags |