1 23 24 29 42 43 48 49 50 package com.sun.enterprise.util.sync; 51 52 import java.lang.Thread ; 53 import java.lang.InterruptedException ; 54 import java.lang.IllegalMonitorStateException ; 55 56 74 75 public class Semaphore { 76 77 80 protected long totalPermits; 82 88 public Semaphore(long initialPermits) { 89 totalPermits = initialPermits; } 91 92 100 public void acquire() throws InterruptedException { 101 if (Thread.interrupted()) 102 throw new InterruptedException (); 103 synchronized (this) { 104 try { 105 while (totalPermits <= 0) 106 wait(); 107 --totalPermits; 108 } catch (InterruptedException ie) { 109 notify(); 110 throw ie; 111 } 112 } 113 } 114 115 126 public boolean attemptAcquire(long waitTime) throws InterruptedException { 127 if (Thread.interrupted()) 128 throw new InterruptedException (); 129 synchronized (this) { 130 if (totalPermits > 0) { --totalPermits; 132 return true; 133 } else if (waitTime <= 0) { return false; 135 } else { 136 try { 137 long startTime = System.currentTimeMillis(); 138 long timeToWait = waitTime; 139 140 while (true) { 141 wait(timeToWait); 142 if (totalPermits > 0) { 143 --totalPermits; 144 return true; 145 } else { long now = System.currentTimeMillis(); 147 timeToWait = waitTime - (now - startTime); 148 if (timeToWait <= 0) 149 return false; 150 } 151 } 152 } catch (InterruptedException ie) { 153 notify(); 154 throw ie; 155 } 156 } 157 } 158 } 159 160 166 public synchronized void release() { 167 ++totalPermits; 168 notify(); 169 } 170 171 } 172 173 | Popular Tags |