ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java
Revision: 1.29
Committed: Fri May 27 19:35:24 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.28: +12 -28 lines
Log Message:
Improve testAllowCoreThreadTimeOut tests

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