ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.21
Committed: Sat Dec 27 14:15:22 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.20: +35 -281 lines
Log Message:
Uses AbstractQueuedSynchronizer instead of cloned code

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. Use, modify, and
4 * redistribute this code in any way without acknowledgement.
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 extends AbstractQueuedSynchronizer implements java.io.Serializable {
122 private static final long serialVersionUID = -3222578661600680210L;
123 private final boolean fair;
124
125 // Implement abstract methods
126
127 protected int acquireSharedState(boolean isQueued, int acquires,
128 Thread current) {
129 final AtomicInteger perms = getState();
130 if (!isQueued && fair && hasWaiters())
131 return -1;
132 for (;;) {
133 int available = perms.get();
134 int remaining = available - acquires;
135 if (remaining < 0 ||
136 perms.compareAndSet(available, remaining))
137 return remaining;
138 }
139 }
140
141 protected boolean releaseSharedState(int releases) {
142 final AtomicInteger perms = getState();
143 for (;;) {
144 int p = perms.get();
145 if (perms.compareAndSet(p, p + releases))
146 return true;
147 }
148 }
149
150 protected int acquireExclusiveState(boolean isQueued, int acquires,
151 Thread current) {
152 throw new UnsupportedOperationException();
153 }
154
155 protected boolean releaseExclusiveState(int releases) {
156 throw new UnsupportedOperationException();
157 }
158
159 protected void checkConditionAccess(Thread thread, boolean waiting) {
160 throw new UnsupportedOperationException();
161 }
162
163 /**
164 * Construct a <tt>Semaphore</tt> with the given number of
165 * permits and the given fairness setting.
166 * @param permits the initial number of permits available. This
167 * value may be negative, in which case releases must
168 * occur before any acquires will be granted.
169 * @param fair true if this semaphore will guarantee first-in
170 * first-out granting of permits under contention, else false.
171 */
172 public Semaphore(int permits, boolean fair) {
173 this.fair = fair;
174 getState().set(permits);
175 }
176
177 /**
178 * Acquires a permit from this semaphore, blocking until one is
179 * available, or the thread is {@link Thread#interrupt interrupted}.
180 *
181 * <p>Acquires a permit, if one is available and returns immediately,
182 * reducing the number of available permits by one.
183 * <p>If no permit is available then the current thread becomes
184 * disabled for thread scheduling purposes and lies dormant until
185 * one of two things happens:
186 * <ul>
187 * <li>Some other thread invokes the {@link #release} method for this
188 * semaphore and the current thread is next to be assigned a permit; or
189 * <li>Some other thread {@link Thread#interrupt interrupts} the current
190 * thread.
191 * </ul>
192 *
193 * <p>If the current thread:
194 * <ul>
195 * <li>has its interrupted status set on entry to this method; or
196 * <li>is {@link Thread#interrupt interrupted} while waiting
197 * for a permit,
198 * </ul>
199 * then {@link InterruptedException} is thrown and the current thread's
200 * interrupted status is cleared.
201 *
202 * @throws InterruptedException if the current thread is interrupted
203 *
204 * @see Thread#interrupt
205 */
206 public void acquire() throws InterruptedException {
207 acquireSharedInterruptibly(1);
208 }
209
210 /**
211 * Acquires a permit from this semaphore, blocking until one is
212 * available.
213 *
214 * <p>Acquires a permit, if one is available and returns immediately,
215 * reducing the number of available permits by one.
216 * <p>If no permit is available then the current thread becomes
217 * disabled for thread scheduling purposes and lies dormant until
218 * some other thread invokes the {@link #release} method for this
219 * semaphore and the current thread is next to be assigned a permit.
220 *
221 * <p>If the current thread
222 * is {@link Thread#interrupt interrupted} while waiting
223 * for a permit then it will continue to wait, but the time at which
224 * the thread is assigned a permit may change compared to the time it
225 * would have received the permit had no interruption occurred. When the
226 * thread does return from this method its interrupt status will be set.
227 *
228 */
229 public void acquireUninterruptibly() {
230 acquireSharedUninterruptibly(1);
231 }
232
233 /**
234 * Acquires a permit from this semaphore, only if one is available at the
235 * time of invocation.
236 * <p>Acquires a permit, if one is available and returns immediately,
237 * with the value <tt>true</tt>,
238 * reducing the number of available permits by one.
239 *
240 * <p>If no permit is available then this method will return
241 * immediately with the value <tt>false</tt>.
242 *
243 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
244 * otherwise.
245 */
246 public boolean tryAcquire() {
247 return acquireSharedState(false, 1, null) >= 0;
248 }
249
250 /**
251 * Acquires a permit from this semaphore, if one becomes available
252 * within the given waiting time and the
253 * current thread has not been {@link Thread#interrupt interrupted}.
254 * <p>Acquires a permit, if one is available and returns immediately,
255 * with the value <tt>true</tt>,
256 * reducing the number of available permits by one.
257 * <p>If no permit is available then
258 * the current thread becomes disabled for thread scheduling
259 * purposes and lies dormant until one of three things happens:
260 * <ul>
261 * <li>Some other thread invokes the {@link #release} method for this
262 * semaphore and the current thread is next to be assigned a permit; or
263 * <li>Some other thread {@link Thread#interrupt interrupts} the current
264 * thread; or
265 * <li>The specified waiting time elapses.
266 * </ul>
267 * <p>If a permit is acquired then the value <tt>true</tt> is returned.
268 * <p>If the current thread:
269 * <ul>
270 * <li>has its interrupted status set on entry to this method; or
271 * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
272 * a permit,
273 * </ul>
274 * then {@link InterruptedException} is thrown and the current thread's
275 * interrupted status is cleared.
276 * <p>If the specified waiting time elapses then the value <tt>false</tt>
277 * is returned.
278 * If the time is less than or equal to zero, the method will not wait
279 * at all.
280 *
281 * @param timeout the maximum time to wait for a permit
282 * @param unit the time unit of the <tt>timeout</tt> argument.
283 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
284 * if the waiting time elapsed before a permit was acquired.
285 *
286 * @throws InterruptedException if the current thread is interrupted
287 *
288 * @see Thread#interrupt
289 *
290 */
291 public boolean tryAcquire(long timeout, TimeUnit unit)
292 throws InterruptedException {
293 return acquireSharedTimed(1, unit.toNanos(timeout));
294 }
295
296 /**
297 * Releases a permit, returning it to the semaphore.
298 * <p>Releases a permit, increasing the number of available permits
299 * by one.
300 * If any threads are blocking trying to acquire a permit, then one
301 * is selected and given the permit that was just released.
302 * That thread is re-enabled for thread scheduling purposes.
303 * <p>There is no requirement that a thread that releases a permit must
304 * have acquired that permit by calling {@link #acquire}.
305 * Correct usage of a semaphore is established by programming convention
306 * in the application.
307 */
308 public void release() {
309 releaseShared(1);
310 }
311
312 /**
313 * Acquires the given number of permits from this semaphore,
314 * blocking until all are available,
315 * or the thread is {@link Thread#interrupt interrupted}.
316 *
317 * <p>Acquires the given number of permits, if they are available,
318 * and returns immediately,
319 * reducing the number of available permits by the given amount.
320 *
321 * <p>If insufficient permits are available then the current thread becomes
322 * disabled for thread scheduling purposes and lies dormant until
323 * one of two things happens:
324 * <ul>
325 * <li>Some other thread invokes one of the {@link #release() release}
326 * methods for this semaphore, the current thread is next to be assigned
327 * permits and the number of available permits satisfies this request; or
328 * <li>Some other thread {@link Thread#interrupt interrupts} the current
329 * thread.
330 * </ul>
331 *
332 * <p>If the current thread:
333 * <ul>
334 * <li>has its interrupted status set on entry to this method; or
335 * <li>is {@link Thread#interrupt interrupted} while waiting
336 * for a permit,
337 * </ul>
338 * then {@link InterruptedException} is thrown and the current thread's
339 * interrupted status is cleared.
340 * Any permits that were to be assigned to this thread are instead
341 * assigned to the next waiting thread(s), as if
342 * they had been made available by a call to {@link #release()}.
343 *
344 * @param permits the number of permits to acquire
345 *
346 * @throws InterruptedException if the current thread is interrupted
347 * @throws IllegalArgumentException if permits less than zero.
348 *
349 * @see Thread#interrupt
350 */
351 public void acquire(int permits) throws InterruptedException {
352 if (permits < 0) throw new IllegalArgumentException();
353 acquireSharedInterruptibly(permits);
354 }
355
356 /**
357 * Acquires the given number of permits from this semaphore,
358 * blocking until all are available.
359 *
360 * <p>Acquires the given number of permits, if they are available,
361 * and returns immediately,
362 * reducing the number of available permits by the given amount.
363 *
364 * <p>If insufficient permits are available then the current thread becomes
365 * disabled for thread scheduling purposes and lies dormant until
366 * some other thread invokes one of the {@link #release() release}
367 * methods for this semaphore, the current thread is next to be assigned
368 * permits and the number of available permits satisfies this request.
369 *
370 * <p>If the current thread
371 * is {@link Thread#interrupt interrupted} while waiting
372 * for permits then it will continue to wait and its position in the
373 * queue is not affected. When the
374 * thread does return from this method its interrupt status will be set.
375 *
376 * @param permits the number of permits to acquire
377 * @throws IllegalArgumentException if permits less than zero.
378 *
379 */
380 public void acquireUninterruptibly(int permits) {
381 if (permits < 0) throw new IllegalArgumentException();
382 acquireSharedUninterruptibly(permits);
383 }
384
385 /**
386 * Acquires the given number of permits from this semaphore, only if
387 * all are available at the time of invocation.
388 * <p>Acquires the given number of permits, if they are available, and
389 * returns immediately, with the value <tt>true</tt>,
390 * reducing the number of available permits by the given amount.
391 *
392 * <p>If insufficient permits are available then this method will return
393 * immediately with the value <tt>false</tt> and the number of available
394 * permits is unchanged.
395 *
396 * @param permits the number of permits to acquire
397 *
398 * @return <tt>true</tt> if the permits were acquired and <tt>false</tt>
399 * otherwise.
400 * @throws IllegalArgumentException if permits less than zero.
401 */
402 public boolean tryAcquire(int permits) {
403 if (permits < 0) throw new IllegalArgumentException();
404 return acquireSharedState(false, permits, null) >= 0;
405 }
406
407 /**
408 * Acquires the given number of permits from this semaphore, if all
409 * become available within the given waiting time and the
410 * current thread has not been {@link Thread#interrupt interrupted}.
411 * <p>Acquires the given number of permits, if they are available and
412 * returns immediately, with the value <tt>true</tt>,
413 * reducing the number of available permits by the given amount.
414 * <p>If insufficient permits are available then
415 * the current thread becomes disabled for thread scheduling
416 * purposes and lies dormant until one of three things happens:
417 * <ul>
418 * <li>Some other thread invokes one of the {@link #release() release}
419 * methods for this semaphore, the current thread is next to be assigned
420 * permits and the number of available permits satisfies this request; or
421 * <li>Some other thread {@link Thread#interrupt interrupts} the current
422 * thread; or
423 * <li>The specified waiting time elapses.
424 * </ul>
425 * <p>If the permits are acquired then the value <tt>true</tt> is returned.
426 * <p>If the current thread:
427 * <ul>
428 * <li>has its interrupted status set on entry to this method; or
429 * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
430 * the permits,
431 * </ul>
432 * then {@link InterruptedException} is thrown and the current thread's
433 * interrupted status is cleared.
434 * Any permits that were to be assigned to this thread, are instead
435 * assigned to the next waiting thread(s), as if
436 * they had been made available by a call to {@link #release()}.
437 *
438 * <p>If the specified waiting time elapses then the value <tt>false</tt>
439 * is returned.
440 * If the time is
441 * less than or equal to zero, the method will not wait at all.
442 * Any permits that were to be assigned to this thread, are instead
443 * assigned to the next waiting thread(s), as if
444 * they had been made available by a call to {@link #release()}.
445 *
446 * @param permits the number of permits to acquire
447 * @param timeout the maximum time to wait for the permits
448 * @param unit the time unit of the <tt>timeout</tt> argument.
449 * @return <tt>true</tt> if all permits were acquired and <tt>false</tt>
450 * if the waiting time elapsed before all permits were acquired.
451 *
452 * @throws InterruptedException if the current thread is interrupted
453 * @throws IllegalArgumentException if permits less than zero.
454 *
455 * @see Thread#interrupt
456 *
457 */
458 public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
459 throws InterruptedException {
460 if (permits < 0) throw new IllegalArgumentException();
461 return acquireSharedTimed(permits, unit.toNanos(timeout));
462 }
463
464
465 /**
466 * Releases the given number of permits, returning them to the semaphore.
467 * <p>Releases the given number of permits, increasing the number of
468 * available permits by that amount.
469 * If any threads are blocking trying to acquire permits, then the
470 * one that has been waiting the longest
471 * is selected and given the permits that were just released.
472 * If the number of available permits satisfies that thread's request
473 * then that thread is re-enabled for thread scheduling purposes; otherwise
474 * the thread continues to wait. If there are still permits available
475 * after the first thread's request has been satisfied, then those permits
476 * are assigned to the next waiting thread. If it is satisfied then it is
477 * re-enabled for thread scheduling purposes. This continues until there
478 * are insufficient permits to satisfy the next waiting thread, or there
479 * are no more waiting threads.
480 *
481 * <p>There is no requirement that a thread that releases a permit must
482 * have acquired that permit by calling {@link Semaphore#acquire acquire}.
483 * Correct usage of a semaphore is established by programming convention
484 * in the application.
485 *
486 * @param permits the number of permits to release
487 * @throws IllegalArgumentException if permits less than zero.
488 */
489 public void release(int permits) {
490 if (permits < 0) throw new IllegalArgumentException();
491 releaseShared(permits);
492 }
493
494 /**
495 * Return the current number of permits available in this semaphore.
496 * <p>This method is typically used for debugging and testing purposes.
497 * @return the number of permits available in this semaphore.
498 */
499 public int availablePermits() {
500 return getState().get();
501 }
502
503 /**
504 * Shrink the number of available permits by the indicated
505 * reduction. This method can be useful in subclasses that
506 * use semaphores to track available resources that become
507 * unavailable. This method differs from <tt>acquire</tt>
508 * in that it does not block waiting for permits to become
509 * available.
510 * @param reduction the number of permits to remove
511 * @throws IllegalArgumentException if reduction is negative
512 */
513 protected void reducePermits(int reduction) {
514 if (reduction < 0) throw new IllegalArgumentException();
515 getState().getAndAdd(-reduction);
516 }
517
518 /**
519 * Return true if this semaphore has fairness set true.
520 * @return true if this semaphore has fairness set true.
521 */
522 public boolean isFair() {
523 return fair;
524 }
525
526 }