Source Code Cross Referenced for Semaphore.java in  » 6.0-JDK-Core » Collections-Jar-Zip-Logging-regex » java » util » concurrent » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Home
Java Source Code / Java Documentation
1.6.0 JDK Core
2.6.0 JDK Modules
3.6.0 JDK Modules com.sun
4.6.0 JDK Modules com.sun.java
5.6.0 JDK Modules sun
6.6.0 JDK Platform
7.Ajax
8.Apache Harmony Java SE
9.Aspect oriented
10.Authentication Authorization
11.Blogger System
12.Build
13.Byte Code
14.Cache
15.Chart
16.Chat
17.Code Analyzer
18.Collaboration
19.Content Management System
20.Database Client
21.Database DBMS
22.Database JDBC Connection Pool
23.Database ORM
24.Development
25.EJB Server
26.ERP CRM Financial
27.ESB
28.Forum
29.Game
30.GIS
31.Graphic 3D
32.Graphic Library
33.Groupware
34.HTML Parser
35.IDE
36.IDE Eclipse
37.IDE Netbeans
38.Installer
39.Internationalization Localization
40.Inversion of Control
41.Issue Tracking
42.J2EE
43.J2ME
44.JBoss
45.JMS
46.JMX
47.Library
48.Mail Clients
49.Music
50.Net
51.Parser
52.PDF
53.Portal
54.Profiler
55.Project Management
56.Report
57.RSS RDF
58.Rule Engine
59.Science
60.Scripting
61.Search Engine
62.Security
63.Sevlet Container
64.Source Control
65.Swing Library
66.Template Engine
67.Test Coverage
68.Testing
69.UML
70.Web Crawler
71.Web Framework
72.Web Mail
73.Web Server
74.Web Services
75.Web Services apache cxf 2.2.6
76.Web Services AXIS2
77.Wiki Engine
78.Workflow Engines
79.XML
80.XML UI
Java Source Code / Java Documentation » 6.0 JDK Core » Collections Jar Zip Logging regex » java.util.concurrent 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001        /*
002         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
003         *
004         * This code is free software; you can redistribute it and/or modify it
005         * under the terms of the GNU General Public License version 2 only, as
006         * published by the Free Software Foundation.  Sun designates this
007         * particular file as subject to the "Classpath" exception as provided
008         * by Sun in the LICENSE file that accompanied this code.
009         *
010         * This code is distributed in the hope that it will be useful, but WITHOUT
011         * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
012         * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
013         * version 2 for more details (a copy is included in the LICENSE file that
014         * accompanied this code).
015         *
016         * You should have received a copy of the GNU General Public License version
017         * 2 along with this work; if not, write to the Free Software Foundation,
018         * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
019         *
020         * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
021         * CA 95054 USA or visit www.sun.com if you need additional information or
022         * have any questions.
023         */
024
025        /*
026         * This file is available under and governed by the GNU General Public
027         * License version 2 only, as published by the Free Software Foundation.
028         * However, the following notice accompanied the original version of this
029         * file:
030         *
031         * Written by Doug Lea with assistance from members of JCP JSR-166
032         * Expert Group and released to the public domain, as explained at
033         * http://creativecommons.org/licenses/publicdomain
034         */
035
036        package java.util.concurrent;
037
038        import java.util.*;
039        import java.util.concurrent.locks.*;
040        import java.util.concurrent.atomic.*;
041
042        /**
043         * A counting semaphore.  Conceptually, a semaphore maintains a set of
044         * permits.  Each {@link #acquire} blocks if necessary until a permit is
045         * available, and then takes it.  Each {@link #release} adds a permit,
046         * potentially releasing a blocking acquirer.
047         * However, no actual permit objects are used; the {@code Semaphore} just
048         * keeps a count of the number available and acts accordingly.
049         *
050         * <p>Semaphores are often used to restrict the number of threads than can
051         * access some (physical or logical) resource. For example, here is
052         * a class that uses a semaphore to control access to a pool of items:
053         * <pre>
054         * class Pool {
055         *   private static final int MAX_AVAILABLE = 100;
056         *   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
057         *
058         *   public Object getItem() throws InterruptedException {
059         *     available.acquire();
060         *     return getNextAvailableItem();
061         *   }
062         *
063         *   public void putItem(Object x) {
064         *     if (markAsUnused(x))
065         *       available.release();
066         *   }
067         *
068         *   // Not a particularly efficient data structure; just for demo
069         *
070         *   protected Object[] items = ... whatever kinds of items being managed
071         *   protected boolean[] used = new boolean[MAX_AVAILABLE];
072         *
073         *   protected synchronized Object getNextAvailableItem() {
074         *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
075         *       if (!used[i]) {
076         *          used[i] = true;
077         *          return items[i];
078         *       }
079         *     }
080         *     return null; // not reached
081         *   }
082         *
083         *   protected synchronized boolean markAsUnused(Object item) {
084         *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
085         *       if (item == items[i]) {
086         *          if (used[i]) {
087         *            used[i] = false;
088         *            return true;
089         *          } else
090         *            return false;
091         *       }
092         *     }
093         *     return false;
094         *   }
095         *
096         * }
097         * </pre>
098         *
099         * <p>Before obtaining an item each thread must acquire a permit from
100         * the semaphore, guaranteeing that an item is available for use. When
101         * the thread has finished with the item it is returned back to the
102         * pool and a permit is returned to the semaphore, allowing another
103         * thread to acquire that item.  Note that no synchronization lock is
104         * held when {@link #acquire} is called as that would prevent an item
105         * from being returned to the pool.  The semaphore encapsulates the
106         * synchronization needed to restrict access to the pool, separately
107         * from any synchronization needed to maintain the consistency of the
108         * pool itself.
109         *
110         * <p>A semaphore initialized to one, and which is used such that it
111         * only has at most one permit available, can serve as a mutual
112         * exclusion lock.  This is more commonly known as a <em>binary
113         * semaphore</em>, because it only has two states: one permit
114         * available, or zero permits available.  When used in this way, the
115         * binary semaphore has the property (unlike many {@link Lock}
116         * implementations), that the &quot;lock&quot; can be released by a
117         * thread other than the owner (as semaphores have no notion of
118         * ownership).  This can be useful in some specialized contexts, such
119         * as deadlock recovery.
120         *
121         * <p> The constructor for this class optionally accepts a
122         * <em>fairness</em> parameter. When set false, this class makes no
123         * guarantees about the order in which threads acquire permits. In
124         * particular, <em>barging</em> is permitted, that is, a thread
125         * invoking {@link #acquire} can be allocated a permit ahead of a
126         * thread that has been waiting - logically the new thread places itself at
127         * the head of the queue of waiting threads. When fairness is set true, the
128         * semaphore guarantees that threads invoking any of the {@link
129         * #acquire() acquire} methods are selected to obtain permits in the order in
130         * which their invocation of those methods was processed
131         * (first-in-first-out; FIFO). Note that FIFO ordering necessarily
132         * applies to specific internal points of execution within these
133         * methods.  So, it is possible for one thread to invoke
134         * {@code acquire} before another, but reach the ordering point after
135         * the other, and similarly upon return from the method.
136         * Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not
137         * honor the fairness setting, but will take any permits that are
138         * available.
139         *
140         * <p>Generally, semaphores used to control resource access should be
141         * initialized as fair, to ensure that no thread is starved out from
142         * accessing a resource. When using semaphores for other kinds of
143         * synchronization control, the throughput advantages of non-fair
144         * ordering often outweigh fairness considerations.
145         *
146         * <p>This class also provides convenience methods to {@link
147         * #acquire(int) acquire} and {@link #release(int) release} multiple
148         * permits at a time.  Beware of the increased risk of indefinite
149         * postponement when these methods are used without fairness set true.
150         *
151         * <p>Memory consistency effects: Actions in a thread prior to calling
152         * a "release" method such as {@code release()}
153         * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
154         * actions following a successful "acquire" method such as {@code acquire()}
155         * in another thread.
156         *
157         * @since 1.5
158         * @author Doug Lea
159         *
160         */
161
162        public class Semaphore implements  java.io.Serializable {
163            private static final long serialVersionUID = -3222578661600680210L;
164            /** All mechanics via AbstractQueuedSynchronizer subclass */
165            private final Sync sync;
166
167            /**
168             * Synchronization implementation for semaphore.  Uses AQS state
169             * to represent permits. Subclassed into fair and nonfair
170             * versions.
171             */
172            abstract static class Sync extends AbstractQueuedSynchronizer {
173                private static final long serialVersionUID = 1192457210091910933L;
174
175                Sync(int permits) {
176                    setState(permits);
177                }
178
179                final int getPermits() {
180                    return getState();
181                }
182
183                final int nonfairTryAcquireShared(int acquires) {
184                    for (;;) {
185                        int available = getState();
186                        int remaining = available - acquires;
187                        if (remaining < 0
188                                || compareAndSetState(available, remaining))
189                            return remaining;
190                    }
191                }
192
193                protected final boolean tryReleaseShared(int releases) {
194                    for (;;) {
195                        int p = getState();
196                        if (compareAndSetState(p, p + releases))
197                            return true;
198                    }
199                }
200
201                final void reducePermits(int reductions) {
202                    for (;;) {
203                        int current = getState();
204                        int next = current - reductions;
205                        if (compareAndSetState(current, next))
206                            return;
207                    }
208                }
209
210                final int drainPermits() {
211                    for (;;) {
212                        int current = getState();
213                        if (current == 0 || compareAndSetState(current, 0))
214                            return current;
215                    }
216                }
217            }
218
219            /**
220             * NonFair version
221             */
222            final static class NonfairSync extends Sync {
223                private static final long serialVersionUID = -2694183684443567898L;
224
225                NonfairSync(int permits) {
226                    super (permits);
227                }
228
229                protected int tryAcquireShared(int acquires) {
230                    return nonfairTryAcquireShared(acquires);
231                }
232            }
233
234            /**
235             * Fair version
236             */
237            final static class FairSync extends Sync {
238                private static final long serialVersionUID = 2014338818796000944L;
239
240                FairSync(int permits) {
241                    super (permits);
242                }
243
244                protected int tryAcquireShared(int acquires) {
245                    for (;;) {
246                        if (hasQueuedPredecessors())
247                            return -1;
248                        int available = getState();
249                        int remaining = available - acquires;
250                        if (remaining < 0
251                                || compareAndSetState(available, remaining))
252                            return remaining;
253                    }
254                }
255            }
256
257            /**
258             * Creates a {@code Semaphore} with the given number of
259             * permits and nonfair fairness setting.
260             *
261             * @param permits the initial number of permits available.
262             *        This value may be negative, in which case releases
263             *        must occur before any acquires will be granted.
264             */
265            public Semaphore(int permits) {
266                sync = new NonfairSync(permits);
267            }
268
269            /**
270             * Creates a {@code Semaphore} with the given number of
271             * permits and the given fairness setting.
272             *
273             * @param permits the initial number of permits available.
274             *        This value may be negative, in which case releases
275             *        must occur before any acquires will be granted.
276             * @param fair {@code true} if this semaphore will guarantee
277             *        first-in first-out granting of permits under contention,
278             *        else {@code false}
279             */
280            public Semaphore(int permits, boolean fair) {
281                sync = (fair) ? new FairSync(permits)
282                        : new NonfairSync(permits);
283            }
284
285            /**
286             * Acquires a permit from this semaphore, blocking until one is
287             * available, or the thread is {@linkplain Thread#interrupt interrupted}.
288             *
289             * <p>Acquires a permit, if one is available and returns immediately,
290             * reducing the number of available permits by one.
291             *
292             * <p>If no permit is available then the current thread becomes
293             * disabled for thread scheduling purposes and lies dormant until
294             * one of two things happens:
295             * <ul>
296             * <li>Some other thread invokes the {@link #release} method for this
297             * semaphore and the current thread is next to be assigned a permit; or
298             * <li>Some other thread {@linkplain Thread#interrupt interrupts}
299             * the current thread.
300             * </ul>
301             *
302             * <p>If the current thread:
303             * <ul>
304             * <li>has its interrupted status set on entry to this method; or
305             * <li>is {@linkplain Thread#interrupt interrupted} while waiting
306             * for a permit,
307             * </ul>
308             * then {@link InterruptedException} is thrown and the current thread's
309             * interrupted status is cleared.
310             *
311             * @throws InterruptedException if the current thread is interrupted
312             */
313            public void acquire() throws InterruptedException {
314                sync.acquireSharedInterruptibly(1);
315            }
316
317            /**
318             * Acquires a permit from this semaphore, blocking until one is
319             * available.
320             *
321             * <p>Acquires a permit, if one is available and returns immediately,
322             * reducing the number of available permits by one.
323             *
324             * <p>If no permit is available then the current thread becomes
325             * disabled for thread scheduling purposes and lies dormant until
326             * some other thread invokes the {@link #release} method for this
327             * semaphore and the current thread is next to be assigned a permit.
328             *
329             * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
330             * while waiting for a permit then it will continue to wait, but the
331             * time at which the thread is assigned a permit may change compared to
332             * the time it would have received the permit had no interruption
333             * occurred.  When the thread does return from this method its interrupt
334             * status will be set.
335             */
336            public void acquireUninterruptibly() {
337                sync.acquireShared(1);
338            }
339
340            /**
341             * Acquires a permit from this semaphore, only if one is available at the
342             * time of invocation.
343             *
344             * <p>Acquires a permit, if one is available and returns immediately,
345             * with the value {@code true},
346             * reducing the number of available permits by one.
347             *
348             * <p>If no permit is available then this method will return
349             * immediately with the value {@code false}.
350             *
351             * <p>Even when this semaphore has been set to use a
352             * fair ordering policy, a call to {@code tryAcquire()} <em>will</em>
353             * immediately acquire a permit if one is available, whether or not
354             * other threads are currently waiting.
355             * This &quot;barging&quot; behavior can be useful in certain
356             * circumstances, even though it breaks fairness. If you want to honor
357             * the fairness setting, then use
358             * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
359             * which is almost equivalent (it also detects interruption).
360             *
361             * @return {@code true} if a permit was acquired and {@code false}
362             *         otherwise
363             */
364            public boolean tryAcquire() {
365                return sync.nonfairTryAcquireShared(1) >= 0;
366            }
367
368            /**
369             * Acquires a permit from this semaphore, if one becomes available
370             * within the given waiting time and the current thread has not
371             * been {@linkplain Thread#interrupt interrupted}.
372             *
373             * <p>Acquires a permit, if one is available and returns immediately,
374             * with the value {@code true},
375             * reducing the number of available permits by one.
376             *
377             * <p>If no permit is available then the current thread becomes
378             * disabled for thread scheduling purposes and lies dormant until
379             * one of three things happens:
380             * <ul>
381             * <li>Some other thread invokes the {@link #release} method for this
382             * semaphore and the current thread is next to be assigned a permit; or
383             * <li>Some other thread {@linkplain Thread#interrupt interrupts}
384             * the current thread; or
385             * <li>The specified waiting time elapses.
386             * </ul>
387             *
388             * <p>If a permit is acquired then the value {@code true} is returned.
389             *
390             * <p>If the current thread:
391             * <ul>
392             * <li>has its interrupted status set on entry to this method; or
393             * <li>is {@linkplain Thread#interrupt interrupted} while waiting
394             * to acquire a permit,
395             * </ul>
396             * then {@link InterruptedException} is thrown and the current thread's
397             * interrupted status is cleared.
398             *
399             * <p>If the specified waiting time elapses then the value {@code false}
400             * is returned.  If the time is less than or equal to zero, the method
401             * will not wait at all.
402             *
403             * @param timeout the maximum time to wait for a permit
404             * @param unit the time unit of the {@code timeout} argument
405             * @return {@code true} if a permit was acquired and {@code false}
406             *         if the waiting time elapsed before a permit was acquired
407             * @throws InterruptedException if the current thread is interrupted
408             */
409            public boolean tryAcquire(long timeout, TimeUnit unit)
410                    throws InterruptedException {
411                return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
412            }
413
414            /**
415             * Releases a permit, returning it to the semaphore.
416             *
417             * <p>Releases a permit, increasing the number of available permits by
418             * one.  If any threads are trying to acquire a permit, then one is
419             * selected and given the permit that was just released.  That thread
420             * is (re)enabled for thread scheduling purposes.
421             *
422             * <p>There is no requirement that a thread that releases a permit must
423             * have acquired that permit by calling {@link #acquire}.
424             * Correct usage of a semaphore is established by programming convention
425             * in the application.
426             */
427            public void release() {
428                sync.releaseShared(1);
429            }
430
431            /**
432             * Acquires the given number of permits from this semaphore,
433             * blocking until all are available,
434             * or the thread is {@linkplain Thread#interrupt interrupted}.
435             *
436             * <p>Acquires the given number of permits, if they are available,
437             * and returns immediately, reducing the number of available permits
438             * by the given amount.
439             *
440             * <p>If insufficient permits are available then the current thread becomes
441             * disabled for thread scheduling purposes and lies dormant until
442             * one of two things happens:
443             * <ul>
444             * <li>Some other thread invokes one of the {@link #release() release}
445             * methods for this semaphore, the current thread is next to be assigned
446             * permits and the number of available permits satisfies this request; or
447             * <li>Some other thread {@linkplain Thread#interrupt interrupts}
448             * the current thread.
449             * </ul>
450             *
451             * <p>If the current thread:
452             * <ul>
453             * <li>has its interrupted status set on entry to this method; or
454             * <li>is {@linkplain Thread#interrupt interrupted} while waiting
455             * for a permit,
456             * </ul>
457             * then {@link InterruptedException} is thrown and the current thread's
458             * interrupted status is cleared.
459             * Any permits that were to be assigned to this thread are instead
460             * assigned to other threads trying to acquire permits, as if
461             * permits had been made available by a call to {@link #release()}.
462             *
463             * @param permits the number of permits to acquire
464             * @throws InterruptedException if the current thread is interrupted
465             * @throws IllegalArgumentException if {@code permits} is negative
466             */
467            public void acquire(int permits) throws InterruptedException {
468                if (permits < 0)
469                    throw new IllegalArgumentException();
470                sync.acquireSharedInterruptibly(permits);
471            }
472
473            /**
474             * Acquires the given number of permits from this semaphore,
475             * blocking until all are available.
476             *
477             * <p>Acquires the given number of permits, if they are available,
478             * and returns immediately, reducing the number of available permits
479             * by the given amount.
480             *
481             * <p>If insufficient permits are available then the current thread becomes
482             * disabled for thread scheduling purposes and lies dormant until
483             * some other thread invokes one of the {@link #release() release}
484             * methods for this semaphore, the current thread is next to be assigned
485             * permits and the number of available permits satisfies this request.
486             *
487             * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
488             * while waiting for permits then it will continue to wait and its
489             * position in the queue is not affected.  When the thread does return
490             * from this method its interrupt status will be set.
491             *
492             * @param permits the number of permits to acquire
493             * @throws IllegalArgumentException if {@code permits} is negative
494             *
495             */
496            public void acquireUninterruptibly(int permits) {
497                if (permits < 0)
498                    throw new IllegalArgumentException();
499                sync.acquireShared(permits);
500            }
501
502            /**
503             * Acquires the given number of permits from this semaphore, only
504             * if all are available at the time of invocation.
505             *
506             * <p>Acquires the given number of permits, if they are available, and
507             * returns immediately, with the value {@code true},
508             * reducing the number of available permits by the given amount.
509             *
510             * <p>If insufficient permits are available then this method will return
511             * immediately with the value {@code false} and the number of available
512             * permits is unchanged.
513             *
514             * <p>Even when this semaphore has been set to use a fair ordering
515             * policy, a call to {@code tryAcquire} <em>will</em>
516             * immediately acquire a permit if one is available, whether or
517             * not other threads are currently waiting.  This
518             * &quot;barging&quot; behavior can be useful in certain
519             * circumstances, even though it breaks fairness. If you want to
520             * honor the fairness setting, then use {@link #tryAcquire(int,
521             * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
522             * which is almost equivalent (it also detects interruption).
523             *
524             * @param permits the number of permits to acquire
525             * @return {@code true} if the permits were acquired and
526             *         {@code false} otherwise
527             * @throws IllegalArgumentException if {@code permits} is negative
528             */
529            public boolean tryAcquire(int permits) {
530                if (permits < 0)
531                    throw new IllegalArgumentException();
532                return sync.nonfairTryAcquireShared(permits) >= 0;
533            }
534
535            /**
536             * Acquires the given number of permits from this semaphore, if all
537             * become available within the given waiting time and the current
538             * thread has not been {@linkplain Thread#interrupt interrupted}.
539             *
540             * <p>Acquires the given number of permits, if they are available and
541             * returns immediately, with the value {@code true},
542             * reducing the number of available permits by the given amount.
543             *
544             * <p>If insufficient permits are available then
545             * the current thread becomes disabled for thread scheduling
546             * purposes and lies dormant until one of three things happens:
547             * <ul>
548             * <li>Some other thread invokes one of the {@link #release() release}
549             * methods for this semaphore, the current thread is next to be assigned
550             * permits and the number of available permits satisfies this request; or
551             * <li>Some other thread {@linkplain Thread#interrupt interrupts}
552             * the current thread; or
553             * <li>The specified waiting time elapses.
554             * </ul>
555             *
556             * <p>If the permits are acquired then the value {@code true} is returned.
557             *
558             * <p>If the current thread:
559             * <ul>
560             * <li>has its interrupted status set on entry to this method; or
561             * <li>is {@linkplain Thread#interrupt interrupted} while waiting
562             * to acquire the permits,
563             * </ul>
564             * then {@link InterruptedException} is thrown and the current thread's
565             * interrupted status is cleared.
566             * Any permits that were to be assigned to this thread, are instead
567             * assigned to other threads trying to acquire permits, as if
568             * the permits had been made available by a call to {@link #release()}.
569             *
570             * <p>If the specified waiting time elapses then the value {@code false}
571             * is returned.  If the time is less than or equal to zero, the method
572             * will not wait at all.  Any permits that were to be assigned to this
573             * thread, are instead assigned to other threads trying to acquire
574             * permits, as if the permits had been made available by a call to
575             * {@link #release()}.
576             *
577             * @param permits the number of permits to acquire
578             * @param timeout the maximum time to wait for the permits
579             * @param unit the time unit of the {@code timeout} argument
580             * @return {@code true} if all permits were acquired and {@code false}
581             *         if the waiting time elapsed before all permits were acquired
582             * @throws InterruptedException if the current thread is interrupted
583             * @throws IllegalArgumentException if {@code permits} is negative
584             */
585            public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
586                    throws InterruptedException {
587                if (permits < 0)
588                    throw new IllegalArgumentException();
589                return sync.tryAcquireSharedNanos(permits, unit
590                        .toNanos(timeout));
591            }
592
593            /**
594             * Releases the given number of permits, returning them to the semaphore.
595             *
596             * <p>Releases the given number of permits, increasing the number of
597             * available permits by that amount.
598             * If any threads are trying to acquire permits, then one
599             * is selected and given the permits that were just released.
600             * If the number of available permits satisfies that thread's request
601             * then that thread is (re)enabled for thread scheduling purposes;
602             * otherwise the thread will wait until sufficient permits are available.
603             * If there are still permits available
604             * after this thread's request has been satisfied, then those permits
605             * are assigned in turn to other threads trying to acquire permits.
606             *
607             * <p>There is no requirement that a thread that releases a permit must
608             * have acquired that permit by calling {@link Semaphore#acquire acquire}.
609             * Correct usage of a semaphore is established by programming convention
610             * in the application.
611             *
612             * @param permits the number of permits to release
613             * @throws IllegalArgumentException if {@code permits} is negative
614             */
615            public void release(int permits) {
616                if (permits < 0)
617                    throw new IllegalArgumentException();
618                sync.releaseShared(permits);
619            }
620
621            /**
622             * Returns the current number of permits available in this semaphore.
623             *
624             * <p>This method is typically used for debugging and testing purposes.
625             *
626             * @return the number of permits available in this semaphore
627             */
628            public int availablePermits() {
629                return sync.getPermits();
630            }
631
632            /**
633             * Acquires and returns all permits that are immediately available.
634             *
635             * @return the number of permits acquired
636             */
637            public int drainPermits() {
638                return sync.drainPermits();
639            }
640
641            /**
642             * Shrinks the number of available permits by the indicated
643             * reduction. This method can be useful in subclasses that use
644             * semaphores to track resources that become unavailable. This
645             * method differs from {@code acquire} in that it does not block
646             * waiting for permits to become available.
647             *
648             * @param reduction the number of permits to remove
649             * @throws IllegalArgumentException if {@code reduction} is negative
650             */
651            protected void reducePermits(int reduction) {
652                if (reduction < 0)
653                    throw new IllegalArgumentException();
654                sync.reducePermits(reduction);
655            }
656
657            /**
658             * Returns {@code true} if this semaphore has fairness set true.
659             *
660             * @return {@code true} if this semaphore has fairness set true
661             */
662            public boolean isFair() {
663                return sync instanceof  FairSync;
664            }
665
666            /**
667             * Queries whether any threads are waiting to acquire. Note that
668             * because cancellations may occur at any time, a {@code true}
669             * return does not guarantee that any other thread will ever
670             * acquire.  This method is designed primarily for use in
671             * monitoring of the system state.
672             *
673             * @return {@code true} if there may be other threads waiting to
674             *         acquire the lock
675             */
676            public final boolean hasQueuedThreads() {
677                return sync.hasQueuedThreads();
678            }
679
680            /**
681             * Returns an estimate of the number of threads waiting to acquire.
682             * The value is only an estimate because the number of threads may
683             * change dynamically while this method traverses internal data
684             * structures.  This method is designed for use in monitoring of the
685             * system state, not for synchronization control.
686             *
687             * @return the estimated number of threads waiting for this lock
688             */
689            public final int getQueueLength() {
690                return sync.getQueueLength();
691            }
692
693            /**
694             * Returns a collection containing threads that may be waiting to acquire.
695             * Because the actual set of threads may change dynamically while
696             * constructing this result, the returned collection is only a best-effort
697             * estimate.  The elements of the returned collection are in no particular
698             * order.  This method is designed to facilitate construction of
699             * subclasses that provide more extensive monitoring facilities.
700             *
701             * @return the collection of threads
702             */
703            protected Collection<Thread> getQueuedThreads() {
704                return sync.getQueuedThreads();
705            }
706
707            /**
708             * Returns a string identifying this semaphore, as well as its state.
709             * The state, in brackets, includes the String {@code "Permits ="}
710             * followed by the number of permits.
711             *
712             * @return a string identifying this semaphore, as well as its state
713             */
714            public String toString() {
715                return super .toString() + "[Permits = " + sync.getPermits()
716                        + "]";
717            }
718        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.