1 29 30 package com.caucho.util; 31 32 import java.util.logging.Logger ; 33 34 37 public class Semaphore { 38 private static final Logger log = 39 Logger.getLogger(Semaphore.class.getName()); 40 41 private volatile int _permits; 42 43 public Semaphore(int permits, boolean fair) 44 { 45 _permits = permits; 46 } 47 48 51 public boolean tryAcquire(long timeout, TimeUnit unit) 52 throws InterruptedException 53 { 54 long ms = unit.toMillis(timeout); 55 long now = System.currentTimeMillis(); 56 long expire = ms + now; 57 58 synchronized (this) { 59 do { 60 if (_permits > 0) { 61 _permits--; 62 return true; 63 } 64 65 now = System.currentTimeMillis(); 66 long delta = expire - now; 67 if (delta > 0) { 68 wait(delta); 69 70 if (_permits > 0) { 71 _permits--; 72 return true; 73 } 74 } 75 } while (System.currentTimeMillis() < expire); 76 } 77 78 return false; 79 } 80 81 84 public void release() 85 { 86 synchronized (this) { 87 _permits++; 88 89 notifyAll(); 90 } 91 } 92 } 93 | Popular Tags |