ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorTest.java
Revision: 1.119
Committed: Mon May 29 22:44:27 2017 UTC (6 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.118: +21 -15 lines
Log Message:
more timeout handling rework; remove most uses of MEDIUM_DELAY_MS; randomize timeouts and TimeUnits; write out IAE and ISE

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