1 16 17 package EDU.oswego.cs.dl.util.concurrent; 18 import java.util.*; 19 20 64 65 public class ReentrantWriterPreferenceReadWriteLock extends WriterPreferenceReadWriteLock { 66 67 68 protected long writeHolds_ = 0; 69 70 71 protected HashMap readers_ = new HashMap(); 72 73 74 protected static final Integer IONE = new Integer (1); 75 76 77 protected boolean allowReader() { 78 return (activeWriter_ == null && waitingWriters_ == 0) || 79 activeWriter_ == Thread.currentThread(); 80 } 81 82 protected synchronized boolean startRead() { 83 Thread t = Thread.currentThread(); 84 Object c = readers_.get(t); 85 if (c != null) { readers_.put(t, new Integer (((Integer )(c)).intValue()+1)); 87 ++activeReaders_; 88 return true; 89 } 90 else if (allowReader()) { 91 readers_.put(t, IONE); 92 ++activeReaders_; 93 return true; 94 } 95 else 96 return false; 97 } 98 99 protected synchronized boolean startWrite() { 100 if (activeWriter_ == Thread.currentThread()) { ++writeHolds_; 102 return true; 103 } 104 else if (writeHolds_ == 0) { 105 if (activeReaders_ == 0 || 106 (readers_.size() == 1 && 107 readers_.get(Thread.currentThread()) != null)) { 108 activeWriter_ = Thread.currentThread(); 109 writeHolds_ = 1; 110 return true; 111 } 112 else 113 return false; 114 } 115 else 116 return false; 117 } 118 119 120 protected synchronized Signaller endRead() { 121 Thread t = Thread.currentThread(); 122 Object c = readers_.get(t); 123 if (c == null) 124 throw new IllegalStateException (); 125 --activeReaders_; 126 if (c != IONE) { int h = ((Integer )(c)).intValue()-1; 128 Integer ih = (h == 1)? IONE : new Integer (h); 129 readers_.put(t, ih); 130 return null; 131 } 132 else { 133 readers_.remove(t); 134 135 if (writeHolds_ > 0) return null; 137 else if (activeReaders_ == 0 && waitingWriters_ > 0) 138 return writerLock_; 139 else 140 return null; 141 } 142 } 143 144 protected synchronized Signaller endWrite() { 145 --writeHolds_; 146 if (writeHolds_ > 0) return null; 148 else { 149 activeWriter_ = null; 150 if (waitingReaders_ > 0 && allowReader()) 151 return readerLock_; 152 else if (waitingWriters_ > 0) 153 return writerLock_; 154 else 155 return null; 156 } 157 } 158 159 } 160 161 | Popular Tags |