| ||||
|
Code - Class EDU.oswego.cs.dl.util.concurrent.PrioritySemaphore1 /* 2 File: PrioritySemaphore.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 EDU.oswego.cs.dl.util.concurrent; 16 17 /** 18 * A Semaphore that grants requests to threads with higher 19 * Thread priority rather than lower priority when there is 20 * contention. Ordering of requests with the same priority 21 * is approximately FIFO. 22 * Priorities are based on Thread.getPriority. 23 * Changing the priority of an already-waiting thread does NOT 24 * change its ordering. This class also does not specially deal with priority 25 * inversion -- when a new high-priority thread enters 26 * while a low-priority thread is currently running, their 27 * priorities are <em>not</em> artificially manipulated. 28 * <p>[<a HREF="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>] 29 30 **/ 31 32 public class PrioritySemaphore extends QueuedSemaphore { 33 34 /** 35 * Create a Semaphore with the given initial number of permits. 36 * Using a seed of one makes the semaphore act as a mutual exclusion lock. 37 * Negative seeds are also allowed, in which case no acquires will proceed 38 * until the number of releases has pushed the number of permits past 0. 39 **/ 40 41 42 public PrioritySemaphore(long initialPermits) { 43 super(new PriorityWaitQueue(), initialPermits); 44 } 45 46 protected static class PriorityWaitQueue extends WaitQueue { 47 48 49 /** An array of wait queues, one per priority **/ 50 protected final FIFOSemaphore.FIFOWaitQueue[] cells_ = 51 new FIFOSemaphore.FIFOWaitQueue[Thread.MAX_PRIORITY - 52 Thread.MIN_PRIORITY + 1]; 53 54 /** 55 * The index of the highest priority cell that may need to be signalled, 56 * or -1 if none. Used to minimize array traversal. 57 **/ 58 59 protected int maxIndex_ = -1; 60 61 protected PriorityWaitQueue() { 62 for (int i = 0; i < cells_.length; ++i) 63 cells_[i] = new FIFOSemaphore.FIFOWaitQueue(); 64 } 65 66 protected void insert(WaitNode w) { 67 int idx = Thread.currentThread().getPriority() - Thread.MIN_PRIORITY; 68 cells_[idx].insert(w); 69 if (idx > maxIndex_) maxIndex_ = idx; 70 } 71 72 protected WaitNode extract() { 73 for (;;) { 74 int idx = maxIndex_; 75 if (idx < 0) 76 return null; 77 WaitNode w = cells_[idx].extract(); 78 if (w != null) 79 return w; 80 else 81 --maxIndex_; 82 } 83 } 84 } 85 86 87 88 89 90 } 91 |
|||
Java API By Example, From Geeks To Geeks. |
Conditions of Use |
About Us
© 2002 - 2005, KickJava.com, or its affiliates
|