ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java
Revision: 1.21
Committed: Mon Oct 11 07:21:32 2010 UTC (13 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.20: +419 -219 lines
Log Message:
remove timing dependencies and optimize runtimes; descriptions of testShutdown3 and testShutdown4 were reversed; testShutDown2 never tested its assertion

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 * Other contributors include Andrew Wright, Jeffrey Hayes,
6 * Pat Fisher, Mike Judd.
7 */
8
9 import java.util.concurrent.*;
10 import static java.util.concurrent.TimeUnit.MILLISECONDS;
11 import java.util.concurrent.locks.*;
12
13 import junit.framework.*;
14 import java.util.*;
15
16 public class ThreadPoolExecutorSubclassTest extends JSR166TestCase {
17 public static void main(String[] args) {
18 junit.textui.TestRunner.run(suite());
19 }
20 public static Test suite() {
21 return new TestSuite(ThreadPoolExecutorSubclassTest.class);
22 }
23
24 static class CustomTask<V> implements RunnableFuture<V> {
25 final Callable<V> callable;
26 final ReentrantLock lock = new ReentrantLock();
27 final Condition cond = lock.newCondition();
28 boolean done;
29 boolean cancelled;
30 V result;
31 Thread thread;
32 Exception exception;
33 CustomTask(Callable<V> c) {
34 if (c == null) throw new NullPointerException();
35 callable = c;
36 }
37 CustomTask(final Runnable r, final V res) {
38 if (r == null) throw new NullPointerException();
39 callable = new Callable<V>() {
40 public V call() throws Exception { r.run(); return res; }};
41 }
42 public boolean isDone() {
43 lock.lock(); try { return done; } finally { lock.unlock() ; }
44 }
45 public boolean isCancelled() {
46 lock.lock(); try { return cancelled; } finally { lock.unlock() ; }
47 }
48 public boolean cancel(boolean mayInterrupt) {
49 lock.lock();
50 try {
51 if (!done) {
52 cancelled = true;
53 done = true;
54 if (mayInterrupt && thread != null)
55 thread.interrupt();
56 return true;
57 }
58 return false;
59 }
60 finally { lock.unlock() ; }
61 }
62 public void run() {
63 boolean runme;
64 lock.lock();
65 try {
66 runme = !done;
67 if (!runme)
68 thread = Thread.currentThread();
69 }
70 finally { lock.unlock() ; }
71 if (!runme) return;
72 V v = null;
73 Exception e = null;
74 try {
75 v = callable.call();
76 }
77 catch (Exception ex) {
78 e = ex;
79 }
80 lock.lock();
81 try {
82 result = v;
83 exception = e;
84 done = true;
85 thread = null;
86 cond.signalAll();
87 }
88 finally { lock.unlock(); }
89 }
90 public V get() throws InterruptedException, ExecutionException {
91 lock.lock();
92 try {
93 while (!done)
94 cond.await();
95 if (exception != null)
96 throw new ExecutionException(exception);
97 return result;
98 }
99 finally { lock.unlock(); }
100 }
101 public V get(long timeout, TimeUnit unit)
102 throws InterruptedException, ExecutionException, TimeoutException {
103 long nanos = unit.toNanos(timeout);
104 lock.lock();
105 try {
106 for (;;) {
107 if (done) break;
108 if (nanos < 0)
109 throw new TimeoutException();
110 nanos = cond.awaitNanos(nanos);
111 }
112 if (exception != null)
113 throw new ExecutionException(exception);
114 return result;
115 }
116 finally { lock.unlock(); }
117 }
118 }
119
120
121 static class CustomTPE extends ThreadPoolExecutor {
122 protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
123 return new CustomTask<V>(c);
124 }
125 protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
126 return new CustomTask<V>(r, v);
127 }
128
129 CustomTPE(int corePoolSize,
130 int maximumPoolSize,
131 long keepAliveTime,
132 TimeUnit unit,
133 BlockingQueue<Runnable> workQueue) {
134 super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
135 workQueue);
136 }
137 CustomTPE(int corePoolSize,
138 int maximumPoolSize,
139 long keepAliveTime,
140 TimeUnit unit,
141 BlockingQueue<Runnable> workQueue,
142 ThreadFactory threadFactory) {
143 super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
144 threadFactory);
145 }
146
147 CustomTPE(int corePoolSize,
148 int maximumPoolSize,
149 long keepAliveTime,
150 TimeUnit unit,
151 BlockingQueue<Runnable> workQueue,
152 RejectedExecutionHandler handler) {
153 super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
154 handler);
155 }
156 CustomTPE(int corePoolSize,
157 int maximumPoolSize,
158 long keepAliveTime,
159 TimeUnit unit,
160 BlockingQueue<Runnable> workQueue,
161 ThreadFactory threadFactory,
162 RejectedExecutionHandler handler) {
163 super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
164 workQueue, threadFactory, handler);
165 }
166
167 volatile boolean beforeCalled = false;
168 volatile boolean afterCalled = false;
169 volatile boolean terminatedCalled = false;
170 public CustomTPE() {
171 super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue<Runnable>());
172 }
173 protected void beforeExecute(Thread t, Runnable r) {
174 beforeCalled = true;
175 }
176 protected void afterExecute(Runnable r, Throwable t) {
177 afterCalled = true;
178 }
179 protected void terminated() {
180 terminatedCalled = true;
181 }
182
183 }
184
185 static class FailingThreadFactory implements ThreadFactory {
186 int calls = 0;
187 public Thread newThread(Runnable r) {
188 if (++calls > 1) return null;
189 return new Thread(r);
190 }
191 }
192
193
194 /**
195 * execute successfully executes a runnable
196 */
197 public void testExecute() throws InterruptedException {
198 final ThreadPoolExecutor p =
199 new CustomTPE(1, 1,
200 LONG_DELAY_MS, MILLISECONDS,
201 new ArrayBlockingQueue<Runnable>(10));
202 final CountDownLatch done = new CountDownLatch(1);
203 final Runnable task = new CheckedRunnable() {
204 public void realRun() {
205 done.countDown();
206 }};
207 try {
208 p.execute(task);
209 assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
210 } finally {
211 joinPool(p);
212 }
213 }
214
215 /**
216 * getActiveCount increases but doesn't overestimate, when a
217 * thread becomes active
218 */
219 public void testGetActiveCount() throws InterruptedException {
220 final ThreadPoolExecutor p =
221 new CustomTPE(2, 2,
222 LONG_DELAY_MS, MILLISECONDS,
223 new ArrayBlockingQueue<Runnable>(10));
224 final CountDownLatch threadStarted = new CountDownLatch(1);
225 final CountDownLatch done = new CountDownLatch(1);
226 try {
227 assertEquals(0, p.getActiveCount());
228 p.execute(new CheckedRunnable() {
229 public void realRun() throws InterruptedException {
230 threadStarted.countDown();
231 assertEquals(1, p.getActiveCount());
232 done.await();
233 }});
234 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
235 assertEquals(1, p.getActiveCount());
236 } finally {
237 done.countDown();
238 joinPool(p);
239 }
240 }
241
242 /**
243 * prestartCoreThread starts a thread if under corePoolSize, else doesn't
244 */
245 public void testPrestartCoreThread() {
246 ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
247 assertEquals(0, p.getPoolSize());
248 assertTrue(p.prestartCoreThread());
249 assertEquals(1, p.getPoolSize());
250 assertTrue(p.prestartCoreThread());
251 assertEquals(2, p.getPoolSize());
252 assertFalse(p.prestartCoreThread());
253 assertEquals(2, p.getPoolSize());
254 joinPool(p);
255 }
256
257 /**
258 * prestartAllCoreThreads starts all corePoolSize threads
259 */
260 public void testPrestartAllCoreThreads() {
261 ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
262 assertEquals(0, p.getPoolSize());
263 p.prestartAllCoreThreads();
264 assertEquals(2, p.getPoolSize());
265 p.prestartAllCoreThreads();
266 assertEquals(2, p.getPoolSize());
267 joinPool(p);
268 }
269
270 /**
271 * getCompletedTaskCount increases, but doesn't overestimate,
272 * when tasks complete
273 */
274 public void testGetCompletedTaskCount() throws InterruptedException {
275 final ThreadPoolExecutor p =
276 new CustomTPE(2, 2,
277 LONG_DELAY_MS, MILLISECONDS,
278 new ArrayBlockingQueue<Runnable>(10));
279 final CountDownLatch threadStarted = new CountDownLatch(1);
280 final CountDownLatch threadProceed = new CountDownLatch(1);
281 final CountDownLatch threadDone = new CountDownLatch(1);
282 try {
283 assertEquals(0, p.getCompletedTaskCount());
284 p.execute(new CheckedRunnable() {
285 public void realRun() throws InterruptedException {
286 threadStarted.countDown();
287 assertEquals(0, p.getCompletedTaskCount());
288 threadProceed.await();
289 threadDone.countDown();
290 }});
291 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
292 assertEquals(0, p.getCompletedTaskCount());
293 threadProceed.countDown();
294 threadDone.await();
295 Thread.sleep(SHORT_DELAY_MS);
296 assertEquals(1, p.getCompletedTaskCount());
297 } finally {
298 joinPool(p);
299 }
300 }
301
302 /**
303 * getCorePoolSize returns size given in constructor if not otherwise set
304 */
305 public void testGetCorePoolSize() {
306 ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
307 assertEquals(1, p.getCorePoolSize());
308 joinPool(p);
309 }
310
311 /**
312 * getKeepAliveTime returns value given in constructor if not otherwise set
313 */
314 public void testGetKeepAliveTime() {
315 ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
316 assertEquals(1, p.getKeepAliveTime(TimeUnit.SECONDS));
317 joinPool(p);
318 }
319
320
321 /**
322 * getThreadFactory returns factory in constructor if not set
323 */
324 public void testGetThreadFactory() {
325 ThreadFactory tf = new SimpleThreadFactory();
326 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), tf, new NoOpREHandler());
327 assertSame(tf, p.getThreadFactory());
328 joinPool(p);
329 }
330
331 /**
332 * setThreadFactory sets the thread factory returned by getThreadFactory
333 */
334 public void testSetThreadFactory() {
335 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
336 ThreadFactory tf = new SimpleThreadFactory();
337 p.setThreadFactory(tf);
338 assertSame(tf, p.getThreadFactory());
339 joinPool(p);
340 }
341
342
343 /**
344 * setThreadFactory(null) throws NPE
345 */
346 public void testSetThreadFactoryNull() {
347 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
348 try {
349 p.setThreadFactory(null);
350 shouldThrow();
351 } catch (NullPointerException success) {
352 } finally {
353 joinPool(p);
354 }
355 }
356
357 /**
358 * getRejectedExecutionHandler returns handler in constructor if not set
359 */
360 public void testGetRejectedExecutionHandler() {
361 RejectedExecutionHandler h = new NoOpREHandler();
362 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), h);
363 assertSame(h, p.getRejectedExecutionHandler());
364 joinPool(p);
365 }
366
367 /**
368 * setRejectedExecutionHandler sets the handler returned by
369 * getRejectedExecutionHandler
370 */
371 public void testSetRejectedExecutionHandler() {
372 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
373 RejectedExecutionHandler h = new NoOpREHandler();
374 p.setRejectedExecutionHandler(h);
375 assertSame(h, p.getRejectedExecutionHandler());
376 joinPool(p);
377 }
378
379
380 /**
381 * setRejectedExecutionHandler(null) throws NPE
382 */
383 public void testSetRejectedExecutionHandlerNull() {
384 ThreadPoolExecutor p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
385 try {
386 p.setRejectedExecutionHandler(null);
387 shouldThrow();
388 } catch (NullPointerException success) {
389 } finally {
390 joinPool(p);
391 }
392 }
393
394
395 /**
396 * getLargestPoolSize increases, but doesn't overestimate, when
397 * multiple threads active
398 */
399 public void testGetLargestPoolSize() throws InterruptedException {
400 final int THREADS = 3;
401 final ThreadPoolExecutor p =
402 new CustomTPE(THREADS, THREADS,
403 LONG_DELAY_MS, MILLISECONDS,
404 new ArrayBlockingQueue<Runnable>(10));
405 final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
406 final CountDownLatch done = new CountDownLatch(1);
407 try {
408 assertEquals(0, p.getLargestPoolSize());
409 for (int i = 0; i < THREADS; i++)
410 p.execute(new CheckedRunnable() {
411 public void realRun() throws InterruptedException {
412 threadsStarted.countDown();
413 done.await();
414 assertEquals(THREADS, p.getLargestPoolSize());
415 }});
416 assertTrue(threadsStarted.await(SMALL_DELAY_MS, MILLISECONDS));
417 assertEquals(THREADS, p.getLargestPoolSize());
418 } finally {
419 done.countDown();
420 joinPool(p);
421 assertEquals(THREADS, p.getLargestPoolSize());
422 }
423 }
424
425 /**
426 * getMaximumPoolSize returns value given in constructor if not
427 * otherwise set
428 */
429 public void testGetMaximumPoolSize() {
430 ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
431 assertEquals(2, p.getMaximumPoolSize());
432 joinPool(p);
433 }
434
435 /**
436 * getPoolSize increases, but doesn't overestimate, when threads
437 * become active
438 */
439 public void testGetPoolSize() throws InterruptedException {
440 final ThreadPoolExecutor p =
441 new CustomTPE(1, 1,
442 LONG_DELAY_MS, MILLISECONDS,
443 new ArrayBlockingQueue<Runnable>(10));
444 final CountDownLatch threadStarted = new CountDownLatch(1);
445 final CountDownLatch done = new CountDownLatch(1);
446 try {
447 assertEquals(0, p.getPoolSize());
448 p.execute(new CheckedRunnable() {
449 public void realRun() throws InterruptedException {
450 threadStarted.countDown();
451 assertEquals(1, p.getPoolSize());
452 done.await();
453 }});
454 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
455 assertEquals(1, p.getPoolSize());
456 } finally {
457 done.countDown();
458 joinPool(p);
459 }
460 }
461
462 /**
463 * getTaskCount increases, but doesn't overestimate, when tasks submitted
464 */
465 public void testGetTaskCount() throws InterruptedException {
466 final ThreadPoolExecutor p =
467 new CustomTPE(1, 1,
468 LONG_DELAY_MS, MILLISECONDS,
469 new ArrayBlockingQueue<Runnable>(10));
470 final CountDownLatch threadStarted = new CountDownLatch(1);
471 final CountDownLatch done = new CountDownLatch(1);
472 try {
473 assertEquals(0, p.getTaskCount());
474 p.execute(new CheckedRunnable() {
475 public void realRun() throws InterruptedException {
476 threadStarted.countDown();
477 assertEquals(1, p.getTaskCount());
478 done.await();
479 }});
480 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
481 assertEquals(1, p.getTaskCount());
482 } finally {
483 done.countDown();
484 joinPool(p);
485 }
486 }
487
488 /**
489 * isShutDown is false before shutdown, true after
490 */
491 public void testIsShutdown() {
492
493 ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
494 assertFalse(p.isShutdown());
495 try { p.shutdown(); } catch (SecurityException ok) { return; }
496 assertTrue(p.isShutdown());
497 joinPool(p);
498 }
499
500
501 /**
502 * isTerminated is false before termination, true after
503 */
504 public void testIsTerminated() throws InterruptedException {
505 final ThreadPoolExecutor p =
506 new CustomTPE(1, 1,
507 LONG_DELAY_MS, MILLISECONDS,
508 new ArrayBlockingQueue<Runnable>(10));
509 final CountDownLatch threadStarted = new CountDownLatch(1);
510 final CountDownLatch done = new CountDownLatch(1);
511 try {
512 assertFalse(p.isTerminating());
513 p.execute(new CheckedRunnable() {
514 public void realRun() throws InterruptedException {
515 threadStarted.countDown();
516 assertFalse(p.isTerminating());
517 done.await();
518 }});
519 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
520 assertFalse(p.isTerminating());
521 done.countDown();
522 } finally {
523 try { p.shutdown(); } catch (SecurityException ok) { return; }
524 }
525 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
526 assertTrue(p.isTerminated());
527 assertFalse(p.isTerminating());
528 }
529
530 /**
531 * isTerminating is not true when running or when terminated
532 */
533 public void testIsTerminating() throws InterruptedException {
534 final ThreadPoolExecutor p =
535 new CustomTPE(1, 1,
536 LONG_DELAY_MS, MILLISECONDS,
537 new ArrayBlockingQueue<Runnable>(10));
538 final CountDownLatch threadStarted = new CountDownLatch(1);
539 final CountDownLatch done = new CountDownLatch(1);
540 try {
541 assertFalse(p.isTerminating());
542 p.execute(new CheckedRunnable() {
543 public void realRun() throws InterruptedException {
544 threadStarted.countDown();
545 assertFalse(p.isTerminating());
546 done.await();
547 }});
548 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
549 assertFalse(p.isTerminating());
550 done.countDown();
551 } finally {
552 try { p.shutdown(); } catch (SecurityException ok) { return; }
553 }
554 assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
555 assertTrue(p.isTerminated());
556 assertFalse(p.isTerminating());
557 }
558
559 /**
560 * getQueue returns the work queue, which contains queued tasks
561 */
562 public void testGetQueue() throws InterruptedException {
563 final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
564 final ThreadPoolExecutor p =
565 new CustomTPE(1, 1,
566 LONG_DELAY_MS, MILLISECONDS,
567 q);
568 final CountDownLatch threadStarted = new CountDownLatch(1);
569 final CountDownLatch done = new CountDownLatch(1);
570 try {
571 FutureTask[] tasks = new FutureTask[5];
572 for (int i = 0; i < tasks.length; i++) {
573 Callable task = new CheckedCallable<Boolean>() {
574 public Boolean realCall() throws InterruptedException {
575 threadStarted.countDown();
576 assertSame(q, p.getQueue());
577 done.await();
578 return Boolean.TRUE;
579 }};
580 tasks[i] = new FutureTask(task);
581 p.execute(tasks[i]);
582 }
583 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
584 assertSame(q, p.getQueue());
585 assertFalse(q.contains(tasks[0]));
586 assertTrue(q.contains(tasks[tasks.length - 1]));
587 assertEquals(tasks.length - 1, q.size());
588 } finally {
589 done.countDown();
590 joinPool(p);
591 }
592 }
593
594 /**
595 * remove(task) removes queued task, and fails to remove active task
596 */
597 public void testRemove() throws InterruptedException {
598 BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
599 final ThreadPoolExecutor p =
600 new CustomTPE(1, 1,
601 LONG_DELAY_MS, MILLISECONDS,
602 q);
603 Runnable[] tasks = new Runnable[6];
604 final CountDownLatch threadStarted = new CountDownLatch(1);
605 final CountDownLatch done = new CountDownLatch(1);
606 try {
607 for (int i = 0; i < tasks.length; i++) {
608 tasks[i] = new CheckedRunnable() {
609 public void realRun() throws InterruptedException {
610 threadStarted.countDown();
611 done.await();
612 }};
613 p.execute(tasks[i]);
614 }
615 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
616 assertFalse(p.remove(tasks[0]));
617 assertTrue(q.contains(tasks[4]));
618 assertTrue(q.contains(tasks[3]));
619 assertTrue(p.remove(tasks[4]));
620 assertFalse(p.remove(tasks[4]));
621 assertFalse(q.contains(tasks[4]));
622 assertTrue(q.contains(tasks[3]));
623 assertTrue(p.remove(tasks[3]));
624 assertFalse(q.contains(tasks[3]));
625 } finally {
626 done.countDown();
627 joinPool(p);
628 }
629 }
630
631 /**
632 * purge removes cancelled tasks from the queue
633 */
634 public void testPurge() throws InterruptedException {
635 final CountDownLatch threadStarted = new CountDownLatch(1);
636 final CountDownLatch done = new CountDownLatch(1);
637 final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
638 final ThreadPoolExecutor p =
639 new CustomTPE(1, 1,
640 LONG_DELAY_MS, MILLISECONDS,
641 q);
642 FutureTask[] tasks = new FutureTask[5];
643 try {
644 for (int i = 0; i < tasks.length; i++) {
645 Callable task = new CheckedCallable<Boolean>() {
646 public Boolean realCall() throws InterruptedException {
647 threadStarted.countDown();
648 done.await();
649 return Boolean.TRUE;
650 }};
651 tasks[i] = new FutureTask(task);
652 p.execute(tasks[i]);
653 }
654 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
655 assertEquals(tasks.length, p.getTaskCount());
656 assertEquals(tasks.length - 1, q.size());
657 assertEquals(1L, p.getActiveCount());
658 assertEquals(0L, p.getCompletedTaskCount());
659 tasks[4].cancel(true);
660 tasks[3].cancel(false);
661 p.purge();
662 assertEquals(tasks.length - 3, q.size());
663 assertEquals(tasks.length - 2, p.getTaskCount());
664 p.purge(); // Nothing to do
665 assertEquals(tasks.length - 3, q.size());
666 assertEquals(tasks.length - 2, p.getTaskCount());
667 } finally {
668 done.countDown();
669 joinPool(p);
670 }
671 }
672
673 /**
674 * shutDownNow returns a list containing tasks that were not run
675 */
676 public void testShutDownNow() {
677 ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
678 List l;
679 try {
680 for (int i = 0; i < 5; i++)
681 p.execute(new MediumPossiblyInterruptedRunnable());
682 }
683 finally {
684 try {
685 l = p.shutdownNow();
686 } catch (SecurityException ok) { return; }
687 }
688 assertTrue(p.isShutdown());
689 assertTrue(l.size() <= 4);
690 }
691
692 // Exception Tests
693
694
695 /**
696 * Constructor throws if corePoolSize argument is less than zero
697 */
698 public void testConstructor1() {
699 try {
700 new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
701 shouldThrow();
702 } catch (IllegalArgumentException success) {}
703 }
704
705 /**
706 * Constructor throws if maximumPoolSize is less than zero
707 */
708 public void testConstructor2() {
709 try {
710 new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
711 shouldThrow();
712 } catch (IllegalArgumentException success) {}
713 }
714
715 /**
716 * Constructor throws if maximumPoolSize is equal to zero
717 */
718 public void testConstructor3() {
719 try {
720 new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
721 shouldThrow();
722 } catch (IllegalArgumentException success) {}
723 }
724
725 /**
726 * Constructor throws if keepAliveTime is less than zero
727 */
728 public void testConstructor4() {
729 try {
730 new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
731 shouldThrow();
732 } catch (IllegalArgumentException success) {}
733 }
734
735 /**
736 * Constructor throws if corePoolSize is greater than the maximumPoolSize
737 */
738 public void testConstructor5() {
739 try {
740 new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
741 shouldThrow();
742 } catch (IllegalArgumentException success) {}
743 }
744
745 /**
746 * Constructor throws if workQueue is set to null
747 */
748 public void testConstructorNullPointerException() {
749 try {
750 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null);
751 shouldThrow();
752 } catch (NullPointerException success) {}
753 }
754
755
756
757 /**
758 * Constructor throws if corePoolSize argument is less than zero
759 */
760 public void testConstructor6() {
761 try {
762 new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
763 shouldThrow();
764 } catch (IllegalArgumentException success) {}
765 }
766
767 /**
768 * Constructor throws if maximumPoolSize is less than zero
769 */
770 public void testConstructor7() {
771 try {
772 new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
773 shouldThrow();
774 } catch (IllegalArgumentException success) {}
775 }
776
777 /**
778 * Constructor throws if maximumPoolSize is equal to zero
779 */
780 public void testConstructor8() {
781 try {
782 new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
783 shouldThrow();
784 } catch (IllegalArgumentException success) {}
785 }
786
787 /**
788 * Constructor throws if keepAliveTime is less than zero
789 */
790 public void testConstructor9() {
791 try {
792 new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
793 shouldThrow();
794 } catch (IllegalArgumentException success) {}
795 }
796
797 /**
798 * Constructor throws if corePoolSize is greater than the maximumPoolSize
799 */
800 public void testConstructor10() {
801 try {
802 new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory());
803 shouldThrow();
804 } catch (IllegalArgumentException success) {}
805 }
806
807 /**
808 * Constructor throws if workQueue is set to null
809 */
810 public void testConstructorNullPointerException2() {
811 try {
812 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory());
813 shouldThrow();
814 } catch (NullPointerException success) {}
815 }
816
817 /**
818 * Constructor throws if threadFactory is set to null
819 */
820 public void testConstructorNullPointerException3() {
821 try {
822 ThreadFactory f = null;
823 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),f);
824 shouldThrow();
825 } catch (NullPointerException success) {}
826 }
827
828
829 /**
830 * Constructor throws if corePoolSize argument is less than zero
831 */
832 public void testConstructor11() {
833 try {
834 new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
835 shouldThrow();
836 } catch (IllegalArgumentException success) {}
837 }
838
839 /**
840 * Constructor throws if maximumPoolSize is less than zero
841 */
842 public void testConstructor12() {
843 try {
844 new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
845 shouldThrow();
846 } catch (IllegalArgumentException success) {}
847 }
848
849 /**
850 * Constructor throws if maximumPoolSize is equal to zero
851 */
852 public void testConstructor13() {
853 try {
854 new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
855 shouldThrow();
856 } catch (IllegalArgumentException success) {}
857 }
858
859 /**
860 * Constructor throws if keepAliveTime is less than zero
861 */
862 public void testConstructor14() {
863 try {
864 new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
865 shouldThrow();
866 } catch (IllegalArgumentException success) {}
867 }
868
869 /**
870 * Constructor throws if corePoolSize is greater than the maximumPoolSize
871 */
872 public void testConstructor15() {
873 try {
874 new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new NoOpREHandler());
875 shouldThrow();
876 } catch (IllegalArgumentException success) {}
877 }
878
879 /**
880 * Constructor throws if workQueue is set to null
881 */
882 public void testConstructorNullPointerException4() {
883 try {
884 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new NoOpREHandler());
885 shouldThrow();
886 } catch (NullPointerException success) {}
887 }
888
889 /**
890 * Constructor throws if handler is set to null
891 */
892 public void testConstructorNullPointerException5() {
893 try {
894 RejectedExecutionHandler r = null;
895 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),r);
896 shouldThrow();
897 } catch (NullPointerException success) {}
898 }
899
900
901 /**
902 * Constructor throws if corePoolSize argument is less than zero
903 */
904 public void testConstructor16() {
905 try {
906 new CustomTPE(-1,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
907 shouldThrow();
908 } catch (IllegalArgumentException success) {}
909 }
910
911 /**
912 * Constructor throws if maximumPoolSize is less than zero
913 */
914 public void testConstructor17() {
915 try {
916 new CustomTPE(1,-1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
917 shouldThrow();
918 } catch (IllegalArgumentException success) {}
919 }
920
921 /**
922 * Constructor throws if maximumPoolSize is equal to zero
923 */
924 public void testConstructor18() {
925 try {
926 new CustomTPE(1,0,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
927 shouldThrow();
928 } catch (IllegalArgumentException success) {}
929 }
930
931 /**
932 * Constructor throws if keepAliveTime is less than zero
933 */
934 public void testConstructor19() {
935 try {
936 new CustomTPE(1,2,-1L,MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
937 shouldThrow();
938 } catch (IllegalArgumentException success) {}
939 }
940
941 /**
942 * Constructor throws if corePoolSize is greater than the maximumPoolSize
943 */
944 public void testConstructor20() {
945 try {
946 new CustomTPE(2,1,LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),new NoOpREHandler());
947 shouldThrow();
948 } catch (IllegalArgumentException success) {}
949 }
950
951 /**
952 * Constructor throws if workQueue is null
953 */
954 public void testConstructorNullPointerException6() {
955 try {
956 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,null,new SimpleThreadFactory(),new NoOpREHandler());
957 shouldThrow();
958 } catch (NullPointerException success) {}
959 }
960
961 /**
962 * Constructor throws if handler is null
963 */
964 public void testConstructorNullPointerException7() {
965 try {
966 RejectedExecutionHandler r = null;
967 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10),new SimpleThreadFactory(),r);
968 shouldThrow();
969 } catch (NullPointerException success) {}
970 }
971
972 /**
973 * Constructor throws if ThreadFactory is null
974 */
975 public void testConstructorNullPointerException8() {
976 try {
977 new CustomTPE(1, 2,
978 LONG_DELAY_MS, MILLISECONDS,
979 new ArrayBlockingQueue<Runnable>(10),
980 (ThreadFactory) null,
981 new NoOpREHandler());
982 shouldThrow();
983 } catch (NullPointerException success) {}
984 }
985
986
987 /**
988 * execute throws RejectedExecutionException if saturated.
989 */
990 public void testSaturatedExecute() {
991 ThreadPoolExecutor p =
992 new CustomTPE(1, 1,
993 LONG_DELAY_MS, MILLISECONDS,
994 new ArrayBlockingQueue<Runnable>(1));
995 final CountDownLatch done = new CountDownLatch(1);
996 try {
997 Runnable task = new CheckedRunnable() {
998 public void realRun() throws InterruptedException {
999 done.await();
1000 }};
1001 for (int i = 0; i < 2; ++i)
1002 p.execute(task);
1003 for (int i = 0; i < 2; ++i) {
1004 try {
1005 p.execute(task);
1006 shouldThrow();
1007 } catch (RejectedExecutionException success) {}
1008 assertTrue(p.getTaskCount() <= 2);
1009 }
1010 } finally {
1011 done.countDown();
1012 joinPool(p);
1013 }
1014 }
1015
1016 /**
1017 * executor using CallerRunsPolicy runs task if saturated.
1018 */
1019 public void testSaturatedExecute2() {
1020 RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
1021 ThreadPoolExecutor p = new CustomTPE(1, 1,
1022 LONG_DELAY_MS, MILLISECONDS,
1023 new ArrayBlockingQueue<Runnable>(1),
1024 h);
1025 try {
1026 TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1027 for (int i = 0; i < tasks.length; ++i)
1028 tasks[i] = new TrackedNoOpRunnable();
1029 TrackedLongRunnable mr = new TrackedLongRunnable();
1030 p.execute(mr);
1031 for (int i = 0; i < tasks.length; ++i)
1032 p.execute(tasks[i]);
1033 for (int i = 1; i < tasks.length; ++i)
1034 assertTrue(tasks[i].done);
1035 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1036 } finally {
1037 joinPool(p);
1038 }
1039 }
1040
1041 /**
1042 * executor using DiscardPolicy drops task if saturated.
1043 */
1044 public void testSaturatedExecute3() {
1045 RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
1046 ThreadPoolExecutor p =
1047 new CustomTPE(1, 1,
1048 LONG_DELAY_MS, MILLISECONDS,
1049 new ArrayBlockingQueue<Runnable>(1),
1050 h);
1051 try {
1052 TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1053 for (int i = 0; i < tasks.length; ++i)
1054 tasks[i] = new TrackedNoOpRunnable();
1055 p.execute(new TrackedLongRunnable());
1056 for (TrackedNoOpRunnable task : tasks)
1057 p.execute(task);
1058 for (TrackedNoOpRunnable task : tasks)
1059 assertFalse(task.done);
1060 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1061 } finally {
1062 joinPool(p);
1063 }
1064 }
1065
1066 /**
1067 * executor using DiscardOldestPolicy drops oldest task if saturated.
1068 */
1069 public void testSaturatedExecute4() {
1070 RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
1071 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1072 try {
1073 p.execute(new TrackedLongRunnable());
1074 TrackedLongRunnable r2 = new TrackedLongRunnable();
1075 p.execute(r2);
1076 assertTrue(p.getQueue().contains(r2));
1077 TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
1078 p.execute(r3);
1079 assertFalse(p.getQueue().contains(r2));
1080 assertTrue(p.getQueue().contains(r3));
1081 try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1082 } finally {
1083 joinPool(p);
1084 }
1085 }
1086
1087 /**
1088 * execute throws RejectedExecutionException if shutdown
1089 */
1090 public void testRejectedExecutionExceptionOnShutdown() {
1091 ThreadPoolExecutor p =
1092 new CustomTPE(1,1,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(1));
1093 try { p.shutdown(); } catch (SecurityException ok) { return; }
1094 try {
1095 p.execute(new NoOpRunnable());
1096 shouldThrow();
1097 } catch (RejectedExecutionException success) {}
1098
1099 joinPool(p);
1100 }
1101
1102 /**
1103 * execute using CallerRunsPolicy drops task on shutdown
1104 */
1105 public void testCallerRunsOnShutdown() {
1106 RejectedExecutionHandler h = new CustomTPE.CallerRunsPolicy();
1107 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1108
1109 try { p.shutdown(); } catch (SecurityException ok) { return; }
1110 try {
1111 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1112 p.execute(r);
1113 assertFalse(r.done);
1114 } finally {
1115 joinPool(p);
1116 }
1117 }
1118
1119 /**
1120 * execute using DiscardPolicy drops task on shutdown
1121 */
1122 public void testDiscardOnShutdown() {
1123 RejectedExecutionHandler h = new CustomTPE.DiscardPolicy();
1124 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1125
1126 try { p.shutdown(); } catch (SecurityException ok) { return; }
1127 try {
1128 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1129 p.execute(r);
1130 assertFalse(r.done);
1131 } finally {
1132 joinPool(p);
1133 }
1134 }
1135
1136
1137 /**
1138 * execute using DiscardOldestPolicy drops task on shutdown
1139 */
1140 public void testDiscardOldestOnShutdown() {
1141 RejectedExecutionHandler h = new CustomTPE.DiscardOldestPolicy();
1142 ThreadPoolExecutor p = new CustomTPE(1,1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), h);
1143
1144 try { p.shutdown(); } catch (SecurityException ok) { return; }
1145 try {
1146 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1147 p.execute(r);
1148 assertFalse(r.done);
1149 } finally {
1150 joinPool(p);
1151 }
1152 }
1153
1154
1155 /**
1156 * execute(null) throws NPE
1157 */
1158 public void testExecuteNull() {
1159 ThreadPoolExecutor p = null;
1160 try {
1161 p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1162 p.execute(null);
1163 shouldThrow();
1164 } catch (NullPointerException success) {}
1165
1166 joinPool(p);
1167 }
1168
1169 /**
1170 * setCorePoolSize of negative value throws IllegalArgumentException
1171 */
1172 public void testCorePoolSizeIllegalArgumentException() {
1173 ThreadPoolExecutor p =
1174 new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1175 try {
1176 p.setCorePoolSize(-1);
1177 shouldThrow();
1178 } catch (IllegalArgumentException success) {
1179 } finally {
1180 try { p.shutdown(); } catch (SecurityException ok) { return; }
1181 }
1182 joinPool(p);
1183 }
1184
1185 /**
1186 * setMaximumPoolSize(int) throws IllegalArgumentException
1187 * if given a value less the core pool size
1188 */
1189 public void testMaximumPoolSizeIllegalArgumentException() {
1190 ThreadPoolExecutor p =
1191 new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1192 try {
1193 p.setMaximumPoolSize(1);
1194 shouldThrow();
1195 } catch (IllegalArgumentException success) {
1196 } finally {
1197 try { p.shutdown(); } catch (SecurityException ok) { return; }
1198 }
1199 joinPool(p);
1200 }
1201
1202 /**
1203 * setMaximumPoolSize throws IllegalArgumentException
1204 * if given a negative value
1205 */
1206 public void testMaximumPoolSizeIllegalArgumentException2() {
1207 ThreadPoolExecutor p =
1208 new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1209 try {
1210 p.setMaximumPoolSize(-1);
1211 shouldThrow();
1212 } catch (IllegalArgumentException success) {
1213 } finally {
1214 try { p.shutdown(); } catch (SecurityException ok) { return; }
1215 }
1216 joinPool(p);
1217 }
1218
1219
1220 /**
1221 * setKeepAliveTime throws IllegalArgumentException
1222 * when given a negative value
1223 */
1224 public void testKeepAliveTimeIllegalArgumentException() {
1225 ThreadPoolExecutor p =
1226 new CustomTPE(2,3,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1227
1228 try {
1229 p.setKeepAliveTime(-1,MILLISECONDS);
1230 shouldThrow();
1231 } catch (IllegalArgumentException success) {
1232 } finally {
1233 try { p.shutdown(); } catch (SecurityException ok) { return; }
1234 }
1235 joinPool(p);
1236 }
1237
1238 /**
1239 * terminated() is called on termination
1240 */
1241 public void testTerminated() {
1242 CustomTPE p = new CustomTPE();
1243 try { p.shutdown(); } catch (SecurityException ok) { return; }
1244 assertTrue(p.terminatedCalled);
1245 joinPool(p);
1246 }
1247
1248 /**
1249 * beforeExecute and afterExecute are called when executing task
1250 */
1251 public void testBeforeAfter() throws InterruptedException {
1252 CustomTPE p = new CustomTPE();
1253 try {
1254 TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1255 p.execute(r);
1256 Thread.sleep(SHORT_DELAY_MS);
1257 assertTrue(r.done);
1258 assertTrue(p.beforeCalled);
1259 assertTrue(p.afterCalled);
1260 try { p.shutdown(); } catch (SecurityException ok) { return; }
1261 } finally {
1262 joinPool(p);
1263 }
1264 }
1265
1266 /**
1267 * completed submit of callable returns result
1268 */
1269 public void testSubmitCallable() throws Exception {
1270 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1271 try {
1272 Future<String> future = e.submit(new StringTask());
1273 String result = future.get();
1274 assertSame(TEST_STRING, result);
1275 } finally {
1276 joinPool(e);
1277 }
1278 }
1279
1280 /**
1281 * completed submit of runnable returns successfully
1282 */
1283 public void testSubmitRunnable() throws Exception {
1284 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1285 try {
1286 Future<?> future = e.submit(new NoOpRunnable());
1287 future.get();
1288 assertTrue(future.isDone());
1289 } finally {
1290 joinPool(e);
1291 }
1292 }
1293
1294 /**
1295 * completed submit of (runnable, result) returns result
1296 */
1297 public void testSubmitRunnable2() throws Exception {
1298 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1299 try {
1300 Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
1301 String result = future.get();
1302 assertSame(TEST_STRING, result);
1303 } finally {
1304 joinPool(e);
1305 }
1306 }
1307
1308
1309 /**
1310 * invokeAny(null) throws NPE
1311 */
1312 public void testInvokeAny1() throws Exception {
1313 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1314 try {
1315 e.invokeAny(null);
1316 shouldThrow();
1317 } catch (NullPointerException success) {
1318 } finally {
1319 joinPool(e);
1320 }
1321 }
1322
1323 /**
1324 * invokeAny(empty collection) throws IAE
1325 */
1326 public void testInvokeAny2() throws Exception {
1327 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1328 try {
1329 e.invokeAny(new ArrayList<Callable<String>>());
1330 shouldThrow();
1331 } catch (IllegalArgumentException success) {
1332 } finally {
1333 joinPool(e);
1334 }
1335 }
1336
1337 /**
1338 * invokeAny(c) throws NPE if c has null elements
1339 */
1340 public void testInvokeAny3() throws Exception {
1341 CountDownLatch latch = new CountDownLatch(1);
1342 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1343 List<Callable<String>> l = new ArrayList<Callable<String>>();
1344 l.add(latchAwaitingStringTask(latch));
1345 l.add(null);
1346 try {
1347 e.invokeAny(l);
1348 shouldThrow();
1349 } catch (NullPointerException success) {
1350 } finally {
1351 latch.countDown();
1352 joinPool(e);
1353 }
1354 }
1355
1356 /**
1357 * invokeAny(c) throws ExecutionException if no task completes
1358 */
1359 public void testInvokeAny4() throws Exception {
1360 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1361 List<Callable<String>> l = new ArrayList<Callable<String>>();
1362 l.add(new NPETask());
1363 try {
1364 e.invokeAny(l);
1365 shouldThrow();
1366 } catch (ExecutionException success) {
1367 assertTrue(success.getCause() instanceof NullPointerException);
1368 } finally {
1369 joinPool(e);
1370 }
1371 }
1372
1373 /**
1374 * invokeAny(c) returns result of some task
1375 */
1376 public void testInvokeAny5() throws Exception {
1377 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1378 try {
1379 List<Callable<String>> l = new ArrayList<Callable<String>>();
1380 l.add(new StringTask());
1381 l.add(new StringTask());
1382 String result = e.invokeAny(l);
1383 assertSame(TEST_STRING, result);
1384 } finally {
1385 joinPool(e);
1386 }
1387 }
1388
1389 /**
1390 * invokeAll(null) throws NPE
1391 */
1392 public void testInvokeAll1() throws Exception {
1393 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1394 try {
1395 e.invokeAll(null);
1396 shouldThrow();
1397 } catch (NullPointerException success) {
1398 } finally {
1399 joinPool(e);
1400 }
1401 }
1402
1403 /**
1404 * invokeAll(empty collection) returns empty collection
1405 */
1406 public void testInvokeAll2() throws Exception {
1407 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1408 try {
1409 List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1410 assertTrue(r.isEmpty());
1411 } finally {
1412 joinPool(e);
1413 }
1414 }
1415
1416 /**
1417 * invokeAll(c) throws NPE if c has null elements
1418 */
1419 public void testInvokeAll3() throws Exception {
1420 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1421 List<Callable<String>> l = new ArrayList<Callable<String>>();
1422 l.add(new StringTask());
1423 l.add(null);
1424 try {
1425 e.invokeAll(l);
1426 shouldThrow();
1427 } catch (NullPointerException success) {
1428 } finally {
1429 joinPool(e);
1430 }
1431 }
1432
1433 /**
1434 * get of element of invokeAll(c) throws exception on failed task
1435 */
1436 public void testInvokeAll4() throws Exception {
1437 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1438 List<Callable<String>> l = new ArrayList<Callable<String>>();
1439 l.add(new NPETask());
1440 List<Future<String>> futures = e.invokeAll(l);
1441 assertEquals(1, futures.size());
1442 try {
1443 futures.get(0).get();
1444 shouldThrow();
1445 } catch (ExecutionException success) {
1446 assertTrue(success.getCause() instanceof NullPointerException);
1447 } finally {
1448 joinPool(e);
1449 }
1450 }
1451
1452 /**
1453 * invokeAll(c) returns results of all completed tasks
1454 */
1455 public void testInvokeAll5() throws Exception {
1456 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1457 try {
1458 List<Callable<String>> l = new ArrayList<Callable<String>>();
1459 l.add(new StringTask());
1460 l.add(new StringTask());
1461 List<Future<String>> futures = e.invokeAll(l);
1462 assertEquals(2, futures.size());
1463 for (Future<String> future : futures)
1464 assertSame(TEST_STRING, future.get());
1465 } finally {
1466 joinPool(e);
1467 }
1468 }
1469
1470
1471
1472 /**
1473 * timed invokeAny(null) throws NPE
1474 */
1475 public void testTimedInvokeAny1() throws Exception {
1476 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1477 try {
1478 e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1479 shouldThrow();
1480 } catch (NullPointerException success) {
1481 } finally {
1482 joinPool(e);
1483 }
1484 }
1485
1486 /**
1487 * timed invokeAny(,,null) throws NPE
1488 */
1489 public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1490 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1491 List<Callable<String>> l = new ArrayList<Callable<String>>();
1492 l.add(new StringTask());
1493 try {
1494 e.invokeAny(l, MEDIUM_DELAY_MS, null);
1495 shouldThrow();
1496 } catch (NullPointerException success) {
1497 } finally {
1498 joinPool(e);
1499 }
1500 }
1501
1502 /**
1503 * timed invokeAny(empty collection) throws IAE
1504 */
1505 public void testTimedInvokeAny2() throws Exception {
1506 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1507 try {
1508 e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1509 shouldThrow();
1510 } catch (IllegalArgumentException success) {
1511 } finally {
1512 joinPool(e);
1513 }
1514 }
1515
1516 /**
1517 * timed invokeAny(c) throws NPE if c has null elements
1518 */
1519 public void testTimedInvokeAny3() throws Exception {
1520 CountDownLatch latch = new CountDownLatch(1);
1521 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1522 List<Callable<String>> l = new ArrayList<Callable<String>>();
1523 l.add(latchAwaitingStringTask(latch));
1524 l.add(null);
1525 try {
1526 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1527 shouldThrow();
1528 } catch (NullPointerException success) {
1529 } finally {
1530 latch.countDown();
1531 joinPool(e);
1532 }
1533 }
1534
1535 /**
1536 * timed invokeAny(c) throws ExecutionException if no task completes
1537 */
1538 public void testTimedInvokeAny4() throws Exception {
1539 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1540 List<Callable<String>> l = new ArrayList<Callable<String>>();
1541 l.add(new NPETask());
1542 try {
1543 e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1544 shouldThrow();
1545 } catch (ExecutionException success) {
1546 assertTrue(success.getCause() instanceof NullPointerException);
1547 } finally {
1548 joinPool(e);
1549 }
1550 }
1551
1552 /**
1553 * timed invokeAny(c) returns result of some task
1554 */
1555 public void testTimedInvokeAny5() throws Exception {
1556 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1557 try {
1558 List<Callable<String>> l = new ArrayList<Callable<String>>();
1559 l.add(new StringTask());
1560 l.add(new StringTask());
1561 String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1562 assertSame(TEST_STRING, result);
1563 } finally {
1564 joinPool(e);
1565 }
1566 }
1567
1568 /**
1569 * timed invokeAll(null) throws NPE
1570 */
1571 public void testTimedInvokeAll1() throws Exception {
1572 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1573 try {
1574 e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1575 shouldThrow();
1576 } catch (NullPointerException success) {
1577 } finally {
1578 joinPool(e);
1579 }
1580 }
1581
1582 /**
1583 * timed invokeAll(,,null) throws NPE
1584 */
1585 public void testTimedInvokeAllNullTimeUnit() throws Exception {
1586 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1587 List<Callable<String>> l = new ArrayList<Callable<String>>();
1588 l.add(new StringTask());
1589 try {
1590 e.invokeAll(l, MEDIUM_DELAY_MS, null);
1591 shouldThrow();
1592 } catch (NullPointerException success) {
1593 } finally {
1594 joinPool(e);
1595 }
1596 }
1597
1598 /**
1599 * timed invokeAll(empty collection) returns empty collection
1600 */
1601 public void testTimedInvokeAll2() throws Exception {
1602 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1603 try {
1604 List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1605 assertTrue(r.isEmpty());
1606 } finally {
1607 joinPool(e);
1608 }
1609 }
1610
1611 /**
1612 * timed invokeAll(c) throws NPE if c has null elements
1613 */
1614 public void testTimedInvokeAll3() throws Exception {
1615 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1616 List<Callable<String>> l = new ArrayList<Callable<String>>();
1617 l.add(new StringTask());
1618 l.add(null);
1619 try {
1620 e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1621 shouldThrow();
1622 } catch (NullPointerException success) {
1623 } finally {
1624 joinPool(e);
1625 }
1626 }
1627
1628 /**
1629 * get of element of invokeAll(c) throws exception on failed task
1630 */
1631 public void testTimedInvokeAll4() throws Exception {
1632 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1633 List<Callable<String>> l = new ArrayList<Callable<String>>();
1634 l.add(new NPETask());
1635 List<Future<String>> futures =
1636 e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1637 assertEquals(1, futures.size());
1638 try {
1639 futures.get(0).get();
1640 shouldThrow();
1641 } catch (ExecutionException success) {
1642 assertTrue(success.getCause() instanceof NullPointerException);
1643 } finally {
1644 joinPool(e);
1645 }
1646 }
1647
1648 /**
1649 * timed invokeAll(c) returns results of all completed tasks
1650 */
1651 public void testTimedInvokeAll5() throws Exception {
1652 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1653 try {
1654 List<Callable<String>> l = new ArrayList<Callable<String>>();
1655 l.add(new StringTask());
1656 l.add(new StringTask());
1657 List<Future<String>> futures =
1658 e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1659 assertEquals(2, futures.size());
1660 for (Future<String> future : futures)
1661 assertSame(TEST_STRING, future.get());
1662 } finally {
1663 joinPool(e);
1664 }
1665 }
1666
1667 /**
1668 * timed invokeAll(c) cancels tasks not completed by timeout
1669 */
1670 public void testTimedInvokeAll6() throws Exception {
1671 ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1672 try {
1673 List<Callable<String>> l = new ArrayList<Callable<String>>();
1674 l.add(new StringTask());
1675 l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1676 l.add(new StringTask());
1677 List<Future<String>> futures =
1678 e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1679 assertEquals(3, futures.size());
1680 Iterator<Future<String>> it = futures.iterator();
1681 Future<String> f1 = it.next();
1682 Future<String> f2 = it.next();
1683 Future<String> f3 = it.next();
1684 assertTrue(f1.isDone());
1685 assertTrue(f2.isDone());
1686 assertTrue(f3.isDone());
1687 assertFalse(f1.isCancelled());
1688 assertTrue(f2.isCancelled());
1689 } finally {
1690 joinPool(e);
1691 }
1692 }
1693
1694 /**
1695 * Execution continues if there is at least one thread even if
1696 * thread factory fails to create more
1697 */
1698 public void testFailingThreadFactory() throws InterruptedException {
1699 final ExecutorService e =
1700 new CustomTPE(100, 100,
1701 LONG_DELAY_MS, MILLISECONDS,
1702 new LinkedBlockingQueue<Runnable>(),
1703 new FailingThreadFactory());
1704 try {
1705 final int TASKS = 100;
1706 final CountDownLatch done = new CountDownLatch(TASKS);
1707 for (int k = 0; k < TASKS; ++k)
1708 e.execute(new CheckedRunnable() {
1709 public void realRun() {
1710 done.countDown();
1711 }});
1712 assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1713 } finally {
1714 joinPool(e);
1715 }
1716 }
1717
1718 /**
1719 * allowsCoreThreadTimeOut is by default false.
1720 */
1721 public void testAllowsCoreThreadTimeOut() {
1722 ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1723 assertFalse(p.allowsCoreThreadTimeOut());
1724 joinPool(p);
1725 }
1726
1727 /**
1728 * allowCoreThreadTimeOut(true) causes idle threads to time out
1729 */
1730 public void testAllowCoreThreadTimeOut_true() throws Exception {
1731 final ThreadPoolExecutor p =
1732 new CustomTPE(2, 10,
1733 SHORT_DELAY_MS, MILLISECONDS,
1734 new ArrayBlockingQueue<Runnable>(10));
1735 final CountDownLatch threadStarted = new CountDownLatch(1);
1736 try {
1737 p.allowCoreThreadTimeOut(true);
1738 p.execute(new CheckedRunnable() {
1739 public void realRun() throws InterruptedException {
1740 threadStarted.countDown();
1741 assertEquals(1, p.getPoolSize());
1742 }});
1743 assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
1744 for (int i = 0; i < (MEDIUM_DELAY_MS/10); i++) {
1745 if (p.getPoolSize() == 0)
1746 break;
1747 Thread.sleep(10);
1748 }
1749 assertEquals(0, p.getPoolSize());
1750 } finally {
1751 joinPool(p);
1752 }
1753 }
1754
1755 /**
1756 * allowCoreThreadTimeOut(false) causes idle threads not to time out
1757 */
1758 public void testAllowCoreThreadTimeOut_false() throws Exception {
1759 final ThreadPoolExecutor p =
1760 new CustomTPE(2, 10,
1761 SHORT_DELAY_MS, MILLISECONDS,
1762 new ArrayBlockingQueue<Runnable>(10));
1763 final CountDownLatch threadStarted = new CountDownLatch(1);
1764 try {
1765 p.allowCoreThreadTimeOut(false);
1766 p.execute(new CheckedRunnable() {
1767 public void realRun() throws InterruptedException {
1768 threadStarted.countDown();
1769 assertTrue(p.getPoolSize() >= 1);
1770 }});
1771 Thread.sleep(SMALL_DELAY_MS);
1772 assertTrue(p.getPoolSize() >= 1);
1773 } finally {
1774 joinPool(p);
1775 }
1776 }
1777
1778 }