ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.30
Committed: Fri Jan 2 00:38:33 2004 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.29: +2 -2 lines
Log Message:
Use ACS in FutureTask; doc improvements

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 tryAcquireSharedState(boolean isQueued, int acquires) {
142 for (;;) {
143 if (!isQueued && fair && hasQueuedThreads())
144 return -1;
145 int available = getState();
146 int remaining = available - acquires;
147 if (remaining < 0 ||
148 compareAndSetState(available, remaining))
149 return remaining;
150 }
151 }
152
153 public boolean releaseSharedState(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
171 /**
172 * Construct a <tt>Semaphore</tt> with the given number of
173 * permits and the given fairness setting.
174 * @param permits the initial number of permits available. This
175 * value may be negative, in which case releases must
176 * occur before any acquires will be granted.
177 * @param fair true if this semaphore will guarantee first-in
178 * first-out granting of permits under contention, else false.
179 */
180 public Semaphore(int permits, boolean fair) {
181 sync = new Sync(permits, fair);
182 }
183
184 /**
185 * Acquires a permit from this semaphore, blocking until one is
186 * available, or the thread is {@link Thread#interrupt interrupted}.
187 *
188 * <p>Acquires a permit, if one is available and returns immediately,
189 * reducing the number of available permits by one.
190 * <p>If no permit is available then the current thread becomes
191 * disabled for thread scheduling purposes and lies dormant until
192 * one of two things happens:
193 * <ul>
194 * <li>Some other thread invokes the {@link #release} method for this
195 * semaphore and the current thread is next to be assigned a permit; or
196 * <li>Some other thread {@link Thread#interrupt interrupts} the current
197 * thread.
198 * </ul>
199 *
200 * <p>If the current thread:
201 * <ul>
202 * <li>has its interrupted status set on entry to this method; or
203 * <li>is {@link Thread#interrupt interrupted} while waiting
204 * for a permit,
205 * </ul>
206 * then {@link InterruptedException} is thrown and the current thread's
207 * interrupted status is cleared.
208 *
209 * @throws InterruptedException if the current thread is interrupted
210 *
211 * @see Thread#interrupt
212 */
213 public void acquire() throws InterruptedException {
214 sync.acquireSharedInterruptibly(1);
215 }
216
217 /**
218 * Acquires a permit from this semaphore, blocking until one is
219 * available.
220 *
221 * <p>Acquires a permit, if one is available and returns immediately,
222 * reducing the number of available permits by one.
223 * <p>If no permit is available then the current thread becomes
224 * disabled for thread scheduling purposes and lies dormant until
225 * some other thread invokes the {@link #release} method for this
226 * semaphore and the current thread is next to be assigned a permit.
227 *
228 * <p>If the current thread
229 * is {@link Thread#interrupt interrupted} while waiting
230 * for a permit then it will continue to wait, but the time at which
231 * the thread is assigned a permit may change compared to the time it
232 * would have received the permit had no interruption occurred. When the
233 * thread does return from this method its interrupt status will be set.
234 *
235 */
236 public void acquireUninterruptibly() {
237 sync.acquireSharedUninterruptibly(1);
238 }
239
240 /**
241 * Acquires a permit from this semaphore, only if one is available at the
242 * time of invocation.
243 * <p>Acquires a permit, if one is available and returns immediately,
244 * with the value <tt>true</tt>,
245 * reducing the number of available permits by one.
246 *
247 * <p>If no permit is available then this method will return
248 * immediately with the value <tt>false</tt>.
249 *
250 * <p>Even when this semaphore has been set to use a
251 * fair ordering policy, a call to <tt>tryAcquire()</tt> <em>will</em>
252 * immediately acquire a permit if one is available, whether or not
253 * other threads are currently waiting.
254 * This &quot;barging&quot; behavior can be useful in certain
255 * circumstances, even though it breaks fairness. If you want to honor
256 * the fairness setting, then use
257 * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
258 * which is almost equivalent (it also detects interruption).
259 *
260 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
261 * otherwise.
262 */
263 public boolean tryAcquire() {
264 return sync.tryAcquireSharedState(true, 1) >= 0;
265 }
266
267 /**
268 * Acquires a permit from this semaphore, if one becomes available
269 * within the given waiting time and the
270 * current thread has not been {@link Thread#interrupt interrupted}.
271 * <p>Acquires a permit, if one is available and returns immediately,
272 * with the value <tt>true</tt>,
273 * reducing the number of available permits by one.
274 * <p>If no permit is available then
275 * the current thread becomes disabled for thread scheduling
276 * purposes and lies dormant until one of three things happens:
277 * <ul>
278 * <li>Some other thread invokes the {@link #release} method for this
279 * semaphore and the current thread is next to be assigned a permit; or
280 * <li>Some other thread {@link Thread#interrupt interrupts} the current
281 * thread; or
282 * <li>The specified waiting time elapses.
283 * </ul>
284 * <p>If a permit is acquired then the value <tt>true</tt> is returned.
285 * <p>If the current thread:
286 * <ul>
287 * <li>has its interrupted status set on entry to this method; or
288 * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
289 * a permit,
290 * </ul>
291 * then {@link InterruptedException} is thrown and the current thread's
292 * interrupted status is cleared.
293 * <p>If the specified waiting time elapses then the value <tt>false</tt>
294 * is returned.
295 * If the time is less than or equal to zero, the method will not wait
296 * at all.
297 *
298 * @param timeout the maximum time to wait for a permit
299 * @param unit the time unit of the <tt>timeout</tt> argument.
300 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
301 * if the waiting time elapsed before a permit was acquired.
302 *
303 * @throws InterruptedException if the current thread is interrupted
304 *
305 * @see Thread#interrupt
306 *
307 */
308 public boolean tryAcquire(long timeout, TimeUnit unit)
309 throws InterruptedException {
310 return sync.acquireSharedTimed(1, unit.toNanos(timeout));
311 }
312
313 /**
314 * Releases a permit, returning it to the semaphore.
315 * <p>Releases a permit, increasing the number of available permits
316 * by one.
317 * If any threads are blocking trying to acquire a permit, then one
318 * is selected and given the permit that was just released.
319 * That thread is re-enabled for thread scheduling purposes.
320 * <p>There is no requirement that a thread that releases a permit must
321 * have acquired that permit by calling {@link #acquire}.
322 * Correct usage of a semaphore is established by programming convention
323 * in the application.
324 */
325 public void release() {
326 sync.releaseShared(1);
327 }
328
329 /**
330 * Acquires the given number of permits from this semaphore,
331 * blocking until all are available,
332 * or the thread is {@link Thread#interrupt interrupted}.
333 *
334 * <p>Acquires the given number of permits, if they are available,
335 * and returns immediately,
336 * reducing the number of available permits by the given amount.
337 *
338 * <p>If insufficient permits are available then the current thread becomes
339 * disabled for thread scheduling purposes and lies dormant until
340 * one of two things happens:
341 * <ul>
342 * <li>Some other thread invokes one of the {@link #release() release}
343 * methods for this semaphore, the current thread is next to be assigned
344 * permits and the number of available permits satisfies this request; or
345 * <li>Some other thread {@link Thread#interrupt interrupts} the current
346 * thread.
347 * </ul>
348 *
349 * <p>If the current thread:
350 * <ul>
351 * <li>has its interrupted status set on entry to this method; or
352 * <li>is {@link Thread#interrupt interrupted} while waiting
353 * for a permit,
354 * </ul>
355 * then {@link InterruptedException} is thrown and the current thread's
356 * interrupted status is cleared.
357 * Any permits that were to be assigned to this thread are instead
358 * assigned to the next waiting thread(s), as if
359 * they had been made available by a call to {@link #release()}.
360 *
361 * @param permits the number of permits to acquire
362 *
363 * @throws InterruptedException if the current thread is interrupted
364 * @throws IllegalArgumentException if permits less than zero.
365 *
366 * @see Thread#interrupt
367 */
368 public void acquire(int permits) throws InterruptedException {
369 if (permits < 0) throw new IllegalArgumentException();
370 sync.acquireSharedInterruptibly(permits);
371 }
372
373 /**
374 * Acquires the given number of permits from this semaphore,
375 * blocking until all are available.
376 *
377 * <p>Acquires the given number of permits, if they are available,
378 * and returns immediately,
379 * reducing the number of available permits by the given amount.
380 *
381 * <p>If insufficient permits are available then the current thread becomes
382 * disabled for thread scheduling purposes and lies dormant until
383 * some other thread invokes one of the {@link #release() release}
384 * methods for this semaphore, the current thread is next to be assigned
385 * permits and the number of available permits satisfies this request.
386 *
387 * <p>If the current thread
388 * is {@link Thread#interrupt interrupted} while waiting
389 * for permits then it will continue to wait and its position in the
390 * queue is not affected. When the
391 * thread does return from this method its interrupt status will be set.
392 *
393 * @param permits the number of permits to acquire
394 * @throws IllegalArgumentException if permits less than zero.
395 *
396 */
397 public void acquireUninterruptibly(int permits) {
398 if (permits < 0) throw new IllegalArgumentException();
399 sync.acquireSharedUninterruptibly(permits);
400 }
401
402 /**
403 * Acquires the given number of permits from this semaphore, only if
404 * all are available at the time of invocation.
405 * <p>Acquires the given number of permits, if they are available, and
406 * returns immediately, with the value <tt>true</tt>,
407 * reducing the number of available permits by the given amount.
408 *
409 * <p>If insufficient permits are available then this method will return
410 * immediately with the value <tt>false</tt> and the number of available
411 * permits is unchanged.
412 *
413 * <p>Even when this semaphore has been set to use a fair ordering
414 * policy, a call to <tt>tryAcquire</tt> <em>will</em>
415 * immediately acquire a permit if one is available, whether or
416 * not other threads are currently waiting. This
417 * &quot;barging&quot; behavior can be useful in certain
418 * circumstances, even though it breaks fairness. If you want to
419 * honor the fairness setting, then use {@link #tryAcquire(int,
420 * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
421 * which is almost equivalent (it also detects interruption).
422 *
423 * @param permits the number of permits to acquire
424 *
425 * @return <tt>true</tt> if the permits were acquired and <tt>false</tt>
426 * otherwise.
427 * @throws IllegalArgumentException if permits less than zero.
428 */
429 public boolean tryAcquire(int permits) {
430 if (permits < 0) throw new IllegalArgumentException();
431 return sync.tryAcquireSharedState(true, permits) >= 0;
432 }
433
434 /**
435 * Acquires the given number of permits from this semaphore, if all
436 * become available within the given waiting time and the
437 * current thread has not been {@link Thread#interrupt interrupted}.
438 * <p>Acquires the given number of permits, if they are available and
439 * returns immediately, with the value <tt>true</tt>,
440 * reducing the number of available permits by the given amount.
441 * <p>If insufficient permits are available then
442 * the current thread becomes disabled for thread scheduling
443 * purposes and lies dormant until one of three things happens:
444 * <ul>
445 * <li>Some other thread invokes one of the {@link #release() release}
446 * methods for this semaphore, the current thread is next to be assigned
447 * permits and the number of available permits satisfies this request; or
448 * <li>Some other thread {@link Thread#interrupt interrupts} the current
449 * thread; or
450 * <li>The specified waiting time elapses.
451 * </ul>
452 * <p>If the permits are acquired then the value <tt>true</tt> is returned.
453 * <p>If the current thread:
454 * <ul>
455 * <li>has its interrupted status set on entry to this method; or
456 * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
457 * the permits,
458 * </ul>
459 * then {@link InterruptedException} is thrown and the current thread's
460 * interrupted status is cleared.
461 * Any permits that were to be assigned to this thread, are instead
462 * assigned to the next waiting thread(s), as if
463 * they had been made available by a call to {@link #release()}.
464 *
465 * <p>If the specified waiting time elapses then the value <tt>false</tt>
466 * is returned.
467 * If the time is
468 * less than or equal to zero, the method will not wait at all.
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 * @param permits the number of permits to acquire
474 * @param timeout the maximum time to wait for the permits
475 * @param unit the time unit of the <tt>timeout</tt> argument.
476 * @return <tt>true</tt> if all permits were acquired and <tt>false</tt>
477 * if the waiting time elapsed before all permits were acquired.
478 *
479 * @throws InterruptedException if the current thread is interrupted
480 * @throws IllegalArgumentException if permits less than zero.
481 *
482 * @see Thread#interrupt
483 *
484 */
485 public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
486 throws InterruptedException {
487 if (permits < 0) throw new IllegalArgumentException();
488 return sync.acquireSharedTimed(permits, unit.toNanos(timeout));
489 }
490
491 /**
492 * Releases the given number of permits, returning them to the semaphore.
493 * <p>Releases the given number of permits, increasing the number of
494 * available permits by that amount.
495 * If any threads are blocking trying to acquire permits, then the
496 * one that has been waiting the longest
497 * is selected and given the permits that were just released.
498 * If the number of available permits satisfies that thread's request
499 * then that thread is re-enabled for thread scheduling purposes; otherwise
500 * the thread continues to wait. If there are still permits available
501 * after the first thread's request has been satisfied, then those permits
502 * are assigned to the next waiting thread. If it is satisfied then it is
503 * re-enabled for thread scheduling purposes. This continues until there
504 * are insufficient permits to satisfy the next waiting thread, or there
505 * are no more waiting threads.
506 *
507 * <p>There is no requirement that a thread that releases a permit must
508 * have acquired that permit by calling {@link Semaphore#acquire acquire}.
509 * Correct usage of a semaphore is established by programming convention
510 * in the application.
511 *
512 * @param permits the number of permits to release
513 * @throws IllegalArgumentException if permits less than zero.
514 */
515 public void release(int permits) {
516 if (permits < 0) throw new IllegalArgumentException();
517 sync.releaseShared(permits);
518 }
519
520 /**
521 * Return the current number of permits available in this semaphore.
522 * <p>This method is typically used for debugging and testing purposes.
523 * @return the number of permits available in this semaphore.
524 */
525 public int availablePermits() {
526 return sync.getPermits();
527 }
528
529 /**
530 * Shrink the number of available permits by the indicated
531 * reduction. This method can be useful in subclasses that
532 * use semaphores to track available resources that become
533 * unavailable. This method differs from <tt>acquire</tt>
534 * in that it does not block waiting for permits to become
535 * available.
536 * @param reduction the number of permits to remove
537 * @throws IllegalArgumentException if reduction is negative
538 */
539 protected void reducePermits(int reduction) {
540 if (reduction < 0) throw new IllegalArgumentException();
541 sync.reducePermits(reduction);
542 }
543
544 /**
545 * Return true if this semaphore has fairness set true.
546 * @return true if this semaphore has fairness set true.
547 */
548 public boolean isFair() {
549 return sync.fair;
550 }
551
552 /**
553 * Queries whether any threads are waiting to acquire. Note that
554 * because cancellations may occur at any time, a <tt>true</tt>
555 * return does not guarantee that any other thread will ever
556 * acquire. This method is designed primarily for use in
557 * monitoring of the system state.
558 *
559 * @return true if there may be other threads waiting to acquire
560 * the lock.
561 */
562 public final boolean hasQueuedThreads() {
563 return sync.hasQueuedThreads();
564 }
565
566 /**
567 * Returns an estimate of the number of threads waiting to
568 * acquire. The value is only an estimate because the number of
569 * threads may change dynamically while this method traverses
570 * internal data structures. This method is designed for use in
571 * monitoring of the system state, not for synchronization
572 * control.
573 * @return the estimated number of threads waiting for this lock
574 */
575 public final int getQueueLength() {
576 return sync.getQueueLength();
577 }
578
579 /**
580 * Returns a collection containing threads that may be waiting to
581 * acquire. Because the actual set of threads may change
582 * dynamically while constructing this result, the returned
583 * collection is only a best-effort estimate. The elements of the
584 * returned collection are in no particular order. This method is
585 * designed to facilitate construction of subclasses that provide
586 * more extensive monitoring facilities.
587 * @return the collection of threads
588 */
589 protected Collection<Thread> getQueuedThreads() {
590 return sync.getQueuedThreads();
591 }
592 }