KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > sync > Semaphore


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 //NOTE: Tabs are used instead of spaces for indentation.
25
// Make sure that your editor does not replace tabs with spaces.
26
// Set the tab length using your favourite editor to your
27
// visual preference.
28

29 /*
30  * Filename: Lock.java
31  *
32  * Copyright 2000-2001 by iPlanet/Sun Microsystems, Inc.,
33  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
34  * All rights reserved.
35  *
36  * This software is the confidential and proprietary information
37  * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
38  * You shall not disclose such Confidential Information and shall
39  * use it only in accordance with the terms of the license
40  * agreement you entered into with iPlanet/Sun Microsystems.
41  */

42  
43 /**
44  * <BR> <I>$Source: /cvs/glassfish/appserv-commons/src/java/com/sun/enterprise/util/sync/Semaphore.java,v $</I>
45  * @author $Author: tcfujii $
46  * @version $Revision: 1.3 $ $Date: 2005/12/25 04:12:31 $
47  */

48  
49
50 package com.sun.enterprise.util.sync;
51
52 import java.lang.Thread JavaDoc;
53 import java.lang.InterruptedException JavaDoc;
54 import java.lang.IllegalMonitorStateException JavaDoc;
55
56 /**
57  * A <i>Semaphore</i> (counting Semaphore) is a concurrency control construct. It conforms
58  * to the standard acquire-release protocol. Counting Semaphores are widely used in
59  * implementation of multi-threaded bounded resource pools, collections etc.
60  * <p>
61  * A Semaphore maintains a set of totalPermits initialized in a constructor. Method acquire()
62  * blocks in wait till a permit becomes available and then takes it. The release() method needs
63  * to be invoked to add the permit back to the Semaphore and notify a waiting
64  * thread that a permit has become available to use. Method attemptAcquire() is
65  * the same as acquire() except it fails on time-out. It returns true or false
66  * based on whether it succeeded or failed.
67  * <p>
68  * This implementation of Semaphore is non-reentrant i.e. if the a thread that has a
69  * permit re-enters to acquire one more permit, it would be given another permit if
70  * available.
71  * <p>
72  * @author Dhiru Pandey 8/1/2000
73  */

74
75 public class Semaphore {
76
77   /**
78    * Denotes the total number permits available for the Semaphore object
79    */

80   protected long totalPermits; // available permits
81

82 /**
83  * Constructs a new Semaphore Object and sets the total number of permits for the
84  * Semaphore.
85  *
86  * @param initialPermits Sets the total number of permits for the Semaphore
87  */

88   public Semaphore(long initialPermits) {
89     totalPermits = initialPermits; // set the total number of permits
90
}
91
92 /**
93  * This method tries to acquire a permit from the Semaphore. If all the permits are
94  * taken then the calling thread will wait till it is notified that a permit has
95  * become available
96  * <p>
97  * @throws InterruptedException thrown if the calling thread is interrupted during
98  * the execution of acquire()
99  */

100   public void acquire() throws InterruptedException JavaDoc {
101     if (Thread.interrupted())
102       throw new InterruptedException JavaDoc();
103     synchronized (this) {
104       try {
105         while (totalPermits <= 0)
106           wait();
107         --totalPermits;
108       } catch (InterruptedException JavaDoc ie) {
109         notify();
110         throw ie;
111       }
112     }
113   }
114
115 /**
116  * This method is variation on the acquire() method, wherein it takes a waitTime
117  * parameter in milliseconds to decide how long to wait to get a permit. It also
118  * returns a <code>true</code> or <code>false</code> based on whether it was able
119  * to get the permit or not.
120  * <p>
121  * @param waitTime time to wait in milliseconds for the permit to become available
122  * @throws InterruptedException thrown if the calling thread is
123  * interrupted during the execution of attemptAcquire()
124  * @return <code>true</code> if acquire succeeded <code>false</code> otherwise
125  */

126   public boolean attemptAcquire(long waitTime) throws InterruptedException JavaDoc {
127     if (Thread.interrupted())
128       throw new InterruptedException JavaDoc();
129     synchronized (this) {
130       if (totalPermits > 0) { // just like acquire
131
--totalPermits;
132         return true;
133       } else if (waitTime <= 0) { // avoided timed wait
134
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 { // now check for timeout
146
long now = System.currentTimeMillis();
147               timeToWait = waitTime - (now - startTime);
148               if (timeToWait <= 0)
149                 return false;
150             }
151           }
152         } catch (InterruptedException JavaDoc ie) {
153           notify();
154           throw ie;
155         }
156       }
157     }
158   }
159
160  /**
161  * This method returns a permit to the Semaphore and will notify a waiting thread to
162  * go ahead and try to acquire the permit.
163  * <p>
164  * @return void
165  */

166  public synchronized void release() {
167     ++totalPermits;
168     notify();
169   }
170
171 }
172
173
Popular Tags