KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ui > internal > Semaphore


1 /*******************************************************************************
2  * Copyright (c) 2000, 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.ui.internal;
12
13 public class Semaphore {
14     protected long notifications;
15
16     protected Thread JavaDoc operation;
17
18     protected Runnable JavaDoc runnable;
19
20     public Semaphore(Runnable JavaDoc runnable) {
21         this.runnable = runnable;
22         notifications = 0;
23     }
24
25     /**
26      * Attempts to acquire this semaphore. Returns true if it was successfully acquired,
27      * and false otherwise.
28      */

29     public synchronized boolean acquire(long delay) throws InterruptedException JavaDoc {
30         if (Thread.interrupted()) {
31             throw new InterruptedException JavaDoc();
32         }
33         long start = System.currentTimeMillis();
34         long timeLeft = delay;
35         while (true) {
36             if (notifications > 0) {
37                 notifications--;
38                 return true;
39             }
40             if (timeLeft <= 0) {
41                 return false;
42             }
43             wait(timeLeft);
44             timeLeft = start + delay - System.currentTimeMillis();
45         }
46     }
47
48     public boolean equals(Object JavaDoc obj) {
49         return (runnable == ((Semaphore) obj).runnable);
50     }
51
52     public Thread JavaDoc getOperationThread() {
53         return operation;
54     }
55
56     public Runnable JavaDoc getRunnable() {
57         return runnable;
58     }
59
60     public int hashCode() {
61         return runnable == null ? 0 : runnable.hashCode();
62     }
63
64     public synchronized void release() {
65         notifications++;
66         notifyAll();
67     }
68
69     public void setOperationThread(Thread JavaDoc operation) {
70         this.operation = operation;
71     }
72
73     // for debug only
74
public String JavaDoc toString() {
75         return "Semaphore(" + runnable + ")"; //$NON-NLS-1$ //$NON-NLS-2$
76
}
77 }
78
Popular Tags