rt/emul/compact/src/main/java/java/util/concurrent/CountDownLatch.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.concurrent.locks.*;
jaroslav@1890
    38
import java.util.concurrent.atomic.*;
jaroslav@1890
    39
jaroslav@1890
    40
/**
jaroslav@1890
    41
 * A synchronization aid that allows one or more threads to wait until
jaroslav@1890
    42
 * a set of operations being performed in other threads completes.
jaroslav@1890
    43
 *
jaroslav@1890
    44
 * <p>A {@code CountDownLatch} is initialized with a given <em>count</em>.
jaroslav@1890
    45
 * The {@link #await await} methods block until the current count reaches
jaroslav@1890
    46
 * zero due to invocations of the {@link #countDown} method, after which
jaroslav@1890
    47
 * all waiting threads are released and any subsequent invocations of
jaroslav@1890
    48
 * {@link #await await} return immediately.  This is a one-shot phenomenon
jaroslav@1890
    49
 * -- the count cannot be reset.  If you need a version that resets the
jaroslav@1890
    50
 * count, consider using a {@link CyclicBarrier}.
jaroslav@1890
    51
 *
jaroslav@1890
    52
 * <p>A {@code CountDownLatch} is a versatile synchronization tool
jaroslav@1890
    53
 * and can be used for a number of purposes.  A
jaroslav@1890
    54
 * {@code CountDownLatch} initialized with a count of one serves as a
jaroslav@1890
    55
 * simple on/off latch, or gate: all threads invoking {@link #await await}
jaroslav@1890
    56
 * wait at the gate until it is opened by a thread invoking {@link
jaroslav@1890
    57
 * #countDown}.  A {@code CountDownLatch} initialized to <em>N</em>
jaroslav@1890
    58
 * can be used to make one thread wait until <em>N</em> threads have
jaroslav@1890
    59
 * completed some action, or some action has been completed N times.
jaroslav@1890
    60
 *
jaroslav@1890
    61
 * <p>A useful property of a {@code CountDownLatch} is that it
jaroslav@1890
    62
 * doesn't require that threads calling {@code countDown} wait for
jaroslav@1890
    63
 * the count to reach zero before proceeding, it simply prevents any
jaroslav@1890
    64
 * thread from proceeding past an {@link #await await} until all
jaroslav@1890
    65
 * threads could pass.
jaroslav@1890
    66
 *
jaroslav@1890
    67
 * <p><b>Sample usage:</b> Here is a pair of classes in which a group
jaroslav@1890
    68
 * of worker threads use two countdown latches:
jaroslav@1890
    69
 * <ul>
jaroslav@1890
    70
 * <li>The first is a start signal that prevents any worker from proceeding
jaroslav@1890
    71
 * until the driver is ready for them to proceed;
jaroslav@1890
    72
 * <li>The second is a completion signal that allows the driver to wait
jaroslav@1890
    73
 * until all workers have completed.
jaroslav@1890
    74
 * </ul>
jaroslav@1890
    75
 *
jaroslav@1890
    76
 * <pre>
jaroslav@1890
    77
 * class Driver { // ...
jaroslav@1890
    78
 *   void main() throws InterruptedException {
jaroslav@1890
    79
 *     CountDownLatch startSignal = new CountDownLatch(1);
jaroslav@1890
    80
 *     CountDownLatch doneSignal = new CountDownLatch(N);
jaroslav@1890
    81
 *
jaroslav@1890
    82
 *     for (int i = 0; i < N; ++i) // create and start threads
jaroslav@1890
    83
 *       new Thread(new Worker(startSignal, doneSignal)).start();
jaroslav@1890
    84
 *
jaroslav@1890
    85
 *     doSomethingElse();            // don't let run yet
jaroslav@1890
    86
 *     startSignal.countDown();      // let all threads proceed
jaroslav@1890
    87
 *     doSomethingElse();
jaroslav@1890
    88
 *     doneSignal.await();           // wait for all to finish
jaroslav@1890
    89
 *   }
jaroslav@1890
    90
 * }
jaroslav@1890
    91
 *
jaroslav@1890
    92
 * class Worker implements Runnable {
jaroslav@1890
    93
 *   private final CountDownLatch startSignal;
jaroslav@1890
    94
 *   private final CountDownLatch doneSignal;
jaroslav@1890
    95
 *   Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
jaroslav@1890
    96
 *      this.startSignal = startSignal;
jaroslav@1890
    97
 *      this.doneSignal = doneSignal;
jaroslav@1890
    98
 *   }
jaroslav@1890
    99
 *   public void run() {
jaroslav@1890
   100
 *      try {
jaroslav@1890
   101
 *        startSignal.await();
jaroslav@1890
   102
 *        doWork();
jaroslav@1890
   103
 *        doneSignal.countDown();
jaroslav@1890
   104
 *      } catch (InterruptedException ex) {} // return;
jaroslav@1890
   105
 *   }
jaroslav@1890
   106
 *
jaroslav@1890
   107
 *   void doWork() { ... }
jaroslav@1890
   108
 * }
jaroslav@1890
   109
 *
jaroslav@1890
   110
 * </pre>
jaroslav@1890
   111
 *
jaroslav@1890
   112
 * <p>Another typical usage would be to divide a problem into N parts,
jaroslav@1890
   113
 * describe each part with a Runnable that executes that portion and
jaroslav@1890
   114
 * counts down on the latch, and queue all the Runnables to an
jaroslav@1890
   115
 * Executor.  When all sub-parts are complete, the coordinating thread
jaroslav@1890
   116
 * will be able to pass through await. (When threads must repeatedly
jaroslav@1890
   117
 * count down in this way, instead use a {@link CyclicBarrier}.)
jaroslav@1890
   118
 *
jaroslav@1890
   119
 * <pre>
jaroslav@1890
   120
 * class Driver2 { // ...
jaroslav@1890
   121
 *   void main() throws InterruptedException {
jaroslav@1890
   122
 *     CountDownLatch doneSignal = new CountDownLatch(N);
jaroslav@1890
   123
 *     Executor e = ...
jaroslav@1890
   124
 *
jaroslav@1890
   125
 *     for (int i = 0; i < N; ++i) // create and start threads
jaroslav@1890
   126
 *       e.execute(new WorkerRunnable(doneSignal, i));
jaroslav@1890
   127
 *
jaroslav@1890
   128
 *     doneSignal.await();           // wait for all to finish
jaroslav@1890
   129
 *   }
jaroslav@1890
   130
 * }
jaroslav@1890
   131
 *
jaroslav@1890
   132
 * class WorkerRunnable implements Runnable {
jaroslav@1890
   133
 *   private final CountDownLatch doneSignal;
jaroslav@1890
   134
 *   private final int i;
jaroslav@1890
   135
 *   WorkerRunnable(CountDownLatch doneSignal, int i) {
jaroslav@1890
   136
 *      this.doneSignal = doneSignal;
jaroslav@1890
   137
 *      this.i = i;
jaroslav@1890
   138
 *   }
jaroslav@1890
   139
 *   public void run() {
jaroslav@1890
   140
 *      try {
jaroslav@1890
   141
 *        doWork(i);
jaroslav@1890
   142
 *        doneSignal.countDown();
jaroslav@1890
   143
 *      } catch (InterruptedException ex) {} // return;
jaroslav@1890
   144
 *   }
jaroslav@1890
   145
 *
jaroslav@1890
   146
 *   void doWork() { ... }
jaroslav@1890
   147
 * }
jaroslav@1890
   148
 *
jaroslav@1890
   149
 * </pre>
jaroslav@1890
   150
 *
jaroslav@1890
   151
 * <p>Memory consistency effects: Until the count reaches
jaroslav@1890
   152
 * zero, actions in a thread prior to calling
jaroslav@1890
   153
 * {@code countDown()}
jaroslav@1890
   154
 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
jaroslav@1890
   155
 * actions following a successful return from a corresponding
jaroslav@1890
   156
 * {@code await()} in another thread.
jaroslav@1890
   157
 *
jaroslav@1890
   158
 * @since 1.5
jaroslav@1890
   159
 * @author Doug Lea
jaroslav@1890
   160
 */
jaroslav@1890
   161
public class CountDownLatch {
jaroslav@1890
   162
    /**
jaroslav@1890
   163
     * Synchronization control For CountDownLatch.
jaroslav@1890
   164
     * Uses AQS state to represent count.
jaroslav@1890
   165
     */
jaroslav@1890
   166
    private static final class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890
   167
        private static final long serialVersionUID = 4982264981922014374L;
jaroslav@1890
   168
jaroslav@1890
   169
        Sync(int count) {
jaroslav@1890
   170
            setState(count);
jaroslav@1890
   171
        }
jaroslav@1890
   172
jaroslav@1890
   173
        int getCount() {
jaroslav@1890
   174
            return getState();
jaroslav@1890
   175
        }
jaroslav@1890
   176
jaroslav@1890
   177
        protected int tryAcquireShared(int acquires) {
jaroslav@1890
   178
            return (getState() == 0) ? 1 : -1;
jaroslav@1890
   179
        }
jaroslav@1890
   180
jaroslav@1890
   181
        protected boolean tryReleaseShared(int releases) {
jaroslav@1890
   182
            // Decrement count; signal when transition to zero
jaroslav@1890
   183
            for (;;) {
jaroslav@1890
   184
                int c = getState();
jaroslav@1890
   185
                if (c == 0)
jaroslav@1890
   186
                    return false;
jaroslav@1890
   187
                int nextc = c-1;
jaroslav@1890
   188
                if (compareAndSetState(c, nextc))
jaroslav@1890
   189
                    return nextc == 0;
jaroslav@1890
   190
            }
jaroslav@1890
   191
        }
jaroslav@1890
   192
    }
jaroslav@1890
   193
jaroslav@1890
   194
    private final Sync sync;
jaroslav@1890
   195
jaroslav@1890
   196
    /**
jaroslav@1890
   197
     * Constructs a {@code CountDownLatch} initialized with the given count.
jaroslav@1890
   198
     *
jaroslav@1890
   199
     * @param count the number of times {@link #countDown} must be invoked
jaroslav@1890
   200
     *        before threads can pass through {@link #await}
jaroslav@1890
   201
     * @throws IllegalArgumentException if {@code count} is negative
jaroslav@1890
   202
     */
jaroslav@1890
   203
    public CountDownLatch(int count) {
jaroslav@1890
   204
        if (count < 0) throw new IllegalArgumentException("count < 0");
jaroslav@1890
   205
        this.sync = new Sync(count);
jaroslav@1890
   206
    }
jaroslav@1890
   207
jaroslav@1890
   208
    /**
jaroslav@1890
   209
     * Causes the current thread to wait until the latch has counted down to
jaroslav@1890
   210
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
jaroslav@1890
   211
     *
jaroslav@1890
   212
     * <p>If the current count is zero then this method returns immediately.
jaroslav@1890
   213
     *
jaroslav@1890
   214
     * <p>If the current count is greater than zero then the current
jaroslav@1890
   215
     * thread becomes disabled for thread scheduling purposes and lies
jaroslav@1890
   216
     * dormant until one of two things happen:
jaroslav@1890
   217
     * <ul>
jaroslav@1890
   218
     * <li>The count reaches zero due to invocations of the
jaroslav@1890
   219
     * {@link #countDown} method; or
jaroslav@1890
   220
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
jaroslav@1890
   221
     * the current thread.
jaroslav@1890
   222
     * </ul>
jaroslav@1890
   223
     *
jaroslav@1890
   224
     * <p>If the current thread:
jaroslav@1890
   225
     * <ul>
jaroslav@1890
   226
     * <li>has its interrupted status set on entry to this method; or
jaroslav@1890
   227
     * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
jaroslav@1890
   228
     * </ul>
jaroslav@1890
   229
     * then {@link InterruptedException} is thrown and the current thread's
jaroslav@1890
   230
     * interrupted status is cleared.
jaroslav@1890
   231
     *
jaroslav@1890
   232
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
   233
     *         while waiting
jaroslav@1890
   234
     */
jaroslav@1890
   235
    public void await() throws InterruptedException {
jaroslav@1890
   236
        sync.acquireSharedInterruptibly(1);
jaroslav@1890
   237
    }
jaroslav@1890
   238
jaroslav@1890
   239
    /**
jaroslav@1890
   240
     * Causes the current thread to wait until the latch has counted down to
jaroslav@1890
   241
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
jaroslav@1890
   242
     * or the specified waiting time elapses.
jaroslav@1890
   243
     *
jaroslav@1890
   244
     * <p>If the current count is zero then this method returns immediately
jaroslav@1890
   245
     * with the value {@code true}.
jaroslav@1890
   246
     *
jaroslav@1890
   247
     * <p>If the current count is greater than zero then the current
jaroslav@1890
   248
     * thread becomes disabled for thread scheduling purposes and lies
jaroslav@1890
   249
     * dormant until one of three things happen:
jaroslav@1890
   250
     * <ul>
jaroslav@1890
   251
     * <li>The count reaches zero due to invocations of the
jaroslav@1890
   252
     * {@link #countDown} method; or
jaroslav@1890
   253
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
jaroslav@1890
   254
     * the current thread; or
jaroslav@1890
   255
     * <li>The specified waiting time elapses.
jaroslav@1890
   256
     * </ul>
jaroslav@1890
   257
     *
jaroslav@1890
   258
     * <p>If the count reaches zero then the method returns with the
jaroslav@1890
   259
     * value {@code true}.
jaroslav@1890
   260
     *
jaroslav@1890
   261
     * <p>If the current thread:
jaroslav@1890
   262
     * <ul>
jaroslav@1890
   263
     * <li>has its interrupted status set on entry to this method; or
jaroslav@1890
   264
     * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
jaroslav@1890
   265
     * </ul>
jaroslav@1890
   266
     * then {@link InterruptedException} is thrown and the current thread's
jaroslav@1890
   267
     * interrupted status is cleared.
jaroslav@1890
   268
     *
jaroslav@1890
   269
     * <p>If the specified waiting time elapses then the value {@code false}
jaroslav@1890
   270
     * is returned.  If the time is less than or equal to zero, the method
jaroslav@1890
   271
     * will not wait at all.
jaroslav@1890
   272
     *
jaroslav@1890
   273
     * @param timeout the maximum time to wait
jaroslav@1890
   274
     * @param unit the time unit of the {@code timeout} argument
jaroslav@1890
   275
     * @return {@code true} if the count reached zero and {@code false}
jaroslav@1890
   276
     *         if the waiting time elapsed before the count reached zero
jaroslav@1890
   277
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
   278
     *         while waiting
jaroslav@1890
   279
     */
jaroslav@1890
   280
    public boolean await(long timeout, TimeUnit unit)
jaroslav@1890
   281
        throws InterruptedException {
jaroslav@1890
   282
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
jaroslav@1890
   283
    }
jaroslav@1890
   284
jaroslav@1890
   285
    /**
jaroslav@1890
   286
     * Decrements the count of the latch, releasing all waiting threads if
jaroslav@1890
   287
     * the count reaches zero.
jaroslav@1890
   288
     *
jaroslav@1890
   289
     * <p>If the current count is greater than zero then it is decremented.
jaroslav@1890
   290
     * If the new count is zero then all waiting threads are re-enabled for
jaroslav@1890
   291
     * thread scheduling purposes.
jaroslav@1890
   292
     *
jaroslav@1890
   293
     * <p>If the current count equals zero then nothing happens.
jaroslav@1890
   294
     */
jaroslav@1890
   295
    public void countDown() {
jaroslav@1890
   296
        sync.releaseShared(1);
jaroslav@1890
   297
    }
jaroslav@1890
   298
jaroslav@1890
   299
    /**
jaroslav@1890
   300
     * Returns the current count.
jaroslav@1890
   301
     *
jaroslav@1890
   302
     * <p>This method is typically used for debugging and testing purposes.
jaroslav@1890
   303
     *
jaroslav@1890
   304
     * @return the current count
jaroslav@1890
   305
     */
jaroslav@1890
   306
    public long getCount() {
jaroslav@1890
   307
        return sync.getCount();
jaroslav@1890
   308
    }
jaroslav@1890
   309
jaroslav@1890
   310
    /**
jaroslav@1890
   311
     * Returns a string identifying this latch, as well as its state.
jaroslav@1890
   312
     * The state, in brackets, includes the String {@code "Count ="}
jaroslav@1890
   313
     * followed by the current count.
jaroslav@1890
   314
     *
jaroslav@1890
   315
     * @return a string identifying this latch, as well as its state
jaroslav@1890
   316
     */
jaroslav@1890
   317
    public String toString() {
jaroslav@1890
   318
        return super.toString() + "[Count = " + sync.getCount() + "]";
jaroslav@1890
   319
    }
jaroslav@1890
   320
}