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