ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.33
Committed: Sun Jan 4 22:57:29 2004 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.32: +3 -3 lines
Log Message:
Better param names; simpler fairness handling

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
5 */
6
7 package java.util.concurrent;
8 import java.util.*;
9 import java.util.concurrent.locks.*;
10 import java.util.concurrent.atomic.*;
11
12 /**
13 * A counting semaphore. Conceptually, a semaphore maintains a set of
14 * permits. Each {@link #acquire} blocks if necessary until a permit is
15 * available, and then takes it. Each {@link #release} adds a permit,
16 * potentially releasing a blocking acquirer.
17 * However, no actual permit objects are used; the <tt>Semaphore</tt> just
18 * keeps a count of the number available and acts accordingly.
19 *
20 * <p>Semaphores are often used to restrict the number of threads than can
21 * access some (physical or logical) resource. For example, here is
22 * a class that uses a semaphore to control access to a pool of items:
23 * <pre>
24 * class Pool {
25 * private static final MAX_AVAILABLE = 100;
26 * private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
27 *
28 * public Object getItem() throws InterruptedException {
29 * available.acquire();
30 * return getNextAvailableItem();
31 * }
32 *
33 * public void putItem(Object x) {
34 * if (markAsUnused(x))
35 * available.release();
36 * }
37 *
38 * // Not a particularly efficient data structure; just for demo
39 *
40 * protected Object[] items = ... whatever kinds of items being managed
41 * protected boolean[] used = new boolean[MAX_AVAILABLE];
42 *
43 * protected synchronized Object getNextAvailableItem() {
44 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
45 * if (!used[i]) {
46 * used[i] = true;
47 * return items[i];
48 * }
49 * }
50 * return null; // not reached
51 * }
52 *
53 * protected synchronized boolean markAsUnused(Object item) {
54 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
55 * if (item == items[i]) {
56 * if (used[i]) {
57 * used[i] = false;
58 * return true;
59 * } else
60 * return false;
61 * }
62 * }
63 * return false;
64 * }
65 *
66 * }
67 * </pre>
68 *
69 * <p>Before obtaining an item each thread must acquire a permit from
70 * the semaphore, guaranteeing that an item is available for use. When
71 * the thread has finished with the item it is returned back to the
72 * pool and a permit is returned to the semaphore, allowing another
73 * thread to acquire that item. Note that no synchronization lock is
74 * held when {@link #acquire} is called as that would prevent an item
75 * from being returned to the pool. The semaphore encapsulates the
76 * synchronization needed to restrict access to the pool, separately
77 * from any synchronization needed to maintain the consistency of the
78 * pool itself.
79 *
80 * <p>A semaphore initialized to one, and which is used such that it
81 * only has at most one permit available, can serve as a mutual
82 * exclusion lock. This is more commonly known as a <em>binary
83 * semaphore</em>, because it only has two states: one permit
84 * available, or zero permits available. When used in this way, the
85 * binary semaphore has the property (unlike many {@link Lock}
86 * implementations), that the &quot;lock&quot; can be released by a
87 * thread other than the owner (as semaphores have no notion of
88 * ownership). This can be useful in some specialized contexts, such
89 * as deadlock recovery.
90 *
91 * <p> The constructor for this class accepts a <em>fairness</em>
92 * parameter. When set false, this class makes no guarantees about the
93 * order in which threads acquire permits. In particular, <em>barging</em> is
94 * permitted, that is, a thread invoking {@link #acquire} can be
95 * allocated a permit ahead of a thread that has been waiting. When
96 * fairness is set true, the semaphore guarantees that threads
97 * invoking any of the {@link #acquire() acquire} methods are
98 * allocated permits in the order in which their invocation of those
99 * methods was processed (first-in-first-out; FIFO). Note that FIFO
100 * ordering necessarily applies to specific internal points of
101 * execution within these methods. So, it is possible for one thread
102 * to invoke <tt>acquire</tt> before another, but reach the ordering
103 * point after the other, and similarly upon return from the method.
104 *
105 * <p>Generally, semaphores used to control resource access should be
106 * initialized as fair, to ensure that no thread is starved out from
107 * accessing a resource. When using semaphores for other kinds of
108 * synchronization control, the throughput advantages of non-fair
109 * ordering often outweigh fairness considerations.
110 *
111 * <p>This class also provides convenience methods to {@link
112 * #acquire(int) acquire} and {@link #release(int) release} multiple
113 * permits at a time. Beware of the increased risk of indefinite
114 * postponement when these methods are used without fairness set true.
115 *
116 * @since 1.5
117 * @author Doug Lea
118 *
119 */
120
121 public class Semaphore implements java.io.Serializable {
122 private static final long serialVersionUID = -3222578661600680210L;
123 /** All mechanics via AbstractQueuedSynchronizer subclass */
124 private final Sync sync;
125
126 /**
127 * Synchronization implementation for semaphore.
128 * Uses AQS state to represent permits
129 */
130 private final static class Sync extends AbstractQueuedSynchronizer {
131 final boolean fair;
132 Sync(int permits, boolean fair) {
133 this.fair = fair;
134 setState(permits);
135 }
136
137 public int getPermits() {
138 return getState();
139 }
140
141 public int tryAcquireShared(boolean isFirst, int acquires) {
142 if (!isFirst && fair)
143 return -1;
144 for (;;) {
145 int available = getState();
146 int remaining = available - acquires;
147 if (remaining < 0 ||
148 compareAndSetState(available, remaining))
149 return remaining;
150 }
151 }
152
153 protected boolean tryReleaseShared(int releases) {
154 for (;;) {
155 int p = getState();
156 if (compareAndSetState(p, p + releases))
157 return true;
158 }
159 }
160
161 void reducePermits(int reductions) {
162 for (;;) {
163 int current = getState();
164 int next = current - reductions;
165 if (compareAndSetState(current, next))
166 return;
167 }
168 }
169
170 int drainPermits() {
171 for (;;) {
172 int current = getState();
173 if (current == 0 || compareAndSetState(current, 0))
174 return current;
175 }
176 }
177 }
178
179 /**
180 * Construct a <tt>Semaphore</tt> with the given number of
181 * permits and the given fairness setting.
182 * @param permits the initial number of permits available. This
183 * value may be negative, in which case releases must
184 * occur before any acquires will be granted.
185 * @param fair true if this semaphore will guarantee first-in
186 * first-out granting of permits under contention, else false.
187 */
188 public Semaphore(int permits, boolean fair) {
189 sync = new Sync(permits, fair);
190 }
191
192 /**
193 * Acquires a permit from this semaphore, blocking until one is
194 * available, or the thread is {@link Thread#interrupt interrupted}.
195 *
196 * <p>Acquires a permit, if one is available and returns immediately,
197 * reducing the number of available permits by one.
198 * <p>If no permit is available then the current thread becomes
199 * disabled for thread scheduling purposes and lies dormant until
200 * one of two things happens:
201 * <ul>
202 * <li>Some other thread invokes the {@link #release} method for this
203 * semaphore and the current thread is next to be assigned a permit; or
204 * <li>Some other thread {@link Thread#interrupt interrupts} the current
205 * thread.
206 * </ul>
207 *
208 * <p>If the current thread:
209 * <ul>
210 * <li>has its interrupted status set on entry to this method; or
211 * <li>is {@link Thread#interrupt interrupted} while waiting
212 * for a permit,
213 * </ul>
214 * then {@link InterruptedException} is thrown and the current thread's
215 * interrupted status is cleared.
216 *
217 * @throws InterruptedException if the current thread is interrupted
218 *
219 * @see Thread#interrupt
220 */
221 public void acquire() throws InterruptedException {
222 sync.acquireSharedInterruptibly(1);
223 }
224
225 /**
226 * Acquires a permit from this semaphore, blocking until one is
227 * available.
228 *
229 * <p>Acquires a permit, if one is available and returns immediately,
230 * reducing the number of available permits by one.
231 * <p>If no permit is available then the current thread becomes
232 * disabled for thread scheduling purposes and lies dormant until
233 * some other thread invokes the {@link #release} method for this
234 * semaphore and the current thread is next to be assigned a permit.
235 *
236 * <p>If the current thread
237 * is {@link Thread#interrupt interrupted} while waiting
238 * for a permit then it will continue to wait, but the time at which
239 * the thread is assigned a permit may change compared to the time it
240 * would have received the permit had no interruption occurred. When the
241 * thread does return from this method its interrupt status will be set.
242 *
243 */
244 public void acquireUninterruptibly() {
245 sync.acquireSharedUninterruptibly(1);
246 }
247
248 /**
249 * Acquires a permit from this semaphore, only if one is available at the
250 * time of invocation.
251 * <p>Acquires a permit, if one is available and returns immediately,
252 * with the value <tt>true</tt>,
253 * reducing the number of available permits by one.
254 *
255 * <p>If no permit is available then this method will return
256 * immediately with the value <tt>false</tt>.
257 *
258 * <p>Even when this semaphore has been set to use a
259 * fair ordering policy, a call to <tt>tryAcquire()</tt> <em>will</em>
260 * immediately acquire a permit if one is available, whether or not
261 * other threads are currently waiting.
262 * This &quot;barging&quot; behavior can be useful in certain
263 * circumstances, even though it breaks fairness. If you want to honor
264 * the fairness setting, then use
265 * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
266 * which is almost equivalent (it also detects interruption).
267 *
268 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
269 * otherwise.
270 */
271 public boolean tryAcquire() {
272 return sync.tryAcquireShared(true, 1) >= 0;
273 }
274
275 /**
276 * Acquires a permit from this semaphore, if one becomes available
277 * within the given waiting time and the
278 * current thread has not been {@link Thread#interrupt interrupted}.
279 * <p>Acquires a permit, if one is available and returns immediately,
280 * with the value <tt>true</tt>,
281 * reducing the number of available permits by one.
282 * <p>If no permit is available then
283 * the current thread becomes disabled for thread scheduling
284 * purposes and lies dormant until one of three things happens:
285 * <ul>
286 * <li>Some other thread invokes the {@link #release} method for this
287 * semaphore and the current thread is next to be assigned a permit; or
288 * <li>Some other thread {@link Thread#interrupt interrupts} the current
289 * thread; or
290 * <li>The specified waiting time elapses.
291 * </ul>
292 * <p>If a permit is acquired then the value <tt>true</tt> is returned.
293 * <p>If the current thread:
294 * <ul>
295 * <li>has its interrupted status set on entry to this method; or
296 * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
297 * a permit,
298 * </ul>
299 * then {@link InterruptedException} is thrown and the current thread's
300 * interrupted status is cleared.
301 * <p>If the specified waiting time elapses then the value <tt>false</tt>
302 * is returned.
303 * If the time is less than or equal to zero, the method will not wait
304 * at all.
305 *
306 * @param timeout the maximum time to wait for a permit
307 * @param unit the time unit of the <tt>timeout</tt> argument.
308 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
309 * if the waiting time elapsed before a permit was acquired.
310 *
311 * @throws InterruptedException if the current thread is interrupted
312 *
313 * @see Thread#interrupt
314 *
315 */
316 public boolean tryAcquire(long timeout, TimeUnit unit)
317 throws InterruptedException {
318 return sync.acquireSharedTimed(1, unit.toNanos(timeout));
319 }
320
321 /**
322 * Releases a permit, returning it to the semaphore.
323 * <p>Releases a permit, increasing the number of available permits
324 * by one.
325 * If any threads are blocking trying to acquire a permit, then one
326 * is selected and given the permit that was just released.
327 * That thread is re-enabled for thread scheduling purposes.
328 * <p>There is no requirement that a thread that releases a permit must
329 * have acquired that permit by calling {@link #acquire}.
330 * Correct usage of a semaphore is established by programming convention
331 * in the application.
332 */
333 public void release() {
334 sync.releaseShared(1);
335 }
336
337 /**
338 * Acquires the given number of permits from this semaphore,
339 * blocking until all are available,
340 * or the thread is {@link Thread#interrupt interrupted}.
341 *
342 * <p>Acquires the given number of permits, if they are available,
343 * and returns immediately,
344 * reducing the number of available permits by the given amount.
345 *
346 * <p>If insufficient permits are available then the current thread becomes
347 * disabled for thread scheduling purposes and lies dormant until
348 * one of two things happens:
349 * <ul>
350 * <li>Some other thread invokes one of the {@link #release() release}
351 * methods for this semaphore, the current thread is next to be assigned
352 * permits and the number of available permits satisfies this request; or
353 * <li>Some other thread {@link Thread#interrupt interrupts} the current
354 * thread.
355 * </ul>
356 *
357 * <p>If the current thread:
358 * <ul>
359 * <li>has its interrupted status set on entry to this method; or
360 * <li>is {@link Thread#interrupt interrupted} while waiting
361 * for a permit,
362 * </ul>
363 * then {@link InterruptedException} is thrown and the current thread's
364 * interrupted status is cleared.
365 * Any permits that were to be assigned to this thread are instead
366 * assigned to the next waiting thread(s), as if
367 * they had been made available by a call to {@link #release()}.
368 *
369 * @param permits the number of permits to acquire
370 *
371 * @throws InterruptedException if the current thread is interrupted
372 * @throws IllegalArgumentException if permits less than zero.
373 *
374 * @see Thread#interrupt
375 */
376 public void acquire(int permits) throws InterruptedException {
377 if (permits < 0) throw new IllegalArgumentException();
378 sync.acquireSharedInterruptibly(permits);
379 }
380
381 /**
382 * Acquires the given number of permits from this semaphore,
383 * blocking until all are available.
384 *
385 * <p>Acquires the given number of permits, if they are available,
386 * and returns immediately,
387 * reducing the number of available permits by the given amount.
388 *
389 * <p>If insufficient permits are available then the current thread becomes
390 * disabled for thread scheduling purposes and lies dormant until
391 * some other thread invokes one of the {@link #release() release}
392 * methods for this semaphore, the current thread is next to be assigned
393 * permits and the number of available permits satisfies this request.
394 *
395 * <p>If the current thread
396 * is {@link Thread#interrupt interrupted} while waiting
397 * for permits then it will continue to wait and its position in the
398 * queue is not affected. When the
399 * thread does return from this method its interrupt status will be set.
400 *
401 * @param permits the number of permits to acquire
402 * @throws IllegalArgumentException if permits less than zero.
403 *
404 */
405 public void acquireUninterruptibly(int permits) {
406 if (permits < 0) throw new IllegalArgumentException();
407 sync.acquireSharedUninterruptibly(permits);
408 }
409
410 /**
411 * Acquires the given number of permits from this semaphore, only if
412 * all are available at the time of invocation.
413 * <p>Acquires the given number of permits, if they are available, and
414 * returns immediately, with the value <tt>true</tt>,
415 * reducing the number of available permits by the given amount.
416 *
417 * <p>If insufficient permits are available then this method will return
418 * immediately with the value <tt>false</tt> and the number of available
419 * permits is unchanged.
420 *
421 * <p>Even when this semaphore has been set to use a fair ordering
422 * policy, a call to <tt>tryAcquire</tt> <em>will</em>
423 * immediately acquire a permit if one is available, whether or
424 * not other threads are currently waiting. This
425 * &quot;barging&quot; behavior can be useful in certain
426 * circumstances, even though it breaks fairness. If you want to
427 * honor the fairness setting, then use {@link #tryAcquire(int,
428 * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
429 * which is almost equivalent (it also detects interruption).
430 *
431 * @param permits the number of permits to acquire
432 *
433 * @return <tt>true</tt> if the permits were acquired and <tt>false</tt>
434 * otherwise.
435 * @throws IllegalArgumentException if permits less than zero.
436 */
437 public boolean tryAcquire(int permits) {
438 if (permits < 0) throw new IllegalArgumentException();
439 return sync.tryAcquireShared(true, permits) >= 0;
440 }
441
442 /**
443 * Acquires the given number of permits from this semaphore, if all
444 * become available within the given waiting time and the
445 * current thread has not been {@link Thread#interrupt interrupted}.
446 * <p>Acquires the given number of permits, if they are available and
447 * returns immediately, with the value <tt>true</tt>,
448 * reducing the number of available permits by the given amount.
449 * <p>If insufficient permits are available then
450 * the current thread becomes disabled for thread scheduling
451 * purposes and lies dormant until one of three things happens:
452 * <ul>
453 * <li>Some other thread invokes one of the {@link #release() release}
454 * methods for this semaphore, the current thread is next to be assigned
455 * permits and the number of available permits satisfies this request; or
456 * <li>Some other thread {@link Thread#interrupt interrupts} the current
457 * thread; or
458 * <li>The specified waiting time elapses.
459 * </ul>
460 * <p>If the permits are acquired then the value <tt>true</tt> is returned.
461 * <p>If the current thread:
462 * <ul>
463 * <li>has its interrupted status set on entry to this method; or
464 * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
465 * the permits,
466 * </ul>
467 * then {@link InterruptedException} is thrown and the current thread's
468 * interrupted status is cleared.
469 * Any permits that were to be assigned to this thread, are instead
470 * assigned to the next waiting thread(s), as if
471 * they had been made available by a call to {@link #release()}.
472 *
473 * <p>If the specified waiting time elapses then the value <tt>false</tt>
474 * is returned.
475 * If the time is
476 * less than or equal to zero, the method will not wait at all.
477 * Any permits that were to be assigned to this thread, are instead
478 * assigned to the next waiting thread(s), as if
479 * they had been made available by a call to {@link #release()}.
480 *
481 * @param permits the number of permits to acquire
482 * @param timeout the maximum time to wait for the permits
483 * @param unit the time unit of the <tt>timeout</tt> argument.
484 * @return <tt>true</tt> if all permits were acquired and <tt>false</tt>
485 * if the waiting time elapsed before all permits were acquired.
486 *
487 * @throws InterruptedException if the current thread is interrupted
488 * @throws IllegalArgumentException if permits less than zero.
489 *
490 * @see Thread#interrupt
491 *
492 */
493 public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
494 throws InterruptedException {
495 if (permits < 0) throw new IllegalArgumentException();
496 return sync.acquireSharedTimed(permits, unit.toNanos(timeout));
497 }
498
499 /**
500 * Releases the given number of permits, returning them to the semaphore.
501 * <p>Releases the given number of permits, increasing the number of
502 * available permits by that amount.
503 * If any threads are blocking trying to acquire permits, then the
504 * one that has been waiting the longest
505 * is selected and given the permits that were just released.
506 * If the number of available permits satisfies that thread's request
507 * then that thread is re-enabled for thread scheduling purposes; otherwise
508 * the thread continues to wait. If there are still permits available
509 * after the first thread's request has been satisfied, then those permits
510 * are assigned to the next waiting thread. If it is satisfied then it is
511 * re-enabled for thread scheduling purposes. This continues until there
512 * are insufficient permits to satisfy the next waiting thread, or there
513 * are no more waiting threads.
514 *
515 * <p>There is no requirement that a thread that releases a permit must
516 * have acquired that permit by calling {@link Semaphore#acquire acquire}.
517 * Correct usage of a semaphore is established by programming convention
518 * in the application.
519 *
520 * @param permits the number of permits to release
521 * @throws IllegalArgumentException if permits less than zero.
522 */
523 public void release(int permits) {
524 if (permits < 0) throw new IllegalArgumentException();
525 sync.releaseShared(permits);
526 }
527
528 /**
529 * Return the current number of permits available in this semaphore.
530 * <p>This method is typically used for debugging and testing purposes.
531 * @return the number of permits available in this semaphore.
532 */
533 public int availablePermits() {
534 return sync.getPermits();
535 }
536
537 /**
538 * Acquire and return all permits that are immediately available.
539 * @return the number of permits
540 */
541 public int drainPermits() {
542 return sync.drainPermits();
543 }
544
545 /**
546 * Shrink the number of available permits by the indicated
547 * reduction. This method can be useful in subclasses that
548 * use semaphores to track resources that become
549 * unavailable. This method differs from <tt>acquire</tt>
550 * in that it does not block waiting for permits to become
551 * available.
552 * @param reduction the number of permits to remove
553 * @throws IllegalArgumentException if reduction is negative
554 */
555 protected void reducePermits(int reduction) {
556 if (reduction < 0) throw new IllegalArgumentException();
557 sync.reducePermits(reduction);
558 }
559
560 /**
561 * Return true if this semaphore has fairness set true.
562 * @return true if this semaphore has fairness set true.
563 */
564 public boolean isFair() {
565 return sync.fair;
566 }
567
568 /**
569 * Queries whether any threads are waiting to acquire. Note that
570 * because cancellations may occur at any time, a <tt>true</tt>
571 * return does not guarantee that any other thread will ever
572 * acquire. This method is designed primarily for use in
573 * monitoring of the system state.
574 *
575 * @return true if there may be other threads waiting to acquire
576 * the lock.
577 */
578 public final boolean hasQueuedThreads() {
579 return sync.hasQueuedThreads();
580 }
581
582 /**
583 * Returns an estimate of the number of threads waiting to
584 * acquire. The value is only an estimate because the number of
585 * threads may change dynamically while this method traverses
586 * internal data structures. This method is designed for use in
587 * monitoring of the system state, not for synchronization
588 * control.
589 * @return the estimated number of threads waiting for this lock
590 */
591 public final int getQueueLength() {
592 return sync.getQueueLength();
593 }
594
595 /**
596 * Returns a collection containing threads that may be waiting to
597 * acquire. Because the actual set of threads may change
598 * dynamically while constructing this result, the returned
599 * collection is only a best-effort estimate. The elements of the
600 * returned collection are in no particular order. This method is
601 * designed to facilitate construction of subclasses that provide
602 * more extensive monitoring facilities.
603 * @return the collection of threads
604 */
605 protected Collection<Thread> getQueuedThreads() {
606 return sync.getQueuedThreads();
607 }
608 }