ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorTest.java
Revision: 1.72
Committed: Sun Oct 4 01:52:43 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.71: +5 -6 lines
Log Message:
improve testSetThreadFactoryNull

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