KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > util > Semaphore


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.util;
31
32 import java.util.logging.Logger JavaDoc;
33
34 /**
35  * The Semaphore handles timed locks.
36  */

37 public class Semaphore {
38   private static final Logger JavaDoc 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   /**
49    * Allocates the semaphore, returns true on success.
50    */

51   public boolean tryAcquire(long timeout, TimeUnit unit)
52     throws InterruptedException JavaDoc
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   /**
82    * Releases the permit.
83    */

84   public void release()
85   {
86     synchronized (this) {
87       _permits++;
88
89       notifyAll();
90     }
91   }
92 }
93
Popular Tags