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 "lock" 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 optionally accepts a |
92 |
* <em>fairness</em> parameter. When set false, this class makes no |
93 |
* guarantees about the order in which threads acquire permits. In |
94 |
* particular, <em>barging</em> is permitted, that is, a thread |
95 |
* invoking {@link #acquire} can be allocated a permit ahead of a |
96 |
* thread that has been waiting - logically the new thread places itself at |
97 |
* the head of the queue of waiting threads. When fairness is set true, the |
98 |
* semaphore guarantees that threads invoking any of the {@link |
99 |
* #acquire() acquire} methods are selected to obtain permits in the order in |
100 |
* which their invocation of those methods was processed |
101 |
* (first-in-first-out; FIFO). Note that FIFO ordering necessarily |
102 |
* applies to specific internal points of execution within these |
103 |
* methods. So, it is possible for one thread to invoke |
104 |
* <tt>acquire</tt> before another, but reach the ordering point after |
105 |
* the other, and similarly upon return from the method. |
106 |
* Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not |
107 |
* honor the fairness setting, but will take any permits that are |
108 |
* available. |
109 |
* |
110 |
* <p>Generally, semaphores used to control resource access should be |
111 |
* initialized as fair, to ensure that no thread is starved out from |
112 |
* accessing a resource. When using semaphores for other kinds of |
113 |
* synchronization control, the throughput advantages of non-fair |
114 |
* ordering often outweigh fairness considerations. |
115 |
* |
116 |
* <p>This class also provides convenience methods to {@link |
117 |
* #acquire(int) acquire} and {@link #release(int) release} multiple |
118 |
* permits at a time. Beware of the increased risk of indefinite |
119 |
* postponement when these methods are used without fairness set true. |
120 |
* |
121 |
* @since 1.5 |
122 |
* @author Doug Lea |
123 |
* |
124 |
*/ |
125 |
|
126 |
public class Semaphore implements java.io.Serializable { |
127 |
private static final long serialVersionUID = -3222578661600680210L; |
128 |
/** All mechanics via AbstractQueuedSynchronizer subclass */ |
129 |
private final Sync sync; |
130 |
|
131 |
/** |
132 |
* Synchronization implementation for semaphore. Uses AQS state |
133 |
* to represent permits. Subclassed into fair and nonfair |
134 |
* versions. |
135 |
*/ |
136 |
abstract static class Sync extends AbstractQueuedSynchronizer { |
137 |
Sync(int permits) { |
138 |
setState(permits); |
139 |
} |
140 |
|
141 |
final int getPermits() { |
142 |
return getState(); |
143 |
} |
144 |
|
145 |
final int nonfairTryAcquireShared(int acquires) { |
146 |
for (;;) { |
147 |
int available = getState(); |
148 |
int remaining = available - acquires; |
149 |
if (remaining < 0 || |
150 |
compareAndSetState(available, remaining)) |
151 |
return remaining; |
152 |
} |
153 |
} |
154 |
|
155 |
protected final boolean tryReleaseShared(int releases) { |
156 |
for (;;) { |
157 |
int p = getState(); |
158 |
if (compareAndSetState(p, p + releases)) |
159 |
return true; |
160 |
} |
161 |
} |
162 |
|
163 |
final void reducePermits(int reductions) { |
164 |
for (;;) { |
165 |
int current = getState(); |
166 |
int next = current - reductions; |
167 |
if (compareAndSetState(current, next)) |
168 |
return; |
169 |
} |
170 |
} |
171 |
|
172 |
final int drainPermits() { |
173 |
for (;;) { |
174 |
int current = getState(); |
175 |
if (current == 0 || compareAndSetState(current, 0)) |
176 |
return current; |
177 |
} |
178 |
} |
179 |
} |
180 |
|
181 |
/** |
182 |
* NonFair version |
183 |
*/ |
184 |
final static class NonfairSync extends Sync { |
185 |
NonfairSync(int permits) { |
186 |
super(permits); |
187 |
} |
188 |
|
189 |
protected int tryAcquireShared(int acquires) { |
190 |
return nonfairTryAcquireShared(acquires); |
191 |
} |
192 |
} |
193 |
|
194 |
/** |
195 |
* Fair version |
196 |
*/ |
197 |
final static class FairSync extends Sync { |
198 |
FairSync(int permits) { |
199 |
super(permits); |
200 |
} |
201 |
|
202 |
protected int tryAcquireShared(int acquires) { |
203 |
Thread current = Thread.currentThread(); |
204 |
for (;;) { |
205 |
Thread first = getFirstQueuedThread(); |
206 |
if (first != null && first != current) |
207 |
return -1; |
208 |
int available = getState(); |
209 |
int remaining = available - acquires; |
210 |
if (remaining < 0 || |
211 |
compareAndSetState(available, remaining)) |
212 |
return remaining; |
213 |
} |
214 |
} |
215 |
} |
216 |
|
217 |
/** |
218 |
* Creates a <tt>Semaphore</tt> with the given number of |
219 |
* permits and nonfair fairness setting. |
220 |
* @param permits the initial number of permits available. This |
221 |
* value may be negative, in which case releases must |
222 |
* occur before any acquires will be granted. |
223 |
*/ |
224 |
public Semaphore(int permits) { |
225 |
sync = new NonfairSync(permits); |
226 |
} |
227 |
|
228 |
/** |
229 |
* Creates a <tt>Semaphore</tt> with the given number of |
230 |
* permits and the given fairness setting. |
231 |
* @param permits the initial number of permits available. This |
232 |
* value may be negative, in which case releases must |
233 |
* occur before any acquires will be granted. |
234 |
* @param fair true if this semaphore will guarantee first-in |
235 |
* first-out granting of permits under contention, else false. |
236 |
*/ |
237 |
public Semaphore(int permits, boolean fair) { |
238 |
sync = (fair)? new FairSync(permits) : new NonfairSync(permits); |
239 |
} |
240 |
|
241 |
/** |
242 |
* Acquires a permit from this semaphore, blocking until one is |
243 |
* available, or the thread is {@link Thread#interrupt interrupted}. |
244 |
* |
245 |
* <p>Acquires a permit, if one is available and returns immediately, |
246 |
* reducing the number of available permits by one. |
247 |
* <p>If no permit is available then the current thread becomes |
248 |
* disabled for thread scheduling purposes and lies dormant until |
249 |
* one of two things happens: |
250 |
* <ul> |
251 |
* <li>Some other thread invokes the {@link #release} method for this |
252 |
* semaphore and the current thread is next to be assigned a permit; or |
253 |
* <li>Some other thread {@link Thread#interrupt interrupts} the current |
254 |
* thread. |
255 |
* </ul> |
256 |
* |
257 |
* <p>If the current thread: |
258 |
* <ul> |
259 |
* <li>has its interrupted status set on entry to this method; or |
260 |
* <li>is {@link Thread#interrupt interrupted} while waiting |
261 |
* for a permit, |
262 |
* </ul> |
263 |
* then {@link InterruptedException} is thrown and the current thread's |
264 |
* interrupted status is cleared. |
265 |
* |
266 |
* @throws InterruptedException if the current thread is interrupted |
267 |
* |
268 |
* @see Thread#interrupt |
269 |
*/ |
270 |
public void acquire() throws InterruptedException { |
271 |
sync.acquireSharedInterruptibly(1); |
272 |
} |
273 |
|
274 |
/** |
275 |
* Acquires a permit from this semaphore, blocking until one is |
276 |
* available. |
277 |
* |
278 |
* <p>Acquires a permit, if one is available and returns immediately, |
279 |
* reducing the number of available permits by one. |
280 |
* <p>If no permit is available then the current thread becomes |
281 |
* disabled for thread scheduling purposes and lies dormant until |
282 |
* some other thread invokes the {@link #release} method for this |
283 |
* semaphore and the current thread is next to be assigned a permit. |
284 |
* |
285 |
* <p>If the current thread |
286 |
* is {@link Thread#interrupt interrupted} while waiting |
287 |
* for a permit then it will continue to wait, but the time at which |
288 |
* the thread is assigned a permit may change compared to the time it |
289 |
* would have received the permit had no interruption occurred. When the |
290 |
* thread does return from this method its interrupt status will be set. |
291 |
* |
292 |
*/ |
293 |
public void acquireUninterruptibly() { |
294 |
sync.acquireShared(1); |
295 |
} |
296 |
|
297 |
/** |
298 |
* Acquires a permit from this semaphore, only if one is available at the |
299 |
* time of invocation. |
300 |
* <p>Acquires a permit, if one is available and returns immediately, |
301 |
* with the value <tt>true</tt>, |
302 |
* reducing the number of available permits by one. |
303 |
* |
304 |
* <p>If no permit is available then this method will return |
305 |
* immediately with the value <tt>false</tt>. |
306 |
* |
307 |
* <p>Even when this semaphore has been set to use a |
308 |
* fair ordering policy, a call to <tt>tryAcquire()</tt> <em>will</em> |
309 |
* immediately acquire a permit if one is available, whether or not |
310 |
* other threads are currently waiting. |
311 |
* This "barging" behavior can be useful in certain |
312 |
* circumstances, even though it breaks fairness. If you want to honor |
313 |
* the fairness setting, then use |
314 |
* {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) } |
315 |
* which is almost equivalent (it also detects interruption). |
316 |
* |
317 |
* @return <tt>true</tt> if a permit was acquired and <tt>false</tt> |
318 |
* otherwise. |
319 |
*/ |
320 |
public boolean tryAcquire() { |
321 |
return sync.nonfairTryAcquireShared(1) >= 0; |
322 |
} |
323 |
|
324 |
/** |
325 |
* Acquires a permit from this semaphore, if one becomes available |
326 |
* within the given waiting time and the |
327 |
* current thread has not been {@link Thread#interrupt interrupted}. |
328 |
* <p>Acquires a permit, if one is available and returns immediately, |
329 |
* with the value <tt>true</tt>, |
330 |
* reducing the number of available permits by one. |
331 |
* <p>If no permit is available then |
332 |
* the current thread becomes disabled for thread scheduling |
333 |
* purposes and lies dormant until one of three things happens: |
334 |
* <ul> |
335 |
* <li>Some other thread invokes the {@link #release} method for this |
336 |
* semaphore and the current thread is next to be assigned a permit; or |
337 |
* <li>Some other thread {@link Thread#interrupt interrupts} the current |
338 |
* thread; or |
339 |
* <li>The specified waiting time elapses. |
340 |
* </ul> |
341 |
* <p>If a permit is acquired then the value <tt>true</tt> is returned. |
342 |
* <p>If the current thread: |
343 |
* <ul> |
344 |
* <li>has its interrupted status set on entry to this method; or |
345 |
* <li>is {@link Thread#interrupt interrupted} while waiting to acquire |
346 |
* a permit, |
347 |
* </ul> |
348 |
* then {@link InterruptedException} is thrown and the current thread's |
349 |
* interrupted status is cleared. |
350 |
* <p>If the specified waiting time elapses then the value <tt>false</tt> |
351 |
* is returned. |
352 |
* If the time is less than or equal to zero, the method will not wait |
353 |
* at all. |
354 |
* |
355 |
* @param timeout the maximum time to wait for a permit |
356 |
* @param unit the time unit of the <tt>timeout</tt> argument. |
357 |
* @return <tt>true</tt> if a permit was acquired and <tt>false</tt> |
358 |
* if the waiting time elapsed before a permit was acquired. |
359 |
* |
360 |
* @throws InterruptedException if the current thread is interrupted |
361 |
* |
362 |
* @see Thread#interrupt |
363 |
* |
364 |
*/ |
365 |
public boolean tryAcquire(long timeout, TimeUnit unit) |
366 |
throws InterruptedException { |
367 |
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); |
368 |
} |
369 |
|
370 |
/** |
371 |
* Releases a permit, returning it to the semaphore. |
372 |
* <p>Releases a permit, increasing the number of available permits |
373 |
* by one. |
374 |
* If any threads are trying to acquire a permit, then one |
375 |
* is selected and given the permit that was just released. |
376 |
* That thread is (re)enabled for thread scheduling purposes. |
377 |
* <p>There is no requirement that a thread that releases a permit must |
378 |
* have acquired that permit by calling {@link #acquire}. |
379 |
* Correct usage of a semaphore is established by programming convention |
380 |
* in the application. |
381 |
*/ |
382 |
public void release() { |
383 |
sync.releaseShared(1); |
384 |
} |
385 |
|
386 |
/** |
387 |
* Acquires the given number of permits from this semaphore, |
388 |
* blocking until all are available, |
389 |
* or the thread is {@link Thread#interrupt interrupted}. |
390 |
* |
391 |
* <p>Acquires the given number of permits, if they are available, |
392 |
* and returns immediately, |
393 |
* reducing the number of available permits by the given amount. |
394 |
* |
395 |
* <p>If insufficient permits are available then the current thread becomes |
396 |
* disabled for thread scheduling purposes and lies dormant until |
397 |
* one of two things happens: |
398 |
* <ul> |
399 |
* <li>Some other thread invokes one of the {@link #release() release} |
400 |
* methods for this semaphore, the current thread is next to be assigned |
401 |
* permits and the number of available permits satisfies this request; or |
402 |
* <li>Some other thread {@link Thread#interrupt interrupts} the current |
403 |
* thread. |
404 |
* </ul> |
405 |
* |
406 |
* <p>If the current thread: |
407 |
* <ul> |
408 |
* <li>has its interrupted status set on entry to this method; or |
409 |
* <li>is {@link Thread#interrupt interrupted} while waiting |
410 |
* for a permit, |
411 |
* </ul> |
412 |
* then {@link InterruptedException} is thrown and the current thread's |
413 |
* interrupted status is cleared. |
414 |
* Any permits that were to be assigned to this thread are instead |
415 |
* assigned to other threads trying to acquire permits, as if |
416 |
* permits had been made available by a call to {@link #release()}. |
417 |
* |
418 |
* @param permits the number of permits to acquire |
419 |
* |
420 |
* @throws InterruptedException if the current thread is interrupted |
421 |
* @throws IllegalArgumentException if permits less than zero. |
422 |
* |
423 |
* @see Thread#interrupt |
424 |
*/ |
425 |
public void acquire(int permits) throws InterruptedException { |
426 |
if (permits < 0) throw new IllegalArgumentException(); |
427 |
sync.acquireSharedInterruptibly(permits); |
428 |
} |
429 |
|
430 |
/** |
431 |
* Acquires the given number of permits from this semaphore, |
432 |
* blocking until all are available. |
433 |
* |
434 |
* <p>Acquires the given number of permits, if they are available, |
435 |
* and returns immediately, |
436 |
* reducing the number of available permits by the given amount. |
437 |
* |
438 |
* <p>If insufficient permits are available then the current thread becomes |
439 |
* disabled for thread scheduling purposes and lies dormant until |
440 |
* some other thread invokes one of the {@link #release() release} |
441 |
* methods for this semaphore, the current thread is next to be assigned |
442 |
* permits and the number of available permits satisfies this request. |
443 |
* |
444 |
* <p>If the current thread |
445 |
* is {@link Thread#interrupt interrupted} while waiting |
446 |
* for permits then it will continue to wait and its position in the |
447 |
* queue is not affected. When the |
448 |
* thread does return from this method its interrupt status will be set. |
449 |
* |
450 |
* @param permits the number of permits to acquire |
451 |
* @throws IllegalArgumentException if permits less than zero. |
452 |
* |
453 |
*/ |
454 |
public void acquireUninterruptibly(int permits) { |
455 |
if (permits < 0) throw new IllegalArgumentException(); |
456 |
sync.acquireShared(permits); |
457 |
} |
458 |
|
459 |
/** |
460 |
* Acquires the given number of permits from this semaphore, only |
461 |
* if all are available at the time of invocation. |
462 |
* |
463 |
* <p>Acquires the given number of permits, if they are available, and |
464 |
* returns immediately, with the value <tt>true</tt>, |
465 |
* reducing the number of available permits by the given amount. |
466 |
* |
467 |
* <p>If insufficient permits are available then this method will return |
468 |
* immediately with the value <tt>false</tt> and the number of available |
469 |
* permits is unchanged. |
470 |
* |
471 |
* <p>Even when this semaphore has been set to use a fair ordering |
472 |
* policy, a call to <tt>tryAcquire</tt> <em>will</em> |
473 |
* immediately acquire a permit if one is available, whether or |
474 |
* not other threads are currently waiting. This |
475 |
* "barging" behavior can be useful in certain |
476 |
* circumstances, even though it breaks fairness. If you want to |
477 |
* honor the fairness setting, then use {@link #tryAcquire(int, |
478 |
* long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) } |
479 |
* which is almost equivalent (it also detects interruption). |
480 |
* |
481 |
* @param permits the number of permits to acquire |
482 |
* |
483 |
* @return <tt>true</tt> if the permits were acquired and <tt>false</tt> |
484 |
* otherwise. |
485 |
* @throws IllegalArgumentException if permits less than zero. |
486 |
*/ |
487 |
public boolean tryAcquire(int permits) { |
488 |
if (permits < 0) throw new IllegalArgumentException(); |
489 |
return sync.nonfairTryAcquireShared(permits) >= 0; |
490 |
} |
491 |
|
492 |
/** |
493 |
* Acquires the given number of permits from this semaphore, if all |
494 |
* become available within the given waiting time and the |
495 |
* current thread has not been {@link Thread#interrupt interrupted}. |
496 |
* <p>Acquires the given number of permits, if they are available and |
497 |
* returns immediately, with the value <tt>true</tt>, |
498 |
* reducing the number of available permits by the given amount. |
499 |
* <p>If insufficient permits are available then |
500 |
* the current thread becomes disabled for thread scheduling |
501 |
* purposes and lies dormant until one of three things happens: |
502 |
* <ul> |
503 |
* <li>Some other thread invokes one of the {@link #release() release} |
504 |
* methods for this semaphore, the current thread is next to be assigned |
505 |
* permits and the number of available permits satisfies this request; or |
506 |
* <li>Some other thread {@link Thread#interrupt interrupts} the current |
507 |
* thread; or |
508 |
* <li>The specified waiting time elapses. |
509 |
* </ul> |
510 |
* <p>If the permits are acquired then the value <tt>true</tt> is returned. |
511 |
* <p>If the current thread: |
512 |
* <ul> |
513 |
* <li>has its interrupted status set on entry to this method; or |
514 |
* <li>is {@link Thread#interrupt interrupted} while waiting to acquire |
515 |
* the permits, |
516 |
* </ul> |
517 |
* then {@link InterruptedException} is thrown and the current thread's |
518 |
* interrupted status is cleared. |
519 |
* Any permits that were to be assigned to this thread, are instead |
520 |
* assigned to other threads trying to acquire permits, as if |
521 |
* the permits had been made available by a call to {@link #release()}. |
522 |
* |
523 |
* <p>If the specified waiting time elapses then the value <tt>false</tt> |
524 |
* is returned. |
525 |
* If the time is |
526 |
* less than or equal to zero, the method will not wait at all. |
527 |
* Any permits that were to be assigned to this thread, are instead |
528 |
* assigned to other threads trying to acquire permits, as if |
529 |
* the permits had been made available by a call to {@link #release()}. |
530 |
* |
531 |
* @param permits the number of permits to acquire |
532 |
* @param timeout the maximum time to wait for the permits |
533 |
* @param unit the time unit of the <tt>timeout</tt> argument. |
534 |
* @return <tt>true</tt> if all permits were acquired and <tt>false</tt> |
535 |
* if the waiting time elapsed before all permits were acquired. |
536 |
* |
537 |
* @throws InterruptedException if the current thread is interrupted |
538 |
* @throws IllegalArgumentException if permits less than zero. |
539 |
* |
540 |
* @see Thread#interrupt |
541 |
* |
542 |
*/ |
543 |
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) |
544 |
throws InterruptedException { |
545 |
if (permits < 0) throw new IllegalArgumentException(); |
546 |
return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout)); |
547 |
} |
548 |
|
549 |
/** |
550 |
* Releases the given number of permits, returning them to the semaphore. |
551 |
* <p>Releases the given number of permits, increasing the number of |
552 |
* available permits by that amount. |
553 |
* If any threads are trying to acquire permits, then one |
554 |
* is selected and given the permits that were just released. |
555 |
* If the number of available permits satisfies that thread's request |
556 |
* then that thread is (re)enabled for thread scheduling purposes; |
557 |
* otherwise the thread will wait until sufficient permits are available. |
558 |
* If there are still permits available |
559 |
* after this thread's request has been satisfied, then those permits |
560 |
* are assigned in turn to other threads trying to acquire permits. |
561 |
* |
562 |
* <p>There is no requirement that a thread that releases a permit must |
563 |
* have acquired that permit by calling {@link Semaphore#acquire acquire}. |
564 |
* Correct usage of a semaphore is established by programming convention |
565 |
* in the application. |
566 |
* |
567 |
* @param permits the number of permits to release |
568 |
* @throws IllegalArgumentException if permits less than zero. |
569 |
*/ |
570 |
public void release(int permits) { |
571 |
if (permits < 0) throw new IllegalArgumentException(); |
572 |
sync.releaseShared(permits); |
573 |
} |
574 |
|
575 |
/** |
576 |
* Returns the current number of permits available in this semaphore. |
577 |
* <p>This method is typically used for debugging and testing purposes. |
578 |
* @return the number of permits available in this semaphore. |
579 |
*/ |
580 |
public int availablePermits() { |
581 |
return sync.getPermits(); |
582 |
} |
583 |
|
584 |
/** |
585 |
* Acquire and return all permits that are immediately available. |
586 |
* @return the number of permits |
587 |
*/ |
588 |
public int drainPermits() { |
589 |
return sync.drainPermits(); |
590 |
} |
591 |
|
592 |
/** |
593 |
* Shrinks the number of available permits by the indicated |
594 |
* reduction. This method can be useful in subclasses that use |
595 |
* semaphores to track resources that become unavailable. This |
596 |
* method differs from <tt>acquire</tt> in that it does not block |
597 |
* waiting for permits to become available. |
598 |
* @param reduction the number of permits to remove |
599 |
* @throws IllegalArgumentException if reduction is negative |
600 |
*/ |
601 |
protected void reducePermits(int reduction) { |
602 |
if (reduction < 0) throw new IllegalArgumentException(); |
603 |
sync.reducePermits(reduction); |
604 |
} |
605 |
|
606 |
/** |
607 |
* Returns true if this semaphore has fairness set true. |
608 |
* @return true if this semaphore has fairness set true. |
609 |
*/ |
610 |
public boolean isFair() { |
611 |
return sync instanceof FairSync; |
612 |
} |
613 |
|
614 |
/** |
615 |
* Queries whether any threads are waiting to acquire. Note that |
616 |
* because cancellations may occur at any time, a <tt>true</tt> |
617 |
* return does not guarantee that any other thread will ever |
618 |
* acquire. This method is designed primarily for use in |
619 |
* monitoring of the system state. |
620 |
* |
621 |
* @return true if there may be other threads waiting to acquire |
622 |
* the lock. |
623 |
*/ |
624 |
public final boolean hasQueuedThreads() { |
625 |
return sync.hasQueuedThreads(); |
626 |
} |
627 |
|
628 |
/** |
629 |
* Returns an estimate of the number of threads waiting to |
630 |
* acquire. The value is only an estimate because the number of |
631 |
* threads may change dynamically while this method traverses |
632 |
* internal data structures. This method is designed for use in |
633 |
* monitoring of the system state, not for synchronization |
634 |
* control. |
635 |
* @return the estimated number of threads waiting for this lock |
636 |
*/ |
637 |
public final int getQueueLength() { |
638 |
return sync.getQueueLength(); |
639 |
} |
640 |
|
641 |
/** |
642 |
* Returns a collection containing threads that may be waiting to |
643 |
* acquire. Because the actual set of threads may change |
644 |
* dynamically while constructing this result, the returned |
645 |
* collection is only a best-effort estimate. The elements of the |
646 |
* returned collection are in no particular order. This method is |
647 |
* designed to facilitate construction of subclasses that provide |
648 |
* more extensive monitoring facilities. |
649 |
* @return the collection of threads |
650 |
*/ |
651 |
protected Collection<Thread> getQueuedThreads() { |
652 |
return sync.getQueuedThreads(); |
653 |
} |
654 |
|
655 |
/** |
656 |
* Returns a string identifying this semaphore, as well as its state. |
657 |
* The state, in brackets, includes the String |
658 |
* "Permits =" followed by the number of permits. |
659 |
* @return a string identifying this semaphore, as well as its |
660 |
* state |
661 |
*/ |
662 |
public String toString() { |
663 |
return super.toString() + "[Permits = " + sync.getPermits() + "]"; |
664 |
} |
665 |
|
666 |
} |