blob: 6c5427bb0c037dca3554b4f2fab7dad30b525166 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
/*************************************************
*
* = PACKAGE
* JACE.Concurrency
*
* = FILENAME
* Semaphore.java
*
*@author Prashant Jain
*
*************************************************/
package JACE.Concurrency;
import java.util.*;
import JACE.ASX.*;
class TimedWaitSAdapter extends JACE.ASX.TimedWait
{
TimedWaitSAdapter (Object obj)
{
super (obj);
}
// Check to see if there are any semaphores available.
public boolean condition ()
{
return this.count_ > 0;
}
// Increment the count by one
public void increment ()
{
this.count_++;
}
// Decrement the count by one
public void decrement ()
{
this.count_--;
}
// Set the count
public void count (int c)
{
this.count_ = c;
}
private int count_ = 0;
}
/**
* <hr>
* <h2>SYNOPSIS</h2>
* Implementation of Dijkstra's counting semaphore in java.
*/
public class Semaphore
{
/**
* Create a Semaphore.
*@param count semaphore count
*/
public Semaphore (int c)
{
this.monitor_.count (c);
}
/**
* Acquire the Semaphore. Note that this will block.
*@exception InterruptedException exception during wait
*/
public synchronized void acquire () throws InterruptedException
{
this.monitor_.timedWait ();
this.monitor_.decrement ();
}
/**
* Acquire the Semaphore. Throws a TimeoutException if the semaphore
* isn't acquired before the given absolute time.
*@param tv time (TimeValue) to wait until before throwing a
* TimeoutException (unless the semaphore is acquired before that)
*@exception TimeoutException wait timed out exception
*@exception InterruptedException exception during wait
*/
public synchronized void acquire (TimeValue tv)
throws JACE.ASX.TimeoutException, InterruptedException
{
this.monitor_.timedWait (tv);
this.monitor_.decrement ();
}
/**
* Release the Semaphore.
*/
public synchronized void release ()
{
this.monitor_.increment ();
this.monitor_.signal ();
}
private TimedWaitSAdapter monitor_ = new TimedWaitSAdapter (this);
// The monitor (adapter) to wait on
}
|