summaryrefslogtreecommitdiff
path: root/java/JACE/Concurrency/Semaphore.java
blob: 5e558035aee338ea4fcfeab1e842cbcd23c4de02 (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/*************************************************
 *
 * = PACKAGE
 *    JACE.Concurrency
 *
 * = FILENAME
 *    Semaphore.java
 *
 *@author Prashant Jain
 *
 *************************************************/
package JACE.Concurrency;

import java.util.*;
import JACE.ASX.*;

/**
 *     Implementation of Dijkstra's counting semaphore in java.
 * <P>
 *     <EM>This class does not support recursive semantics.</EM>
 */
public class Semaphore extends LockAdapter
{
  static 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;
    }
  
    public int count ()
    {
      return this.count_;
    }
  
    private int count_ = 0;
  }

  /**
   * Create a Semaphore.
   *@param count semaphore count
   */
  public Semaphore (int c)
  {
    this.monitor_.count (c);
    this.owners_ = new Hashtable (c);
  }
  
  /**
   * Create a binary Semaphore.
   */
  public Semaphore ()
  {
    this.monitor_.count (1);
    this.owners_ = new Hashtable (1);
  }
  
  public synchronized int tryAcquire ()
  {
    if (this.monitor_.condition ()) {
      this.monitor_.decrement ();
      setOwner ();
      return AbstractLock.SUCCESS;
    } else
      return AbstractLock.FAILURE;
  }
  
  /**
   * 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 int acquire (TimeValue tv)
    throws TimeoutException, InterruptedException 
  {
    if (this.monitor_.condition ()) {
      this.monitor_.decrement ();
      setOwner ();
      return AbstractLock.SUCCESS;
    }

    numberOfWaiters_++;
    
    try {
      sleepHook ();
      this.monitor_.timedWait (tv);
    } finally {
      numberOfWaiters_--;
    }
    
    this.monitor_.decrement ();
    setOwner ();

    return AbstractLock.SLEEPHOOK;
  }
  
  public synchronized int release ()
  {
    if (!isOwner ())
      return AbstractLock.FAILURE;
    
    if (!signalNextRenewer ()) {
      this.monitor_.increment ();
      this.monitor_.signal ();
      clearOwner ();
    }
    
    return AbstractLock.SUCCESS;
  }
  
  /**
   * Checks any objects in the renewers queue, giving one of them
   * the lock if it is appropriate.  Assumes the synchronization
   * lock is already held.
   *
   *@return true if a renewer was signaled, else false
   */
  protected boolean signalNextRenewer ()
  {
    // First find the renewer with the minimum yieldTo count, processing
    // all of them along the way.
    if (this.renewers_.size() > 0) {
      
      RenewObject renewer = (RenewObject)renewers_.
	elementAt (renewers_.size () - 1);
      
      renewer.decrementYieldTo ();
      
      for (int i = this.renewers_.size() - 2; i >=0; i--) {
	
	RenewObject rwo = (RenewObject)renewers_.elementAt (i);
	
	rwo.decrementYieldTo ();
	
	renewer = renewer.min (rwo);
      }
      
      // If the renewer with the minimum yieldTo count has yielded to
      // enough threads, or if there are no waiting threads, it should
      // be signaled (thus, it wakes up and obtains the lock again).
      
      if (renewer.condition () || numberOfWaiters_ == 0) {
	// Note that we leave monitor_.inUse in the true state so
	// we are assured that only the renewer (and not another
	// Thread that does an acquire) will gain control.  This
	// is important since the renew method can't be synchronized
	// in its current implementation.
	renewers_.removeElement(renewer);

	synchronized (renewer) {
	  renewer.signal ();
	}
  
	return true;
      }
    }

    return false;
  }

  public int renew (int requeuePosition, 
		    JACE.ASX.TimeValue timeout) 
    throws InterruptedException,
	   TimeoutException
  {
    RenewObject rwo;

    synchronized (this) {

      if (!this.isOwner ())
	return AbstractLock.FAILURE;
      
      if (numberOfWaiters_ == 0 || 
	  requeuePosition == 0 ||
	  this.monitor_.condition ())
	return AbstractLock.SUCCESS;

      if (requeuePosition < 0 || requeuePosition > numberOfWaiters_)
	requeuePosition = numberOfWaiters_;
      
      rwo = new RenewObject (requeuePosition);

      this.release ();
      this.renewers_.addElement (rwo);
    }

    boolean exceptionOccured = true;
    try {
      synchronized (rwo) {
	rwo.timedWait (timeout);
	
	exceptionOccured = false;
      }
    } finally {
      synchronized (this) {

	if (exceptionOccured) {
	  if (!renewers_.removeElement (rwo)) {  
	    setOwner ();
	    release ();
	  } 
	} else {
	  setOwner();
	}
      }
    }
  
    // By this point, we should know that we have the lock.  The inUse
    // flag is never set to false in the release() call from the Thread
    // that gave us control.  That thread also set the owner value.
    
    return AbstractLock.SUCCESS;
  }

  protected boolean isOwner ()
  {
    return owners_.containsKey (accessorID());
  }

  protected void setOwner ()
  {
    owners_.put (accessorID(), this);
  }

  protected void clearOwner ()
  {
    owners_.remove (accessorID());
  }

  private TimedWaitSAdapter monitor_ = new TimedWaitSAdapter (this);
  // The monitor (adapter) to wait on

  private Hashtable owners_;
  private Vector renewers_ = new Vector ();
  private int numberOfWaiters_ = 0;
}