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