ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorSubclassTest.java
Revision: 1.32
Committed: Wed Sep 25 06:59:34 2013 UTC (10 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.31: +0 -2 lines
Log Message:
whitespace

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