1 14 15 16 package EDU.oswego.cs.dl.util.concurrent; 17 18 48 49 50 public final class WaiterPreferenceSemaphore extends Semaphore { 51 52 55 56 public WaiterPreferenceSemaphore(long initial) { super(initial); } 57 58 59 protected long waits_ = 0; 60 61 public void acquire() throws InterruptedException { 62 if (Thread.interrupted()) throw new InterruptedException (); 63 synchronized(this) { 64 68 if (permits_ > waits_) { 69 --permits_; 70 return; 71 } 72 else { 73 ++waits_; 74 try { 75 for (;;) { 76 wait(); 77 if (permits_ > 0) { 78 --waits_; 79 --permits_; 80 return; 81 } 82 } 83 } 84 catch(InterruptedException ex) { 85 --waits_; 86 notify(); 87 throw ex; 88 } 89 } 90 } 91 } 92 93 public boolean attempt(long msecs) throws InterruptedException { 94 if (Thread.interrupted()) throw new InterruptedException (); 95 96 synchronized(this) { 97 if (permits_ > waits_) { 98 --permits_; 99 return true; 100 } 101 else if (msecs <= 0) 102 return false; 103 else { 104 ++waits_; 105 106 long startTime = System.currentTimeMillis(); 107 long waitTime = msecs; 108 109 try { 110 for (;;) { 111 wait(waitTime); 112 if (permits_ > 0) { 113 --waits_; 114 --permits_; 115 return true; 116 } 117 else { waitTime = msecs - (System.currentTimeMillis() - startTime); 119 if (waitTime <= 0) { 120 --waits_; 121 return false; 122 } 123 } 124 } 125 } 126 catch(InterruptedException ex) { 127 --waits_; 128 notify(); 129 throw ex; 130 } 131 } 132 } 133 } 134 135 public synchronized void release() { 136 ++permits_; 137 notify(); 138 } 139 140 141 public synchronized void release(long n) { 142 permits_ += n; 143 for (long i = 0; i < n; ++i) notify(); 144 } 145 146 } 147 148 | Popular Tags |