1 7 package org.jboss.cache.lock; 8 9 import java.util.Collections ; 10 import java.util.Set ; 11 import java.util.concurrent.CopyOnWriteArraySet ; 12 13 19 public class LockMap 20 { 21 public static final int OWNER_ANY = 0; 22 public static final int OWNER_READ = 1; 23 public static final int OWNER_WRITE = 2; 24 25 private Object writeOwner_=null; 26 27 31 private final Set readOwnerList_ = new CopyOnWriteArraySet (); 32 33 public LockMap() 34 { 35 } 36 37 38 48 public boolean isOwner(Object caller, int ownership) 49 { 50 53 54 switch (ownership) { 55 case OWNER_ANY: 56 return (writeOwner_ != null && caller.equals(writeOwner_) || readOwnerList_.contains(caller)); 57 case OWNER_READ: 58 return (readOwnerList_.contains(caller)); 59 case OWNER_WRITE: 60 return (writeOwner_ != null && caller.equals(writeOwner_)); 61 default: 62 return false; 63 } 64 } 65 66 67 68 73 public void addReader(Object owner) 74 { 75 readOwnerList_.add(owner); 76 } 77 78 83 public void setWriterIfNotNull(Object owner) 84 { 85 synchronized(this) { 86 if(writeOwner_ != null) 87 throw new IllegalStateException ("there is already a writer holding the lock: " + writeOwner_); 88 writeOwner_=owner; 89 } 90 } 91 92 private Object setWriter(Object owner) { 93 Object old; 94 synchronized(this) { 95 old=writeOwner_; 96 writeOwner_=owner; 97 } 98 return old; 99 } 100 101 102 108 public boolean upgrade(Object owner) throws OwnerNotExistedException 109 { 110 boolean old_value = readOwnerList_.remove(owner); 111 if(!old_value) throw new OwnerNotExistedException("Can't upgrade lock. Read lock owner did not exist"); 113 setWriter(owner); 114 return true; 115 } 116 117 120 public Set readerOwners() 121 { 122 return Collections.unmodifiableSet(readOwnerList_); 123 } 124 125 public void releaseReaderOwners(LockStrategy lock) 126 { 127 int size = readOwnerList_.size(); 128 for (int i = 0; i < size; i++) 129 lock.readLock().unlock(); 130 } 131 132 135 public Object writerOwner() 136 { 137 return writeOwner_; 138 } 139 140 143 public void removeReader(Object owner) 144 { 145 readOwnerList_.remove(owner); 146 } 147 148 151 public void removeWriter() 152 { 153 synchronized(this) { 154 writeOwner_=null; 155 } 156 } 157 158 161 public void removeAll() 162 { 163 removeWriter(); 164 readOwnerList_.clear(); 165 } 166 167 172 public String printInfo() 173 { 174 StringBuffer buf = new StringBuffer (64); 175 buf.append("Read lock owners: ").append(readOwnerList_).append('\n'); 176 buf.append("Write lock owner: ").append(writeOwner_).append('\n'); 177 return buf.toString(); 178 } 179 180 public boolean isReadLocked() { 181 return !readOwnerList_.isEmpty(); 182 } 183 } 184 | Popular Tags |