KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > core > runtime > adaptor > Semaphore


1 /*******************************************************************************
2  * Copyright (c) 2003, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.core.runtime.adaptor;
12
13 /**
14  * Internal class.
15  */

16 public class Semaphore {
17     protected long notifications;
18
19     public Semaphore(int count) {
20         notifications = count;
21     }
22
23     /**
24      * Attempts to acquire this semaphore. Returns only when the semaphore has been acquired.
25      */

26     public synchronized void acquire() {
27         while (true) {
28             if (notifications > 0) {
29                 notifications--;
30                 return;
31             }
32             try {
33                 wait();
34             } catch (InterruptedException JavaDoc e) {
35                 //Ignore
36
}
37         }
38     }
39
40     /**
41      * Attempts to acquire this semaphore. Returns true if it was successfully acquired,
42      * and false otherwise.
43      */

44     public synchronized boolean acquire(long delay) {
45         long start = System.currentTimeMillis();
46         long timeLeft = delay;
47         while (true) {
48             if (notifications > 0) {
49                 notifications--;
50                 return true;
51             }
52             if (timeLeft < 0)
53                 return false;
54             try {
55                 wait(timeLeft);
56             } catch (InterruptedException JavaDoc e) {
57                 //Ignore
58
}
59             timeLeft = start + delay - System.currentTimeMillis();
60         }
61     }
62
63     public synchronized void release() {
64         notifications++;
65         notifyAll();
66     }
67
68     // for debug only
69
public String JavaDoc toString() {
70         return "Semaphore(" + notifications + ")"; //$NON-NLS-1$ //$NON-NLS-2$
71
}
72 }
Popular Tags