KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > core > internal > jobs > Semaphore


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

11 package org.eclipse.core.internal.jobs;
12
13 public class Semaphore {
14     protected long notifications;
15     protected Runnable JavaDoc runnable;
16
17     public Semaphore(Runnable JavaDoc runnable) {
18         this.runnable = runnable;
19         notifications = 0;
20     }
21
22     /**
23      * Attempts to acquire this semaphore. Returns true if it was successfully acquired,
24      * and false otherwise.
25      */

26     public synchronized boolean acquire(long delay) throws InterruptedException JavaDoc {
27         if (Thread.interrupted())
28             throw new InterruptedException JavaDoc();
29         long start = System.currentTimeMillis();
30         long timeLeft = delay;
31         while (true) {
32             if (notifications > 0) {
33                 notifications--;
34                 return true;
35             }
36             if (timeLeft <= 0)
37                 return false;
38             wait(timeLeft);
39             timeLeft = start + delay - System.currentTimeMillis();
40         }
41     }
42
43     public boolean equals(Object JavaDoc obj) {
44         return (runnable == ((Semaphore) obj).runnable);
45     }
46
47     public int hashCode() {
48         return runnable == null ? 0 : runnable.hashCode();
49     }
50
51     public synchronized void release() {
52         notifications++;
53         notifyAll();
54     }
55
56     // for debug only
57
public String JavaDoc toString() {
58         return "Semaphore(" + runnable + ")"; //$NON-NLS-1$ //$NON-NLS-2$
59
}
60 }
61
Popular Tags