ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.27
Committed: Mon Dec 29 16:38:06 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.26: +22 -2 lines
Log Message:
Clarify tryLock/timeout policy

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 */
129 private final static class Sync extends AbstractQueuedSynchronizer {
130 final boolean fair;
131 Sync(int permits, boolean fair) {
132 this.fair = fair;
133 state().set(permits);
134 }
135
136 public int acquireSharedState(boolean isQueued, int acquires) {
137 final AtomicInteger perms = state();
138 if (!isQueued && fair && hasQueuedThreads())
139 return -1;
140 for (;;) {
141 int available = perms.get();
142 int remaining = available - acquires;
143 if (remaining < 0 ||
144 perms.compareAndSet(available, remaining))
145 return remaining;
146 }
147 }
148
149 public boolean releaseSharedState(int releases) {
150 final AtomicInteger perms = state();
151 for (;;) {
152 int p = perms.get();
153 if (perms.compareAndSet(p, p + releases))
154 return true;
155 }
156 }
157
158 public int acquireExclusiveState(boolean isQueued, int acquires) {
159 throw new UnsupportedOperationException();
160 }
161
162 public final boolean releaseExclusiveState(int releases) {
163 throw new UnsupportedOperationException();
164 }
165
166 public final void checkConditionAccess(Thread thread, boolean waiting) {
167 throw new UnsupportedOperationException();
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.acquireSharedState(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.acquireSharedState(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 /**
493 * Releases the given number of permits, returning them to the semaphore.
494 * <p>Releases the given number of permits, increasing the number of
495 * available permits by that amount.
496 * If any threads are blocking trying to acquire permits, then the
497 * one that has been waiting the longest
498 * is selected and given the permits that were just released.
499 * If the number of available permits satisfies that thread's request
500 * then that thread is re-enabled for thread scheduling purposes; otherwise
501 * the thread continues to wait. If there are still permits available
502 * after the first thread's request has been satisfied, then those permits
503 * are assigned to the next waiting thread. If it is satisfied then it is
504 * re-enabled for thread scheduling purposes. This continues until there
505 * are insufficient permits to satisfy the next waiting thread, or there
506 * are no more waiting threads.
507 *
508 * <p>There is no requirement that a thread that releases a permit must
509 * have acquired that permit by calling {@link Semaphore#acquire acquire}.
510 * Correct usage of a semaphore is established by programming convention
511 * in the application.
512 *
513 * @param permits the number of permits to release
514 * @throws IllegalArgumentException if permits less than zero.
515 */
516 public void release(int permits) {
517 if (permits < 0) throw new IllegalArgumentException();
518 sync.releaseShared(permits);
519 }
520
521 /**
522 * Return the current number of permits available in this semaphore.
523 * <p>This method is typically used for debugging and testing purposes.
524 * @return the number of permits available in this semaphore.
525 */
526 public int availablePermits() {
527 return sync.state().get();
528 }
529
530 /**
531 * Shrink the number of available permits by the indicated
532 * reduction. This method can be useful in subclasses that
533 * use semaphores to track available resources that become
534 * unavailable. This method differs from <tt>acquire</tt>
535 * in that it does not block waiting for permits to become
536 * available.
537 * @param reduction the number of permits to remove
538 * @throws IllegalArgumentException if reduction is negative
539 */
540 protected void reducePermits(int reduction) {
541 if (reduction < 0) throw new IllegalArgumentException();
542 sync.state().getAndAdd(-reduction);
543 }
544
545 /**
546 * Return true if this semaphore has fairness set true.
547 * @return true if this semaphore has fairness set true.
548 */
549 public boolean isFair() {
550 return sync.fair;
551 }
552
553
554 /**
555 * Queries whether any threads are waiting to acquire. Note that
556 * because cancellations may occur at any time, a <tt>true</tt>
557 * return does not guarantee that any other thread will ever
558 * acquire. This method is designed primarily for use in
559 * monitoring of the system state.
560 *
561 * @return true if there may be other threads waiting to acquire
562 * the lock.
563 */
564 public final boolean hasQueuedThreads() {
565 return sync.hasQueuedThreads();
566 }
567
568
569 /**
570 * Returns an estimate of the number of threads waiting to
571 * acquire. The value is only an estimate because the number of
572 * threads may change dynamically while this method traverses
573 * internal data structures. This method is designed for use in
574 * monitoring of the system state, not for synchronization
575 * control.
576 * @return the estimated number of threads waiting for this lock
577 */
578 public final int getQueueLength() {
579 return sync.getQueueLength();
580 }
581
582 /**
583 * Returns a collection containing threads that may be waiting to
584 * acquire. Because the actual set of threads may change
585 * dynamically while constructing this result, the returned
586 * collection is only a best-effort estimate. The elements of the
587 * returned collection are in no particular order. This method is
588 * designed to facilitate construction of subclasses that provide
589 * more extensive monitoring facilities.
590 * @return the collection of threads
591 */
592 protected Collection<Thread> getQueuedThreads() {
593 return sync.getQueuedThreads();
594 }
595
596 }