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