ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorTest.java
Revision: 1.91
Committed: Sun Oct 4 03:27:46 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.90: +17 -16 lines
Log Message:
improve testSaturatedExecute3

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