1 25 26 package org.objectweb.perseus.concurrency.pessimistic; 27 28 import org.objectweb.perseus.concurrency.api.ConcurrencyException; 29 import org.objectweb.perseus.concurrency.api.RolledBackConcurrencyException; 30 import org.objectweb.perseus.concurrency.lib.RWLockValue; 31 import org.objectweb.perseus.dependency.api.DependencyGraph; 32 33 import java.util.Set ; 34 import java.util.HashSet ; 35 import java.util.List ; 36 import java.util.ArrayList ; 37 38 45 public final class RWPri2RLock extends Lock { 46 50 protected Object writer = null; 51 54 int waiter = 0; 55 59 protected Set readers = new HashSet (); 60 61 public RWPri2RLock() { 62 } 63 64 public RWPri2RLock(Object hints, DependencyGraph dg) { 65 super(hints, dg); 66 } 67 68 73 public synchronized void readIntention(Object ctxt) 74 throws ConcurrencyException { 75 boolean ok; 76 do { 77 ok = writer == null || writer.equals(ctxt); 78 if (!ok) { 79 waiter ++; 80 Object w = writer; 81 try { 82 if (!dg.addVertex(ctxt, w)) { 83 throw new RolledBackConcurrencyException("Deadlock"); 84 } 85 wait(); 86 } catch (InterruptedException e) { 87 throw new ConcurrencyException( 88 "Waiting of a read intention has been interupted:", e); 89 } finally { 90 waiter --; 91 dg.removeVertex(ctxt, w); 92 } 93 } 94 } while (!ok); 95 reservations--; 96 readers.add(ctxt); 97 } 99 100 105 public synchronized void writeIntention(Object ctxt) 106 throws ConcurrencyException { 107 boolean ok; 108 do { 109 if (writer == null) { 110 int r = readers.size(); 111 ok = r == 0 || (r == 1 && readers.contains(ctxt)); 112 } else { 113 ok = writer.equals(ctxt); 114 } 115 if (!ok) { 116 List l = new ArrayList (); 117 if (writer == null) { 118 l.addAll(readers); 119 } else { 120 l.add(writer); 121 } 122 waiter ++; 123 try { 124 for (int i = 0; i < l.size(); ++i) { 125 if (!dg.addVertex(ctxt, l.get(i))) { 126 throw new RolledBackConcurrencyException("Deadlock"); 127 } 128 } 129 wait(); 130 } catch (InterruptedException e) { 131 throw new ConcurrencyException( 132 "Waiting of a write intention has been interupted:", e); 133 } finally { 134 waiter --; 135 for (int i = 0; i < l.size(); ++i) { 136 dg.removeVertex(ctxt, l.get(i)); 137 } 138 } 139 } 140 } while (!ok); 141 reservations--; 142 writer = ctxt; 143 } 145 146 154 public synchronized boolean close(Object ctxt) { 155 readers.remove(ctxt); 157 if (writer != null && writer.equals(ctxt)) { 158 writer = null; 159 } 160 boolean res = reservations == 0 161 && waiter == 0 && readers.isEmpty() && writer == null; 162 if (!res) { 163 notifyAll(); 164 } 165 return res; 166 } 167 168 public synchronized byte getMax() { 169 if (writer != null) return RWLockValue.WRITE; 170 if (!readers.isEmpty()) return RWLockValue.READ; 171 return RWLockValue.NOLOCK; 172 } 173 174 } 175 | Popular Tags |