ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.16
Committed: Tue Dec 30 15:47:48 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.15: +30 -46 lines
Log Message:
Avoid cache threashing

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3 dl 1.16 * Expert Group and released to the public domain, as explained at
4     * http://creativecommons.org/licenses/publicdomain
5 dl 1.2 */
6    
7 tim 1.1 package java.util.concurrent;
8 dl 1.6 import java.util.concurrent.locks.*;
9 dl 1.16 import java.util.concurrent.atomic.*;
10 tim 1.1
11     /**
12 brian 1.4 * A synchronization aid that allows one or more threads to wait until
13     * a set of operations being performed in other threads completes.
14 dl 1.3 *
15     * <p>A <tt>CountDownLatch</tt> is initialized with a given
16 dholmes 1.9 * <em>count</em>. The {@link #await await} methods block until the current
17 dl 1.3 * {@link #getCount count} reaches zero due to invocations of the
18     * {@link #countDown} method, after which all waiting threads are
19 dholmes 1.9 * released and any subsequent invocations of {@link #await await} return
20 dl 1.3 * immediately. This is a one-shot phenomenon -- the count cannot be
21     * reset. If you need a version that resets the count, consider using
22     * a {@link CyclicBarrier}.
23 tim 1.1 *
24     * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
25 dl 1.5 * and can be used for a number of purposes. A
26     * <tt>CountDownLatch</tt> initialized with a count of one serves as a
27 dholmes 1.9 * simple on/off latch, or gate: all threads invoking {@link #await await}
28 dl 1.5 * wait at the gate until it is opened by a thread invoking {@link
29     * #countDown}. A <tt>CountDownLatch</tt> initialized to <em>N</em>
30     * can be used to make one thread wait until <em>N</em> threads have
31     * completed some action, or some action has been completed N times.
32     * <p>A useful property of a <tt>CountDownLatch</tt> is that it
33     * doesn't require that threads calling <tt>countDown</tt> wait for
34     * the count to reach zero before proceeding, it simply prevents any
35 dholmes 1.9 * thread from proceeding past an {@link #await await} until all
36 dl 1.5 * threads could pass.
37 tim 1.1 *
38     * <p><b>Sample usage:</b> Here is a pair of classes in which a group
39     * of worker threads use two countdown latches:
40     * <ul>
41 dholmes 1.9 * <li>The first is a start signal that prevents any worker from proceeding
42 tim 1.1 * until the driver is ready for them to proceed;
43 dholmes 1.9 * <li>The second is a completion signal that allows the driver to wait
44 tim 1.1 * until all workers have completed.
45     * </ul>
46     *
47     * <pre>
48     * class Driver { // ...
49     * void main() throws InterruptedException {
50     * CountDownLatch startSignal = new CountDownLatch(1);
51     * CountDownLatch doneSignal = new CountDownLatch(N);
52     *
53     * for (int i = 0; i < N; ++i) // create and start threads
54     * new Thread(new Worker(startSignal, doneSignal)).start();
55     *
56     * doSomethingElse(); // don't let run yet
57     * startSignal.countDown(); // let all threads proceed
58     * doSomethingElse();
59     * doneSignal.await(); // wait for all to finish
60     * }
61     * }
62     *
63     * class Worker implements Runnable {
64     * private final CountDownLatch startSignal;
65     * private final CountDownLatch doneSignal;
66     * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
67     * this.startSignal = startSignal;
68     * this.doneSignal = doneSignal;
69     * }
70     * public void run() {
71     * try {
72     * startSignal.await();
73     * doWork();
74     * doneSignal.countDown();
75 tim 1.7 * } catch (InterruptedException ex) {} // return;
76 tim 1.1 * }
77     *
78     * void doWork() { ... }
79     * }
80     *
81     * </pre>
82     *
83 dl 1.5 * <p>Another typical usage would be to divide a problem into N parts,
84     * describe each part with a Runnable that executes that portion and
85     * counts down on the latch, and queue all the Runnables to an
86     * Executor. When all sub-parts are complete, the coordinating thread
87 dl 1.13 * will be able to pass through await. (When threads must repeatedly
88     * count down in this way, instead use a {@link CyclicBarrier}.)
89 brian 1.4 *
90     * <pre>
91     * class Driver2 { // ...
92     * void main() throws InterruptedException {
93     * CountDownLatch doneSignal = new CountDownLatch(N);
94     * Executor e = ...
95     *
96     * for (int i = 0; i < N; ++i) // create and start threads
97     * e.execute(new WorkerRunnable(doneSignal, i));
98     *
99     * doneSignal.await(); // wait for all to finish
100     * }
101     * }
102     *
103     * class WorkerRunnable implements Runnable {
104     * private final CountDownLatch doneSignal;
105     * private final int i;
106 dl 1.13 * WorkerRunnable(CountDownLatch doneSignal, int i) {
107 brian 1.4 * this.doneSignal = doneSignal;
108     * this.i = i;
109     * }
110     * public void run() {
111     * try {
112     * doWork(i);
113     * doneSignal.countDown();
114 tim 1.7 * } catch (InterruptedException ex) {} // return;
115 brian 1.4 * }
116     *
117     * void doWork() { ... }
118     * }
119     *
120     * </pre>
121     *
122 tim 1.1 * @since 1.5
123 dl 1.5 * @author Doug Lea
124 tim 1.1 */
125     public class CountDownLatch {
126 dl 1.16 /**
127     * Synchronization control For CountDownLatch.
128     * Uses AQS state to represent count.
129     */
130     private static final class Sync extends AbstractQueuedSynchronizer {
131     Sync(int count) {
132     set(count);
133     }
134    
135     public int acquireSharedState(boolean isQueued, int acquires) {
136     return get() == 0? 1 : -1;
137     }
138    
139     public boolean releaseSharedState(int releases) {
140     // Decrement count; signal when transition to zero
141     int c;
142     while ( (c = get()) > 0 && !compareAndSet(c, c-1))
143     ;
144     return c == 1;
145     }
146     }
147 tim 1.1
148 dl 1.16 private final Sync sync;
149 tim 1.1 /**
150     * Constructs a <tt>CountDownLatch</tt> initialized with the given
151     * count.
152     *
153     * @param count the number of times {@link #countDown} must be invoked
154     * before threads can pass through {@link #await}.
155     *
156 dl 1.2 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
157 tim 1.1 */
158 dl 1.2 public CountDownLatch(int count) {
159     if (count < 0) throw new IllegalArgumentException("count < 0");
160 dl 1.16 this.sync = new Sync(count);
161 dl 1.2 }
162 tim 1.1
163     /**
164     * Causes the current thread to wait until the latch has counted down to
165     * zero, unless the thread is {@link Thread#interrupt interrupted}.
166     *
167     * <p>If the current {@link #getCount count} is zero then this method
168     * returns immediately.
169     * <p>If the current {@link #getCount count} is greater than zero then
170     * the current thread becomes disabled for thread scheduling
171     * purposes and lies dormant until one of two things happen:
172     * <ul>
173 dholmes 1.9 * <li>The count reaches zero due to invocations of the
174 tim 1.1 * {@link #countDown} method; or
175 dholmes 1.9 * <li>Some other thread {@link Thread#interrupt interrupts} the current
176 tim 1.1 * thread.
177     * </ul>
178     * <p>If the current thread:
179     * <ul>
180     * <li>has its interrupted status set on entry to this method; or
181     * <li>is {@link Thread#interrupt interrupted} while waiting,
182     * </ul>
183     * then {@link InterruptedException} is thrown and the current thread's
184     * interrupted status is cleared.
185     *
186     * @throws InterruptedException if the current thread is interrupted
187     * while waiting.
188     */
189 dl 1.2 public void await() throws InterruptedException {
190 dl 1.16 sync.acquireSharedInterruptibly(1);
191 dl 1.2 }
192    
193 tim 1.1 /**
194     * Causes the current thread to wait until the latch has counted down to
195     * zero, unless the thread is {@link Thread#interrupt interrupted},
196     * or the specified waiting time elapses.
197     *
198     * <p>If the current {@link #getCount count} is zero then this method
199     * returns immediately with the value <tt>true</tt>.
200     *
201     * <p>If the current {@link #getCount count} is greater than zero then
202     * the current thread becomes disabled for thread scheduling
203     * purposes and lies dormant until one of three things happen:
204     * <ul>
205     * <li>The count reaches zero due to invocations of the
206     * {@link #countDown} method; or
207     * <li>Some other thread {@link Thread#interrupt interrupts} the current
208     * thread; or
209     * <li>The specified waiting time elapses.
210     * </ul>
211     * <p>If the count reaches zero then the method returns with the
212     * value <tt>true</tt>.
213     * <p>If the current thread:
214     * <ul>
215     * <li>has its interrupted status set on entry to this method; or
216     * <li>is {@link Thread#interrupt interrupted} while waiting,
217     * </ul>
218     * then {@link InterruptedException} is thrown and the current thread's
219     * interrupted status is cleared.
220     *
221     * <p>If the specified waiting time elapses then the value <tt>false</tt>
222     * is returned.
223 dholmes 1.10 * If the time is
224 tim 1.1 * less than or equal to zero, the method will not wait at all.
225     *
226     * @param timeout the maximum time to wait
227 dl 1.2 * @param unit the time unit of the <tt>timeout</tt> argument.
228 tim 1.1 * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
229     * if the waiting time elapsed before the count reached zero.
230     *
231     * @throws InterruptedException if the current thread is interrupted
232     * while waiting.
233     */
234 dl 1.2 public boolean await(long timeout, TimeUnit unit)
235 tim 1.1 throws InterruptedException {
236 dl 1.16 return sync.acquireSharedTimed(1, unit.toNanos(timeout));
237 tim 1.1 }
238    
239     /**
240     * Decrements the count of the latch, releasing all waiting threads if
241     * the count reaches zero.
242     * <p>If the current {@link #getCount count} is greater than zero then
243     * it is decremented. If the new count is zero then all waiting threads
244     * are re-enabled for thread scheduling purposes.
245     * <p>If the current {@link #getCount count} equals zero then nothing
246     * happens.
247     */
248 dl 1.2 public void countDown() {
249 dl 1.16 sync.releaseShared(1);
250 dl 1.2 }
251 tim 1.1
252     /**
253     * Returns the current count.
254     * <p>This method is typically used for debugging and testing purposes.
255     * @return the current count.
256     */
257     public long getCount() {
258 dl 1.16 return sync.get();
259 tim 1.1 }
260     }