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