KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jofti > oswego > concurrent > FIFOSemaphore


1 /*
2   File: FIFOSemaphore.java
3
4   Originally written by Doug Lea and released into the public domain.
5   This may be used for any purposes whatsoever without acknowledgment.
6   Thanks for the assistance and support of Sun Microsystems Labs,
7   and everyone contributing, testing, and using this code.
8
9   History:
10   Date Who What
11   11Jun1998 dl Create public version
12 */

13
14
15 package com.jofti.oswego.concurrent;
16
17 /**
18  * A First-in/First-out implementation of a Semaphore.
19  * Waiting requests will be satisified in
20  * the order that the processing of those requests got to a certain point.
21  * If this sounds vague it is meant to be. FIFO implies a
22  * logical timestamping at some point in the processing of the
23  * request. To simplify things we don't actually timestamp but
24  * simply store things in a FIFO queue. Thus the order in which
25  * requests enter the queue will be the order in which they come
26  * out. This order need not have any relationship to the order in
27  * which requests were made, nor the order in which requests
28  * actually return to the caller. These depend on Java thread
29  * scheduling which is not guaranteed to be predictable (although
30  * JVMs tend not to go out of their way to be unfair).
31  * <p>[<a HREF="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
32 **/

33
34 public class FIFOSemaphore extends QueuedSemaphore {
35   
36   /**
37    * Create a Semaphore with the given initial number of permits.
38    * Using a seed of one makes the semaphore act as a mutual exclusion lock.
39    * Negative seeds are also allowed, in which case no acquires will proceed
40    * until the number of releases has pushed the number of permits past 0.
41   **/

42
43   public FIFOSemaphore(long initialPermits) {
44     super(new FIFOWaitQueue(), initialPermits);
45   }
46
47   /**
48    * Simple linked list queue used in FIFOSemaphore.
49    * Methods are not synchronized; they depend on synch of callers
50   **/

51
52   protected static class FIFOWaitQueue extends WaitQueue {
53     protected WaitNode head_ = null;
54     protected WaitNode tail_ = null;
55
56     protected void insert(WaitNode w) {
57       if (tail_ == null)
58         head_ = tail_ = w;
59       else {
60         tail_.next = w;
61         tail_ = w;
62       }
63     }
64
65     protected WaitNode extract() {
66       if (head_ == null)
67         return null;
68       else {
69         WaitNode w = head_;
70         head_ = w.next;
71         if (head_ == null) tail_ = null;
72         w.next = null;
73         return w;
74       }
75     }
76   }
77
78 }
79
Popular Tags