KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > SemaphoreImpl


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 package com.sun.enterprise.util;
24
25 /**
26  * Based on Concurrent Programming in Java, Second Edition,
27  * by Doug Lea, page 266
28  *
29  */

30
31 public class SemaphoreImpl implements Semaphore {
32
33     private long numPermits_;
34
35     public SemaphoreImpl(long initialPermits) {
36         numPermits_ = initialPermits;
37     }
38
39     public synchronized void release() {
40         numPermits_++;
41         notify();
42     }
43
44     public void acquire() throws InterruptedException JavaDoc {
45         if( Thread.interrupted()) {
46             throw new InterruptedException JavaDoc();
47         }
48         
49         synchronized (this) {
50             try {
51                 while( numPermits_ <= 0 ) {
52                     wait();
53                 }
54                 numPermits_--;
55             } catch( InterruptedException JavaDoc ie) {
56                 notify();
57                 throw ie;
58             }
59         }
60     }
61
62 }
63
Popular Tags