1 14 15 package EDU.oswego.cs.dl.util.concurrent; 16 17 25 26 27 public class ReentrantLock implements Sync { 28 29 protected Thread owner_ = null; 30 protected long holds_ = 0; 31 32 public void acquire() throws InterruptedException { 33 if (Thread.interrupted()) throw new InterruptedException (); 34 Thread caller = Thread.currentThread(); 35 synchronized(this) { 36 if (caller == owner_) 37 ++holds_; 38 else { 39 try { 40 while (owner_ != null) wait(); 41 owner_ = caller; 42 holds_ = 1; 43 } 44 catch (InterruptedException ex) { 45 notify(); 46 throw ex; 47 } 48 } 49 } 50 } 51 52 53 public boolean attempt(long msecs) throws InterruptedException { 54 if (Thread.interrupted()) throw new InterruptedException (); 55 Thread caller = Thread.currentThread(); 56 synchronized(this) { 57 if (caller == owner_) { 58 ++holds_; 59 return true; 60 } 61 else if (owner_ == null) { 62 owner_ = caller; 63 holds_ = 1; 64 return true; 65 } 66 else if (msecs <= 0) 67 return false; 68 else { 69 long waitTime = msecs; 70 long start = System.currentTimeMillis(); 71 try { 72 for (;;) { 73 wait(waitTime); 74 if (caller == owner_) { 75 ++holds_; 76 return true; 77 } 78 else if (owner_ == null) { 79 owner_ = caller; 80 holds_ = 1; 81 return true; 82 } 83 else { 84 waitTime = msecs - (System.currentTimeMillis() - start); 85 if (waitTime <= 0) 86 return false; 87 } 88 } 89 } 90 catch (InterruptedException ex) { 91 notify(); 92 throw ex; 93 } 94 } 95 } 96 } 97 98 102 public synchronized void release() { 103 if (Thread.currentThread() != owner_) 104 throw new Error ("Illegal Lock usage"); 105 106 if (--holds_ == 0) { 107 owner_ = null; 108 notify(); 109 } 110 } 111 112 122 public synchronized void release(long n) { 123 if (Thread.currentThread() != owner_ || n > holds_) 124 throw new Error ("Illegal Lock usage"); 125 126 holds_ -= n; 127 if (holds_ == 0) { 128 owner_ = null; 129 notify(); 130 } 131 } 132 133 134 139 public synchronized long holds() { 140 if (Thread.currentThread() != owner_) return 0; 141 return holds_; 142 } 143 144 145 146 } 147 148 | Popular Tags |