ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.57
Committed: Mon Sep 28 03:05:23 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.56: +3 -0 lines
Log Message:
improve tests for shutdownNow

File Contents

# User Rev Content
1 dl 1.1 /*
2 dl 1.13 * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain, as explained at
4 jsr166 1.37 * http://creativecommons.org/publicdomain/zero/1.0/
5 jsr166 1.22 * Other contributors include Andrew Wright, Jeffrey Hayes,
6     * Pat Fisher, Mike Judd.
7 dl 1.1 */
8    
9 jsr166 1.25 import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 jsr166 1.54 import static java.util.concurrent.TimeUnit.SECONDS;
11 jsr166 1.50
12     import java.util.ArrayList;
13 jsr166 1.54 import java.util.HashSet;
14 jsr166 1.50 import java.util.List;
15     import java.util.concurrent.BlockingQueue;
16     import java.util.concurrent.Callable;
17 jsr166 1.52 import java.util.concurrent.CancellationException;
18 jsr166 1.50 import java.util.concurrent.CountDownLatch;
19     import java.util.concurrent.ExecutionException;
20     import java.util.concurrent.Executors;
21     import java.util.concurrent.ExecutorService;
22     import java.util.concurrent.Future;
23     import java.util.concurrent.RejectedExecutionException;
24     import java.util.concurrent.ScheduledFuture;
25     import java.util.concurrent.ScheduledThreadPoolExecutor;
26     import java.util.concurrent.ThreadFactory;
27     import java.util.concurrent.ThreadPoolExecutor;
28 jsr166 1.46 import java.util.concurrent.atomic.AtomicInteger;
29 dl 1.1
30 jsr166 1.50 import junit.framework.Test;
31     import junit.framework.TestSuite;
32    
33 dl 1.4 public class ScheduledExecutorTest extends JSR166TestCase {
34 dl 1.1 public static void main(String[] args) {
35 jsr166 1.51 main(suite(), args);
36 dl 1.1 }
37     public static Test suite() {
38 jsr166 1.26 return new TestSuite(ScheduledExecutorTest.class);
39 dl 1.1 }
40    
41 dl 1.5 /**
42 dl 1.6 * execute successfully executes a runnable
43 dl 1.5 */
44 jsr166 1.25 public void testExecute() throws InterruptedException {
45 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
46     final CountDownLatch done = new CountDownLatch(1);
47     final Runnable task = new CheckedRunnable() {
48     public void realRun() {
49     done.countDown();
50     }};
51     try {
52     p.execute(task);
53     assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
54     } finally {
55     joinPool(p);
56     }
57 dl 1.1 }
58    
59 dl 1.5 /**
60 dl 1.6 * delayed schedule of callable successfully executes after delay
61 dl 1.5 */
62 jsr166 1.25 public void testSchedule1() throws Exception {
63 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
64 jsr166 1.44 final long startTime = System.nanoTime();
65 jsr166 1.33 final CountDownLatch done = new CountDownLatch(1);
66     try {
67     Callable task = new CheckedCallable<Boolean>() {
68     public Boolean realCall() {
69     done.countDown();
70 jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
71 jsr166 1.33 return Boolean.TRUE;
72     }};
73 jsr166 1.44 Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
74     assertSame(Boolean.TRUE, f.get());
75     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
76 jsr166 1.33 assertTrue(done.await(0L, MILLISECONDS));
77     } finally {
78     joinPool(p);
79     }
80 dl 1.1 }
81    
82     /**
83 jsr166 1.32 * delayed schedule of runnable successfully executes after delay
84 dl 1.1 */
85 jsr166 1.33 public void testSchedule3() throws Exception {
86     ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
87 jsr166 1.44 final long startTime = System.nanoTime();
88 jsr166 1.33 final CountDownLatch done = new CountDownLatch(1);
89     try {
90     Runnable task = new CheckedRunnable() {
91     public void realRun() {
92     done.countDown();
93 jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
94 jsr166 1.33 }};
95 jsr166 1.44 Future f = p.schedule(task, timeoutMillis(), MILLISECONDS);
96     await(done);
97     assertNull(f.get(LONG_DELAY_MS, MILLISECONDS));
98     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
99 jsr166 1.33 } finally {
100     joinPool(p);
101     }
102 dl 1.1 }
103 jsr166 1.22
104 dl 1.1 /**
105 dl 1.6 * scheduleAtFixedRate executes runnable after given initial delay
106 dl 1.1 */
107 jsr166 1.33 public void testSchedule4() throws Exception {
108     ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
109 jsr166 1.44 final long startTime = System.nanoTime();
110 jsr166 1.33 final CountDownLatch done = new CountDownLatch(1);
111     try {
112     Runnable task = new CheckedRunnable() {
113     public void realRun() {
114     done.countDown();
115 jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
116 jsr166 1.33 }};
117     ScheduledFuture f =
118 jsr166 1.44 p.scheduleAtFixedRate(task, timeoutMillis(),
119     LONG_DELAY_MS, MILLISECONDS);
120     await(done);
121     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
122 jsr166 1.33 f.cancel(true);
123     } finally {
124     joinPool(p);
125     }
126 dl 1.18 }
127    
128 dl 1.6 /**
129     * scheduleWithFixedDelay executes runnable after given initial delay
130     */
131 jsr166 1.44 public void testSchedule5() throws Exception {
132 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
133 jsr166 1.44 final long startTime = System.nanoTime();
134 jsr166 1.33 final CountDownLatch done = new CountDownLatch(1);
135     try {
136     Runnable task = new CheckedRunnable() {
137     public void realRun() {
138     done.countDown();
139 jsr166 1.44 assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
140 jsr166 1.33 }};
141     ScheduledFuture f =
142 jsr166 1.44 p.scheduleWithFixedDelay(task, timeoutMillis(),
143     LONG_DELAY_MS, MILLISECONDS);
144     await(done);
145     assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
146 jsr166 1.33 f.cancel(true);
147     } finally {
148     joinPool(p);
149     }
150     }
151    
152     static class RunnableCounter implements Runnable {
153     AtomicInteger count = new AtomicInteger(0);
154     public void run() { count.getAndIncrement(); }
155 dl 1.1 }
156 jsr166 1.22
157 dl 1.6 /**
158 dl 1.18 * scheduleAtFixedRate executes series of tasks at given rate
159     */
160 jsr166 1.25 public void testFixedRateSequence() throws InterruptedException {
161 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
162 jsr166 1.47 try {
163     for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
164     long startTime = System.nanoTime();
165     int cycles = 10;
166     final CountDownLatch done = new CountDownLatch(cycles);
167 jsr166 1.49 Runnable task = new CheckedRunnable() {
168 jsr166 1.47 public void realRun() { done.countDown(); }};
169     ScheduledFuture h =
170     p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
171     done.await();
172     h.cancel(true);
173     double normalizedTime =
174     (double) millisElapsedSince(startTime) / delay;
175     if (normalizedTime >= cycles - 1 &&
176     normalizedTime <= cycles)
177     return;
178     }
179     throw new AssertionError("unexpected execution rate");
180     } finally {
181     joinPool(p);
182     }
183 dl 1.18 }
184    
185     /**
186     * scheduleWithFixedDelay executes series of tasks with given period
187     */
188 jsr166 1.25 public void testFixedDelaySequence() throws InterruptedException {
189 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
190 jsr166 1.47 try {
191     for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
192     long startTime = System.nanoTime();
193     int cycles = 10;
194     final CountDownLatch done = new CountDownLatch(cycles);
195 jsr166 1.49 Runnable task = new CheckedRunnable() {
196 jsr166 1.47 public void realRun() { done.countDown(); }};
197     ScheduledFuture h =
198     p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
199     done.await();
200     h.cancel(true);
201     double normalizedTime =
202     (double) millisElapsedSince(startTime) / delay;
203     if (normalizedTime >= cycles - 1 &&
204     normalizedTime <= cycles)
205     return;
206     }
207     throw new AssertionError("unexpected execution rate");
208     } finally {
209     joinPool(p);
210     }
211 dl 1.18 }
212    
213     /**
214 jsr166 1.32 * execute(null) throws NPE
215 dl 1.6 */
216 jsr166 1.25 public void testExecuteNull() throws InterruptedException {
217 dl 1.9 ScheduledThreadPoolExecutor se = null;
218 dl 1.6 try {
219 jsr166 1.26 se = new ScheduledThreadPoolExecutor(1);
220     se.execute(null);
221 dl 1.6 shouldThrow();
222 jsr166 1.26 } catch (NullPointerException success) {}
223 jsr166 1.22
224 jsr166 1.26 joinPool(se);
225 dl 1.6 }
226    
227     /**
228 jsr166 1.30 * schedule(null) throws NPE
229 dl 1.6 */
230 jsr166 1.25 public void testScheduleNull() throws InterruptedException {
231 dl 1.9 ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
232 jsr166 1.26 try {
233 dl 1.7 TrackedCallable callable = null;
234 jsr166 1.26 Future f = se.schedule(callable, SHORT_DELAY_MS, MILLISECONDS);
235 dl 1.6 shouldThrow();
236 jsr166 1.26 } catch (NullPointerException success) {}
237     joinPool(se);
238 dl 1.6 }
239 jsr166 1.22
240 dl 1.1 /**
241 dl 1.6 * execute throws RejectedExecutionException if shutdown
242 dl 1.1 */
243 jsr166 1.25 public void testSchedule1_RejectedExecutionException() throws InterruptedException {
244 dl 1.9 ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
245 dl 1.5 try {
246 dl 1.1 se.shutdown();
247 dl 1.4 se.schedule(new NoOpRunnable(),
248 jsr166 1.25 MEDIUM_DELAY_MS, MILLISECONDS);
249 dl 1.5 shouldThrow();
250 jsr166 1.24 } catch (RejectedExecutionException success) {
251 dl 1.17 } catch (SecurityException ok) {
252 dl 1.4 }
253 jsr166 1.22
254 dl 1.4 joinPool(se);
255 dl 1.1 }
256    
257     /**
258 dl 1.6 * schedule throws RejectedExecutionException if shutdown
259 dl 1.1 */
260 jsr166 1.25 public void testSchedule2_RejectedExecutionException() throws InterruptedException {
261 dl 1.9 ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
262 dl 1.5 try {
263 dl 1.1 se.shutdown();
264 dl 1.4 se.schedule(new NoOpCallable(),
265 jsr166 1.25 MEDIUM_DELAY_MS, MILLISECONDS);
266 dl 1.5 shouldThrow();
267 jsr166 1.24 } catch (RejectedExecutionException success) {
268 dl 1.17 } catch (SecurityException ok) {
269 dl 1.4 }
270     joinPool(se);
271 dl 1.1 }
272    
273     /**
274 dl 1.6 * schedule callable throws RejectedExecutionException if shutdown
275 dl 1.1 */
276 jsr166 1.38 public void testSchedule3_RejectedExecutionException() throws InterruptedException {
277     ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
278     try {
279 dl 1.1 se.shutdown();
280 dl 1.4 se.schedule(new NoOpCallable(),
281 jsr166 1.25 MEDIUM_DELAY_MS, MILLISECONDS);
282 dl 1.5 shouldThrow();
283 jsr166 1.24 } catch (RejectedExecutionException success) {
284 dl 1.17 } catch (SecurityException ok) {
285     }
286 jsr166 1.38 joinPool(se);
287 dl 1.1 }
288    
289     /**
290 jsr166 1.32 * scheduleAtFixedRate throws RejectedExecutionException if shutdown
291 dl 1.1 */
292 jsr166 1.25 public void testScheduleAtFixedRate1_RejectedExecutionException() throws InterruptedException {
293 dl 1.9 ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
294 dl 1.5 try {
295 dl 1.1 se.shutdown();
296 dl 1.4 se.scheduleAtFixedRate(new NoOpRunnable(),
297 jsr166 1.25 MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
298 dl 1.5 shouldThrow();
299 jsr166 1.24 } catch (RejectedExecutionException success) {
300 dl 1.17 } catch (SecurityException ok) {
301 jsr166 1.22 }
302 dl 1.4 joinPool(se);
303 dl 1.1 }
304 jsr166 1.22
305 dl 1.1 /**
306 dl 1.6 * scheduleWithFixedDelay throws RejectedExecutionException if shutdown
307 dl 1.1 */
308 jsr166 1.25 public void testScheduleWithFixedDelay1_RejectedExecutionException() throws InterruptedException {
309 dl 1.9 ScheduledThreadPoolExecutor se = new ScheduledThreadPoolExecutor(1);
310 dl 1.5 try {
311 dl 1.1 se.shutdown();
312 dl 1.4 se.scheduleWithFixedDelay(new NoOpRunnable(),
313 jsr166 1.25 MEDIUM_DELAY_MS, MEDIUM_DELAY_MS, MILLISECONDS);
314 dl 1.5 shouldThrow();
315 jsr166 1.24 } catch (RejectedExecutionException success) {
316 dl 1.17 } catch (SecurityException ok) {
317 jsr166 1.22 }
318 dl 1.4 joinPool(se);
319 dl 1.1 }
320    
321     /**
322 jsr166 1.32 * getActiveCount increases but doesn't overestimate, when a
323     * thread becomes active
324 dl 1.2 */
325 jsr166 1.25 public void testGetActiveCount() throws InterruptedException {
326 jsr166 1.33 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
327     final CountDownLatch threadStarted = new CountDownLatch(1);
328     final CountDownLatch done = new CountDownLatch(1);
329     try {
330     assertEquals(0, p.getActiveCount());
331     p.execute(new CheckedRunnable() {
332     public void realRun() throws InterruptedException {
333     threadStarted.countDown();
334     assertEquals(1, p.getActiveCount());
335     done.await();
336     }});
337     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
338     assertEquals(1, p.getActiveCount());
339     } finally {
340     done.countDown();
341     joinPool(p);
342     }
343 dl 1.2 }
344 jsr166 1.22
345 dl 1.2 /**
346 jsr166 1.32 * getCompletedTaskCount increases, but doesn't overestimate,
347     * when tasks complete
348 dl 1.2 */
349 jsr166 1.25 public void testGetCompletedTaskCount() throws InterruptedException {
350 jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(2);
351     final CountDownLatch threadStarted = new CountDownLatch(1);
352     final CountDownLatch threadProceed = new CountDownLatch(1);
353     final CountDownLatch threadDone = new CountDownLatch(1);
354     try {
355     assertEquals(0, p.getCompletedTaskCount());
356     p.execute(new CheckedRunnable() {
357     public void realRun() throws InterruptedException {
358     threadStarted.countDown();
359     assertEquals(0, p.getCompletedTaskCount());
360     threadProceed.await();
361     threadDone.countDown();
362     }});
363 jsr166 1.45 await(threadStarted);
364 jsr166 1.33 assertEquals(0, p.getCompletedTaskCount());
365     threadProceed.countDown();
366     threadDone.await();
367 jsr166 1.44 long startTime = System.nanoTime();
368     while (p.getCompletedTaskCount() != 1) {
369     if (millisElapsedSince(startTime) > LONG_DELAY_MS)
370     fail("timed out");
371     Thread.yield();
372     }
373 jsr166 1.33 } finally {
374     joinPool(p);
375     }
376 dl 1.2 }
377 jsr166 1.22
378 dl 1.2 /**
379 jsr166 1.32 * getCorePoolSize returns size given in constructor if not otherwise set
380 dl 1.2 */
381 jsr166 1.25 public void testGetCorePoolSize() throws InterruptedException {
382 jsr166 1.33 ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
383     assertEquals(1, p.getCorePoolSize());
384     joinPool(p);
385 dl 1.2 }
386 jsr166 1.22
387 dl 1.2 /**
388 jsr166 1.32 * getLargestPoolSize increases, but doesn't overestimate, when
389     * multiple threads active
390 dl 1.2 */
391 jsr166 1.25 public void testGetLargestPoolSize() throws InterruptedException {
392 jsr166 1.33 final int THREADS = 3;
393     final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(THREADS);
394     final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
395     final CountDownLatch done = new CountDownLatch(1);
396     try {
397     assertEquals(0, p.getLargestPoolSize());
398     for (int i = 0; i < THREADS; i++)
399     p.execute(new CheckedRunnable() {
400     public void realRun() throws InterruptedException {
401     threadsStarted.countDown();
402     done.await();
403     assertEquals(THREADS, p.getLargestPoolSize());
404     }});
405     assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
406     assertEquals(THREADS, p.getLargestPoolSize());
407     } finally {
408     done.countDown();
409     joinPool(p);
410     assertEquals(THREADS, p.getLargestPoolSize());
411     }
412 dl 1.2 }
413 jsr166 1.22
414 dl 1.2 /**
415 jsr166 1.32 * getPoolSize increases, but doesn't overestimate, when threads
416     * become active
417 dl 1.2 */
418 jsr166 1.25 public void testGetPoolSize() throws InterruptedException {
419 jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
420     final CountDownLatch threadStarted = new CountDownLatch(1);
421     final CountDownLatch done = new CountDownLatch(1);
422     try {
423     assertEquals(0, p.getPoolSize());
424     p.execute(new CheckedRunnable() {
425     public void realRun() throws InterruptedException {
426     threadStarted.countDown();
427     assertEquals(1, p.getPoolSize());
428     done.await();
429     }});
430     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
431     assertEquals(1, p.getPoolSize());
432     } finally {
433     done.countDown();
434     joinPool(p);
435     }
436 dl 1.2 }
437 jsr166 1.22
438 dl 1.2 /**
439 jsr166 1.32 * getTaskCount increases, but doesn't overestimate, when tasks
440     * submitted
441 dl 1.2 */
442 jsr166 1.25 public void testGetTaskCount() throws InterruptedException {
443 jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
444     final CountDownLatch threadStarted = new CountDownLatch(1);
445     final CountDownLatch done = new CountDownLatch(1);
446     final int TASKS = 5;
447     try {
448     assertEquals(0, p.getTaskCount());
449     for (int i = 0; i < TASKS; i++)
450     p.execute(new CheckedRunnable() {
451     public void realRun() throws InterruptedException {
452     threadStarted.countDown();
453     done.await();
454     }});
455     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
456     assertEquals(TASKS, p.getTaskCount());
457     } finally {
458     done.countDown();
459     joinPool(p);
460     }
461 dl 1.2 }
462 dl 1.8
463 jsr166 1.22 /**
464 dl 1.8 * getThreadFactory returns factory in constructor if not set
465     */
466 jsr166 1.25 public void testGetThreadFactory() throws InterruptedException {
467 dl 1.8 ThreadFactory tf = new SimpleThreadFactory();
468 jsr166 1.26 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1, tf);
469 dl 1.8 assertSame(tf, p.getThreadFactory());
470     joinPool(p);
471     }
472    
473 jsr166 1.22 /**
474 dl 1.8 * setThreadFactory sets the thread factory returned by getThreadFactory
475     */
476 jsr166 1.25 public void testSetThreadFactory() throws InterruptedException {
477 dl 1.8 ThreadFactory tf = new SimpleThreadFactory();
478 jsr166 1.26 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
479 dl 1.8 p.setThreadFactory(tf);
480     assertSame(tf, p.getThreadFactory());
481     joinPool(p);
482     }
483    
484 jsr166 1.22 /**
485 dl 1.8 * setThreadFactory(null) throws NPE
486     */
487 jsr166 1.25 public void testSetThreadFactoryNull() throws InterruptedException {
488 jsr166 1.26 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
489 dl 1.8 try {
490     p.setThreadFactory(null);
491     shouldThrow();
492     } catch (NullPointerException success) {
493     } finally {
494     joinPool(p);
495     }
496     }
497 jsr166 1.22
498 dl 1.2 /**
499 jsr166 1.41 * isShutdown is false before shutdown, true after
500 dl 1.2 */
501 dl 1.5 public void testIsShutdown() {
502 jsr166 1.22
503 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
504 dl 1.2 try {
505 jsr166 1.33 assertFalse(p.isShutdown());
506 dl 1.2 }
507     finally {
508 jsr166 1.33 try { p.shutdown(); } catch (SecurityException ok) { return; }
509 dl 1.2 }
510 jsr166 1.33 assertTrue(p.isShutdown());
511 dl 1.2 }
512    
513     /**
514 jsr166 1.32 * isTerminated is false before termination, true after
515 dl 1.2 */
516 jsr166 1.25 public void testIsTerminated() throws InterruptedException {
517 jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
518     final CountDownLatch threadStarted = new CountDownLatch(1);
519     final CountDownLatch done = new CountDownLatch(1);
520     assertFalse(p.isTerminated());
521     try {
522     p.execute(new CheckedRunnable() {
523     public void realRun() throws InterruptedException {
524 jsr166 1.36 assertFalse(p.isTerminated());
525 jsr166 1.33 threadStarted.countDown();
526     done.await();
527     }});
528     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
529 jsr166 1.36 assertFalse(p.isTerminating());
530 jsr166 1.33 done.countDown();
531 dl 1.2 } finally {
532 jsr166 1.33 try { p.shutdown(); } catch (SecurityException ok) { return; }
533 dl 1.2 }
534 jsr166 1.33 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
535     assertTrue(p.isTerminated());
536 dl 1.5 }
537    
538     /**
539 jsr166 1.32 * isTerminating is not true when running or when terminated
540 dl 1.5 */
541 jsr166 1.25 public void testIsTerminating() throws InterruptedException {
542 jsr166 1.33 final ThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
543     final CountDownLatch threadStarted = new CountDownLatch(1);
544     final CountDownLatch done = new CountDownLatch(1);
545     try {
546     assertFalse(p.isTerminating());
547     p.execute(new CheckedRunnable() {
548     public void realRun() throws InterruptedException {
549 jsr166 1.35 assertFalse(p.isTerminating());
550 jsr166 1.33 threadStarted.countDown();
551     done.await();
552     }});
553     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
554     assertFalse(p.isTerminating());
555     done.countDown();
556     } finally {
557     try { p.shutdown(); } catch (SecurityException ok) { return; }
558     }
559     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
560     assertTrue(p.isTerminated());
561     assertFalse(p.isTerminating());
562 dl 1.2 }
563    
564     /**
565 dl 1.8 * getQueue returns the work queue, which contains queued tasks
566     */
567 jsr166 1.25 public void testGetQueue() throws InterruptedException {
568 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
569     final CountDownLatch threadStarted = new CountDownLatch(1);
570     final CountDownLatch done = new CountDownLatch(1);
571 dl 1.8 try {
572 jsr166 1.33 ScheduledFuture[] tasks = new ScheduledFuture[5];
573     for (int i = 0; i < tasks.length; i++) {
574     Runnable r = new CheckedRunnable() {
575     public void realRun() throws InterruptedException {
576     threadStarted.countDown();
577     done.await();
578     }};
579     tasks[i] = p.schedule(r, 1, MILLISECONDS);
580     }
581     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
582     BlockingQueue<Runnable> q = p.getQueue();
583     assertTrue(q.contains(tasks[tasks.length - 1]));
584 dl 1.8 assertFalse(q.contains(tasks[0]));
585     } finally {
586 jsr166 1.33 done.countDown();
587     joinPool(p);
588 dl 1.8 }
589     }
590    
591     /**
592     * remove(task) removes queued task, and fails to remove active task
593     */
594 jsr166 1.25 public void testRemove() throws InterruptedException {
595 jsr166 1.33 final ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
596 dl 1.9 ScheduledFuture[] tasks = new ScheduledFuture[5];
597 jsr166 1.33 final CountDownLatch threadStarted = new CountDownLatch(1);
598     final CountDownLatch done = new CountDownLatch(1);
599 dl 1.8 try {
600 jsr166 1.33 for (int i = 0; i < tasks.length; i++) {
601     Runnable r = new CheckedRunnable() {
602     public void realRun() throws InterruptedException {
603     threadStarted.countDown();
604     done.await();
605     }};
606     tasks[i] = p.schedule(r, 1, MILLISECONDS);
607     }
608     assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
609     BlockingQueue<Runnable> q = p.getQueue();
610     assertFalse(p.remove((Runnable)tasks[0]));
611 dl 1.8 assertTrue(q.contains((Runnable)tasks[4]));
612     assertTrue(q.contains((Runnable)tasks[3]));
613 jsr166 1.33 assertTrue(p.remove((Runnable)tasks[4]));
614     assertFalse(p.remove((Runnable)tasks[4]));
615 dl 1.8 assertFalse(q.contains((Runnable)tasks[4]));
616     assertTrue(q.contains((Runnable)tasks[3]));
617 jsr166 1.33 assertTrue(p.remove((Runnable)tasks[3]));
618 dl 1.8 assertFalse(q.contains((Runnable)tasks[3]));
619     } finally {
620 jsr166 1.33 done.countDown();
621     joinPool(p);
622 dl 1.8 }
623     }
624    
625     /**
626 jsr166 1.40 * purge eventually removes cancelled tasks from the queue
627 dl 1.2 */
628 jsr166 1.25 public void testPurge() throws InterruptedException {
629 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
630 dl 1.9 ScheduledFuture[] tasks = new ScheduledFuture[5];
631 jsr166 1.40 for (int i = 0; i < tasks.length; i++)
632     tasks[i] = p.schedule(new SmallPossiblyInterruptedRunnable(),
633     LONG_DELAY_MS, MILLISECONDS);
634 dl 1.19 try {
635 jsr166 1.33 int max = tasks.length;
636 dl 1.19 if (tasks[4].cancel(true)) --max;
637     if (tasks[3].cancel(true)) --max;
638     // There must eventually be an interference-free point at
639     // which purge will not fail. (At worst, when queue is empty.)
640 jsr166 1.40 long startTime = System.nanoTime();
641     do {
642 jsr166 1.33 p.purge();
643     long count = p.getTaskCount();
644 jsr166 1.40 if (count == max)
645     return;
646     } while (millisElapsedSince(startTime) < MEDIUM_DELAY_MS);
647     fail("Purge failed to remove cancelled tasks");
648 dl 1.19 } finally {
649 jsr166 1.33 for (ScheduledFuture task : tasks)
650     task.cancel(true);
651     joinPool(p);
652 dl 1.2 }
653     }
654    
655     /**
656 jsr166 1.53 * shutdownNow returns a list containing tasks that were not run,
657     * and those tasks are drained from the queue
658 dl 1.2 */
659 jsr166 1.56 public void testShutdownNow() throws InterruptedException {
660     final int poolSize = 2;
661     final int count = 5;
662     final AtomicInteger ran = new AtomicInteger(0);
663     final ScheduledThreadPoolExecutor p =
664     new ScheduledThreadPoolExecutor(poolSize);
665     CountDownLatch threadsStarted = new CountDownLatch(poolSize);
666     CheckedRunnable waiter = new CheckedRunnable() { public void realRun() {
667     threadsStarted.countDown();
668     try {
669     MILLISECONDS.sleep(2 * LONG_DELAY_MS);
670     } catch (InterruptedException success) {}
671     ran.getAndIncrement();
672     }};
673     for (int i = 0; i < count; i++)
674     p.execute(waiter);
675     assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
676 jsr166 1.57 assertEquals(poolSize, p.getActiveCount());
677     assertEquals(0, p.getCompletedTaskCount());
678 jsr166 1.56 final List<Runnable> queuedTasks;
679     try {
680     queuedTasks = p.shutdownNow();
681     } catch (SecurityException ok) {
682     return; // Allowed in case test doesn't have privs
683     }
684     assertTrue(p.isShutdown());
685     assertTrue(p.getQueue().isEmpty());
686     assertEquals(count - poolSize, queuedTasks.size());
687     assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
688     assertTrue(p.isTerminated());
689     assertEquals(poolSize, ran.get());
690 jsr166 1.57 assertEquals(poolSize, p.getCompletedTaskCount());
691 jsr166 1.56 }
692    
693     /**
694     * shutdownNow returns a list containing tasks that were not run,
695     * and those tasks are drained from the queue
696     */
697 jsr166 1.54 public void testShutdownNow_delayedTasks() throws InterruptedException {
698 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
699 jsr166 1.54 List<ScheduledFuture> tasks = new ArrayList<>();
700     for (int i = 0; i < 3; i++) {
701     Runnable r = new NoOpRunnable();
702     tasks.add(p.schedule(r, 9, SECONDS));
703     tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS));
704     tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
705     }
706 jsr166 1.55 if (testImplementationDetails)
707     assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
708 jsr166 1.54 final List<Runnable> queuedTasks;
709 dl 1.17 try {
710 jsr166 1.54 queuedTasks = p.shutdownNow();
711 jsr166 1.22 } catch (SecurityException ok) {
712 jsr166 1.54 return; // Allowed in case test doesn't have privs
713     }
714     assertTrue(p.isShutdown());
715     assertTrue(p.getQueue().isEmpty());
716 jsr166 1.55 if (testImplementationDetails)
717     assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
718 jsr166 1.54 assertEquals(tasks.size(), queuedTasks.size());
719     for (ScheduledFuture task : tasks) {
720     assertFalse(task.isDone());
721     assertFalse(task.isCancelled());
722 dl 1.17 }
723 jsr166 1.54 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
724     assertTrue(p.isTerminated());
725 dl 1.2 }
726    
727 dl 1.5 /**
728 dl 1.6 * In default setting, shutdown cancels periodic but not delayed
729     * tasks at shutdown
730 dl 1.5 */
731 jsr166 1.41 public void testShutdown1() throws InterruptedException {
732 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
733     assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
734     assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
735 jsr166 1.22
736 jsr166 1.25 ScheduledFuture[] tasks = new ScheduledFuture[5];
737 jsr166 1.33 for (int i = 0; i < tasks.length; i++)
738     tasks[i] = p.schedule(new NoOpRunnable(),
739     SHORT_DELAY_MS, MILLISECONDS);
740     try { p.shutdown(); } catch (SecurityException ok) { return; }
741     BlockingQueue<Runnable> q = p.getQueue();
742     for (ScheduledFuture task : tasks) {
743     assertFalse(task.isDone());
744     assertFalse(task.isCancelled());
745     assertTrue(q.contains(task));
746 jsr166 1.25 }
747 jsr166 1.33 assertTrue(p.isShutdown());
748     assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
749     assertTrue(p.isTerminated());
750     for (ScheduledFuture task : tasks) {
751     assertTrue(task.isDone());
752     assertFalse(task.isCancelled());
753 dl 1.2 }
754     }
755    
756 dl 1.5 /**
757 dl 1.6 * If setExecuteExistingDelayedTasksAfterShutdownPolicy is false,
758     * delayed tasks are cancelled at shutdown
759 dl 1.5 */
760 jsr166 1.41 public void testShutdown2() throws InterruptedException {
761 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
762     p.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
763 jsr166 1.34 assertFalse(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
764     assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
765 jsr166 1.25 ScheduledFuture[] tasks = new ScheduledFuture[5];
766 jsr166 1.33 for (int i = 0; i < tasks.length; i++)
767     tasks[i] = p.schedule(new NoOpRunnable(),
768     SHORT_DELAY_MS, MILLISECONDS);
769     BlockingQueue q = p.getQueue();
770     assertEquals(tasks.length, q.size());
771     try { p.shutdown(); } catch (SecurityException ok) { return; }
772     assertTrue(p.isShutdown());
773 jsr166 1.25 assertTrue(q.isEmpty());
774 jsr166 1.33 assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
775     assertTrue(p.isTerminated());
776     for (ScheduledFuture task : tasks) {
777     assertTrue(task.isDone());
778     assertTrue(task.isCancelled());
779     }
780 dl 1.2 }
781    
782 dl 1.5 /**
783 dl 1.6 * If setContinueExistingPeriodicTasksAfterShutdownPolicy is set false,
784 jsr166 1.33 * periodic tasks are cancelled at shutdown
785 dl 1.5 */
786 jsr166 1.41 public void testShutdown3() throws InterruptedException {
787 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
788 jsr166 1.34 assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
789     assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
790 jsr166 1.33 p.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
791 jsr166 1.34 assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
792     assertFalse(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
793 jsr166 1.42 long initialDelay = LONG_DELAY_MS;
794 jsr166 1.25 ScheduledFuture task =
795 jsr166 1.42 p.scheduleAtFixedRate(new NoOpRunnable(), initialDelay,
796     5, MILLISECONDS);
797 jsr166 1.33 try { p.shutdown(); } catch (SecurityException ok) { return; }
798     assertTrue(p.isShutdown());
799     assertTrue(p.getQueue().isEmpty());
800     assertTrue(task.isDone());
801     assertTrue(task.isCancelled());
802 jsr166 1.42 joinPool(p);
803 dl 1.2 }
804    
805 dl 1.5 /**
806 dl 1.6 * if setContinueExistingPeriodicTasksAfterShutdownPolicy is true,
807 jsr166 1.33 * periodic tasks are not cancelled at shutdown
808 dl 1.5 */
809 jsr166 1.41 public void testShutdown4() throws InterruptedException {
810 jsr166 1.33 ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
811     final CountDownLatch counter = new CountDownLatch(2);
812 dl 1.2 try {
813 jsr166 1.34 p.setContinueExistingPeriodicTasksAfterShutdownPolicy(true);
814     assertTrue(p.getExecuteExistingDelayedTasksAfterShutdownPolicy());
815     assertTrue(p.getContinueExistingPeriodicTasksAfterShutdownPolicy());
816 jsr166 1.33 final Runnable r = new CheckedRunnable() {
817     public void realRun() {
818     counter.countDown();
819     }};
820 dl 1.9 ScheduledFuture task =
821 jsr166 1.33 p.scheduleAtFixedRate(r, 1, 1, MILLISECONDS);
822     assertFalse(task.isDone());
823 dl 1.2 assertFalse(task.isCancelled());
824 jsr166 1.33 try { p.shutdown(); } catch (SecurityException ok) { return; }
825 dl 1.2 assertFalse(task.isCancelled());
826 jsr166 1.33 assertFalse(p.isTerminated());
827     assertTrue(p.isShutdown());
828     assertTrue(counter.await(SMALL_DELAY_MS, MILLISECONDS));
829 dl 1.2 assertFalse(task.isCancelled());
830 jsr166 1.33 assertTrue(task.cancel(false));
831 dl 1.15 assertTrue(task.isDone());
832 jsr166 1.33 assertTrue(task.isCancelled());
833     assertTrue(p.awaitTermination(SMALL_DELAY_MS, MILLISECONDS));
834     assertTrue(p.isTerminated());
835 dl 1.2 }
836 jsr166 1.22 finally {
837 jsr166 1.33 joinPool(p);
838 dl 1.2 }
839 dl 1.1 }
840    
841 dl 1.10 /**
842     * completed submit of callable returns result
843     */
844 jsr166 1.25 public void testSubmitCallable() throws Exception {
845 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
846     try {
847     Future<String> future = e.submit(new StringTask());
848     String result = future.get();
849     assertSame(TEST_STRING, result);
850     } finally {
851     joinPool(e);
852     }
853     }
854    
855     /**
856     * completed submit of runnable returns successfully
857     */
858 jsr166 1.25 public void testSubmitRunnable() throws Exception {
859 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
860     try {
861     Future<?> future = e.submit(new NoOpRunnable());
862     future.get();
863     assertTrue(future.isDone());
864     } finally {
865     joinPool(e);
866     }
867     }
868    
869     /**
870     * completed submit of (runnable, result) returns result
871     */
872 jsr166 1.25 public void testSubmitRunnable2() throws Exception {
873 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
874     try {
875     Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
876     String result = future.get();
877     assertSame(TEST_STRING, result);
878     } finally {
879     joinPool(e);
880     }
881     }
882    
883     /**
884     * invokeAny(null) throws NPE
885     */
886 jsr166 1.25 public void testInvokeAny1() throws Exception {
887 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
888     try {
889     e.invokeAny(null);
890 jsr166 1.25 shouldThrow();
891 dl 1.10 } catch (NullPointerException success) {
892     } finally {
893     joinPool(e);
894     }
895     }
896    
897     /**
898     * invokeAny(empty collection) throws IAE
899     */
900 jsr166 1.25 public void testInvokeAny2() throws Exception {
901 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
902     try {
903     e.invokeAny(new ArrayList<Callable<String>>());
904 jsr166 1.25 shouldThrow();
905 dl 1.10 } catch (IllegalArgumentException success) {
906     } finally {
907     joinPool(e);
908     }
909     }
910    
911     /**
912     * invokeAny(c) throws NPE if c has null elements
913     */
914 jsr166 1.25 public void testInvokeAny3() throws Exception {
915 jsr166 1.29 CountDownLatch latch = new CountDownLatch(1);
916 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
917 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
918     l.add(latchAwaitingStringTask(latch));
919     l.add(null);
920 dl 1.10 try {
921     e.invokeAny(l);
922 jsr166 1.25 shouldThrow();
923 dl 1.10 } catch (NullPointerException success) {
924     } finally {
925 jsr166 1.25 latch.countDown();
926 dl 1.10 joinPool(e);
927     }
928     }
929    
930     /**
931     * invokeAny(c) throws ExecutionException if no task completes
932     */
933 jsr166 1.25 public void testInvokeAny4() throws Exception {
934 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
935 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
936     l.add(new NPETask());
937 dl 1.10 try {
938     e.invokeAny(l);
939 jsr166 1.25 shouldThrow();
940 dl 1.10 } catch (ExecutionException success) {
941 jsr166 1.25 assertTrue(success.getCause() instanceof NullPointerException);
942 dl 1.10 } finally {
943     joinPool(e);
944     }
945     }
946    
947     /**
948     * invokeAny(c) returns result of some task
949     */
950 jsr166 1.25 public void testInvokeAny5() throws Exception {
951 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
952     try {
953 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
954 dl 1.10 l.add(new StringTask());
955     l.add(new StringTask());
956     String result = e.invokeAny(l);
957     assertSame(TEST_STRING, result);
958     } finally {
959     joinPool(e);
960     }
961     }
962    
963     /**
964     * invokeAll(null) throws NPE
965     */
966 jsr166 1.25 public void testInvokeAll1() throws Exception {
967 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
968     try {
969     e.invokeAll(null);
970 jsr166 1.25 shouldThrow();
971 dl 1.10 } catch (NullPointerException success) {
972     } finally {
973     joinPool(e);
974     }
975     }
976    
977     /**
978     * invokeAll(empty collection) returns empty collection
979     */
980 jsr166 1.25 public void testInvokeAll2() throws Exception {
981 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
982     try {
983     List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
984     assertTrue(r.isEmpty());
985     } finally {
986     joinPool(e);
987     }
988     }
989    
990     /**
991     * invokeAll(c) throws NPE if c has null elements
992     */
993 jsr166 1.25 public void testInvokeAll3() throws Exception {
994 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
995 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
996     l.add(new StringTask());
997     l.add(null);
998 dl 1.10 try {
999     e.invokeAll(l);
1000 jsr166 1.25 shouldThrow();
1001 dl 1.10 } catch (NullPointerException success) {
1002     } finally {
1003     joinPool(e);
1004     }
1005     }
1006    
1007     /**
1008     * get of invokeAll(c) throws exception on failed task
1009     */
1010 jsr166 1.25 public void testInvokeAll4() throws Exception {
1011 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1012 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1013     l.add(new NPETask());
1014     List<Future<String>> futures = e.invokeAll(l);
1015     assertEquals(1, futures.size());
1016 dl 1.10 try {
1017 jsr166 1.29 futures.get(0).get();
1018 jsr166 1.25 shouldThrow();
1019 jsr166 1.23 } catch (ExecutionException success) {
1020 jsr166 1.25 assertTrue(success.getCause() instanceof NullPointerException);
1021 dl 1.10 } finally {
1022     joinPool(e);
1023     }
1024     }
1025    
1026     /**
1027     * invokeAll(c) returns results of all completed tasks
1028     */
1029 jsr166 1.25 public void testInvokeAll5() throws Exception {
1030 dl 1.10 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1031     try {
1032 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1033 dl 1.10 l.add(new StringTask());
1034     l.add(new StringTask());
1035 jsr166 1.29 List<Future<String>> futures = e.invokeAll(l);
1036     assertEquals(2, futures.size());
1037     for (Future<String> future : futures)
1038 jsr166 1.25 assertSame(TEST_STRING, future.get());
1039 dl 1.10 } finally {
1040     joinPool(e);
1041     }
1042     }
1043    
1044 dl 1.11 /**
1045     * timed invokeAny(null) throws NPE
1046     */
1047 jsr166 1.25 public void testTimedInvokeAny1() throws Exception {
1048 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1049     try {
1050 jsr166 1.25 e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1051     shouldThrow();
1052 dl 1.11 } catch (NullPointerException success) {
1053     } finally {
1054     joinPool(e);
1055     }
1056     }
1057    
1058     /**
1059     * timed invokeAny(,,null) throws NPE
1060     */
1061 jsr166 1.25 public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1062 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1063 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1064     l.add(new StringTask());
1065 dl 1.11 try {
1066     e.invokeAny(l, MEDIUM_DELAY_MS, null);
1067 jsr166 1.25 shouldThrow();
1068 dl 1.11 } catch (NullPointerException success) {
1069     } finally {
1070     joinPool(e);
1071     }
1072     }
1073    
1074     /**
1075     * timed invokeAny(empty collection) throws IAE
1076     */
1077 jsr166 1.25 public void testTimedInvokeAny2() throws Exception {
1078 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1079     try {
1080 jsr166 1.25 e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1081     shouldThrow();
1082 dl 1.11 } catch (IllegalArgumentException success) {
1083     } finally {
1084     joinPool(e);
1085     }
1086     }
1087    
1088     /**
1089     * timed invokeAny(c) throws NPE if c has null elements
1090     */
1091 jsr166 1.25 public void testTimedInvokeAny3() throws Exception {
1092 jsr166 1.29 CountDownLatch latch = new CountDownLatch(1);
1093 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1094 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1095     l.add(latchAwaitingStringTask(latch));
1096     l.add(null);
1097 dl 1.11 try {
1098 jsr166 1.25 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1099     shouldThrow();
1100 dl 1.11 } catch (NullPointerException success) {
1101     } finally {
1102 jsr166 1.25 latch.countDown();
1103 dl 1.11 joinPool(e);
1104     }
1105     }
1106    
1107     /**
1108     * timed invokeAny(c) throws ExecutionException if no task completes
1109     */
1110 jsr166 1.25 public void testTimedInvokeAny4() throws Exception {
1111 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1112 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1113     l.add(new NPETask());
1114 dl 1.11 try {
1115 jsr166 1.25 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1116     shouldThrow();
1117 jsr166 1.23 } catch (ExecutionException success) {
1118 jsr166 1.25 assertTrue(success.getCause() instanceof NullPointerException);
1119 dl 1.11 } finally {
1120     joinPool(e);
1121     }
1122     }
1123    
1124     /**
1125     * timed invokeAny(c) returns result of some task
1126     */
1127 jsr166 1.25 public void testTimedInvokeAny5() throws Exception {
1128 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1129     try {
1130 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1131 dl 1.11 l.add(new StringTask());
1132     l.add(new StringTask());
1133 jsr166 1.25 String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1134 dl 1.11 assertSame(TEST_STRING, result);
1135     } finally {
1136     joinPool(e);
1137     }
1138     }
1139    
1140     /**
1141     * timed invokeAll(null) throws NPE
1142     */
1143 jsr166 1.25 public void testTimedInvokeAll1() throws Exception {
1144 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1145     try {
1146 jsr166 1.25 e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1147     shouldThrow();
1148 dl 1.11 } catch (NullPointerException success) {
1149     } finally {
1150     joinPool(e);
1151     }
1152     }
1153    
1154     /**
1155     * timed invokeAll(,,null) throws NPE
1156     */
1157 jsr166 1.25 public void testTimedInvokeAllNullTimeUnit() throws Exception {
1158 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1159 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1160     l.add(new StringTask());
1161 dl 1.11 try {
1162     e.invokeAll(l, MEDIUM_DELAY_MS, null);
1163 jsr166 1.25 shouldThrow();
1164 dl 1.11 } catch (NullPointerException success) {
1165     } finally {
1166     joinPool(e);
1167     }
1168     }
1169    
1170     /**
1171     * timed invokeAll(empty collection) returns empty collection
1172     */
1173 jsr166 1.25 public void testTimedInvokeAll2() throws Exception {
1174 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1175     try {
1176 jsr166 1.25 List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1177 dl 1.11 assertTrue(r.isEmpty());
1178     } finally {
1179     joinPool(e);
1180     }
1181     }
1182    
1183     /**
1184     * timed invokeAll(c) throws NPE if c has null elements
1185     */
1186 jsr166 1.25 public void testTimedInvokeAll3() throws Exception {
1187 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1188 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1189     l.add(new StringTask());
1190     l.add(null);
1191 dl 1.11 try {
1192 jsr166 1.25 e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1193     shouldThrow();
1194 dl 1.11 } catch (NullPointerException success) {
1195     } finally {
1196     joinPool(e);
1197     }
1198     }
1199    
1200     /**
1201     * get of element of invokeAll(c) throws exception on failed task
1202     */
1203 jsr166 1.25 public void testTimedInvokeAll4() throws Exception {
1204 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1205 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1206     l.add(new NPETask());
1207     List<Future<String>> futures =
1208     e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1209     assertEquals(1, futures.size());
1210 dl 1.11 try {
1211 jsr166 1.29 futures.get(0).get();
1212 jsr166 1.25 shouldThrow();
1213 jsr166 1.23 } catch (ExecutionException success) {
1214 jsr166 1.25 assertTrue(success.getCause() instanceof NullPointerException);
1215 dl 1.11 } finally {
1216     joinPool(e);
1217     }
1218     }
1219    
1220     /**
1221     * timed invokeAll(c) returns results of all completed tasks
1222     */
1223 jsr166 1.25 public void testTimedInvokeAll5() throws Exception {
1224 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1225     try {
1226 jsr166 1.29 List<Callable<String>> l = new ArrayList<Callable<String>>();
1227 dl 1.11 l.add(new StringTask());
1228     l.add(new StringTask());
1229 jsr166 1.29 List<Future<String>> futures =
1230     e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1231     assertEquals(2, futures.size());
1232     for (Future<String> future : futures)
1233 jsr166 1.25 assertSame(TEST_STRING, future.get());
1234 dl 1.11 } finally {
1235     joinPool(e);
1236     }
1237     }
1238    
1239     /**
1240     * timed invokeAll(c) cancels tasks not completed by timeout
1241     */
1242 jsr166 1.25 public void testTimedInvokeAll6() throws Exception {
1243 dl 1.11 ExecutorService e = new ScheduledThreadPoolExecutor(2);
1244     try {
1245 jsr166 1.52 for (long timeout = timeoutMillis();;) {
1246     List<Callable<String>> tasks = new ArrayList<>();
1247     tasks.add(new StringTask("0"));
1248     tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1249     tasks.add(new StringTask("2"));
1250     long startTime = System.nanoTime();
1251     List<Future<String>> futures =
1252     e.invokeAll(tasks, timeout, MILLISECONDS);
1253     assertEquals(tasks.size(), futures.size());
1254     assertTrue(millisElapsedSince(startTime) >= timeout);
1255     for (Future future : futures)
1256     assertTrue(future.isDone());
1257     assertTrue(futures.get(1).isCancelled());
1258     try {
1259     assertEquals("0", futures.get(0).get());
1260     assertEquals("2", futures.get(2).get());
1261     break;
1262     } catch (CancellationException retryWithLongerTimeout) {
1263     timeout *= 2;
1264     if (timeout >= LONG_DELAY_MS / 2)
1265     fail("expected exactly one task to be cancelled");
1266     }
1267     }
1268 dl 1.11 } finally {
1269     joinPool(e);
1270     }
1271     }
1272    
1273 dl 1.1 }