ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.47
Committed: Tue Sep 24 18:35:21 2013 UTC (10 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.46: +44 -20 lines
Log Message:
Improve expected execution times of testFixedDelaySequence,testFixedRateSequence

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