ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java
Revision: 1.25
Committed: Tue Mar 15 19:47:07 2011 UTC (13 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.24: +1 -1 lines
Log Message:
Update Creative Commons license URL in legal notices

File Contents

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