ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CountDownLatch.java
Revision: 1.2
Committed: Tue May 27 18:14:39 2003 UTC (21 years ago) by dl
Branch: MAIN
CVS Tags: JSR166_PRERELEASE_0_1
Changes since 1.1: +59 -8 lines
Log Message:
re-check-in initial implementations

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain. Use, modify, and
4 * redistribute this code in any way without acknowledgement.
5 */
6
7 package java.util.concurrent;
8
9 /**
10 * A <tt>CountDownLatch</tt> allows one set of threads to wait until
11 * the actions of another set of threads allow the first set to proceed.
12 * <p>A <tt>CountDownLatch</tt> is initialized with a given <em>count</em>.
13 * The {@link #await} methods block until the current {@link #getCount count}
14 * reaches zero due to invocations of the {@link #countDown} method,
15 * after which all waiting threads are
16 * released and any subsequent invocations of {@link #await} return
17 * immediately. This is a one-shot phenomenon -- the count
18 * cannot be reset. If you need a version that resets the count,
19 * consider using a {@link CyclicBarrier}.
20 *
21 * <p>A <tt>CountDownLatch</tt> is a versatile synchronization tool
22 * and can be used for a number of purposes.
23 * A <tt>CountDownLatch</tt> initialized to one serves as a simple on/off
24 * latch, or gate: all threads invoking {@link #await} wait at the gate until
25 * it is opened by a thread invoking {@link #countDown}.
26 * A <tt>CountDownLatch</tt> initialized to <em>N</em> can be used to make
27 * one thread wait until <em>N</em> threads have completed some action.
28 * A useful property of a <tt>CountDownLatch</tt> is that it doesn't
29 * require that all threads wait before any can proceed, it simply
30 * prevents any thread from proceeding past the {@link #await wait} until
31 * all threads could pass.
32 *
33 * <p><b>Sample usage:</b> Here is a pair of classes in which a group
34 * of worker threads use two countdown latches:
35 * <ul>
36 * <li> The first is a start signal that prevents any worker from proceeding
37 * until the driver is ready for them to proceed;
38 * <li> The second is a completion signal that allows the driver to wait
39 * until all workers have completed.
40 * </ul>
41 *
42 * <pre>
43 * class Driver { // ...
44 * void main() throws InterruptedException {
45 * CountDownLatch startSignal = new CountDownLatch(1);
46 * CountDownLatch doneSignal = new CountDownLatch(N);
47 *
48 * for (int i = 0; i < N; ++i) // create and start threads
49 * new Thread(new Worker(startSignal, doneSignal)).start();
50 *
51 * doSomethingElse(); // don't let run yet
52 * startSignal.countDown(); // let all threads proceed
53 * doSomethingElse();
54 * doneSignal.await(); // wait for all to finish
55 * }
56 * }
57 *
58 * class Worker implements Runnable {
59 * private final CountDownLatch startSignal;
60 * private final CountDownLatch doneSignal;
61 * Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
62 * this.startSignal = startSignal;
63 * this.doneSignal = doneSignal;
64 * }
65 * public void run() {
66 * try {
67 * startSignal.await();
68 * doWork();
69 * doneSignal.countDown();
70 * }
71 * catch (InterruptedException ex) {} // return;
72 * }
73 *
74 * void doWork() { ... }
75 * }
76 *
77 * </pre>
78 *
79 * @since 1.5
80 * @spec JSR-166
81 * @revised $Date: 2003/01/30 22:12:13 $
82 * @editor $Author: dholmes $
83 */
84 public class CountDownLatch {
85 private final ReentrantLock lock = new ReentrantLock();
86 private final Condition zero = lock.newCondition();
87 private int count;
88
89 /**
90 * Constructs a <tt>CountDownLatch</tt> initialized with the given
91 * count.
92 *
93 * @param count the number of times {@link #countDown} must be invoked
94 * before threads can pass through {@link #await}.
95 *
96 * @throws IllegalArgumentException if <tt>count</tt> is less than zero.
97 */
98 public CountDownLatch(int count) {
99 if (count < 0) throw new IllegalArgumentException("count < 0");
100 this.count = count;
101 }
102
103 /**
104 * Causes the current thread to wait until the latch has counted down to
105 * zero, unless the thread is {@link Thread#interrupt interrupted}.
106 *
107 * <p>If the current {@link #getCount count} is zero then this method
108 * returns immediately.
109 * <p>If the current {@link #getCount count} is greater than zero then
110 * the current thread becomes disabled for thread scheduling
111 * purposes and lies dormant until one of two things happen:
112 * <ul>
113 * <li> The count reaches zero due to invocations of the
114 * {@link #countDown} method; or
115 * <li> Some other thread {@link Thread#interrupt interrupts} the current
116 * thread.
117 * </ul>
118 * <p>If the current thread:
119 * <ul>
120 * <li>has its interrupted status set on entry to this method; or
121 * <li>is {@link Thread#interrupt interrupted} while waiting,
122 * </ul>
123 * then {@link InterruptedException} is thrown and the current thread's
124 * interrupted status is cleared.
125 *
126 * @throws InterruptedException if the current thread is interrupted
127 * while waiting.
128 */
129 public void await() throws InterruptedException {
130 lock.lock();
131 try {
132 while (count != 0)
133 zero.await();
134 }
135 finally {
136 lock.unlock();
137 }
138 }
139
140
141 /**
142 * Causes the current thread to wait until the latch has counted down to
143 * zero, unless the thread is {@link Thread#interrupt interrupted},
144 * or the specified waiting time elapses.
145 *
146 * <p>If the current {@link #getCount count} is zero then this method
147 * returns immediately with the value <tt>true</tt>.
148 *
149 * <p>If the current {@link #getCount count} is greater than zero then
150 * the current thread becomes disabled for thread scheduling
151 * purposes and lies dormant until one of three things happen:
152 * <ul>
153 * <li>The count reaches zero due to invocations of the
154 * {@link #countDown} method; or
155 * <li>Some other thread {@link Thread#interrupt interrupts} the current
156 * thread; or
157 * <li>The specified waiting time elapses.
158 * </ul>
159 * <p>If the count reaches zero then the method returns with the
160 * value <tt>true</tt>.
161 * <p>If the current thread:
162 * <ul>
163 * <li>has its interrupted status set on entry to this method; or
164 * <li>is {@link Thread#interrupt interrupted} while waiting,
165 * </ul>
166 * then {@link InterruptedException} is thrown and the current thread's
167 * interrupted status is cleared.
168 *
169 * <p>If the specified waiting time elapses then the value <tt>false</tt>
170 * is returned.
171 * The given waiting time is a best-effort lower bound. If the time is
172 * less than or equal to zero, the method will not wait at all.
173 *
174 * @param timeout the maximum time to wait
175 * @param unit the time unit of the <tt>timeout</tt> argument.
176 * @return <tt>true</tt> if the count reached zero and <tt>false</tt>
177 * if the waiting time elapsed before the count reached zero.
178 *
179 * @throws InterruptedException if the current thread is interrupted
180 * while waiting.
181 */
182 public boolean await(long timeout, TimeUnit unit)
183 throws InterruptedException {
184 long nanos = unit.toNanos(timeout);
185 lock.lock();
186 try {
187 for (;;) {
188 if (count == 0)
189 return true;
190 nanos = zero.awaitNanos(nanos);
191 if (nanos <= 0)
192 return false;
193 }
194 }
195 finally {
196 lock.unlock();
197 }
198 }
199
200
201
202 /**
203 * Decrements the count of the latch, releasing all waiting threads if
204 * the count reaches zero.
205 * <p>If the current {@link #getCount count} is greater than zero then
206 * it is decremented. If the new count is zero then all waiting threads
207 * are re-enabled for thread scheduling purposes.
208 * <p>If the current {@link #getCount count} equals zero then nothing
209 * happens.
210 */
211 public void countDown() {
212 lock.lock();
213 try {
214 if (count > 0 && --count == 0)
215 zero.signalAll();
216 }
217 finally {
218 lock.unlock();
219 }
220 }
221
222 /**
223 * Returns the current count.
224 * <p>This method is typically used for debugging and testing purposes.
225 * @return the current count.
226 */
227 public long getCount() {
228 lock.lock();
229 try {
230 return count;
231 }
232 finally {
233 lock.unlock();
234 }
235 }
236 }