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