ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ScheduledExecutorSubclassTest.java
Revision: 1.16
Committed: Mon Oct 11 15:46:40 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.15: +9 -1 lines
Log Message:
add a few assertions

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