ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorTest.java
Revision: 1.50
Committed: Wed Dec 31 19:05:43 2014 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.49: +18 -3 lines
Log Message:
no wildcard imports

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