ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ThreadPoolExecutorTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ThreadPoolExecutorTest.java (file contents):
Revision 1.76 by jsr166, Sun Oct 4 02:04:56 2015 UTC vs.
Revision 1.123 by jsr166, Sat Jul 15 23:15:21 2017 UTC

# Line 11 | Line 11 | import static java.util.concurrent.TimeU
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;
# Line 18 | Line 20 | import java.util.concurrent.Callable;
20   import java.util.concurrent.CancellationException;
21   import java.util.concurrent.CountDownLatch;
22   import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.Executors;
23   import java.util.concurrent.ExecutorService;
24   import java.util.concurrent.Future;
25   import java.util.concurrent.FutureTask;
# Line 27 | Line 28 | import java.util.concurrent.RejectedExec
28   import java.util.concurrent.RejectedExecutionHandler;
29   import java.util.concurrent.SynchronousQueue;
30   import java.util.concurrent.ThreadFactory;
31 + import java.util.concurrent.ThreadLocalRandom;
32   import java.util.concurrent.ThreadPoolExecutor;
33 < import java.util.concurrent.TimeUnit;
33 > import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
34 > import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
35 > import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
36 > import java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;
37   import java.util.concurrent.atomic.AtomicInteger;
38 + import java.util.concurrent.atomic.AtomicReference;
39  
40   import junit.framework.Test;
41   import junit.framework.TestSuite;
# Line 87 | Line 93 | public class ThreadPoolExecutorTest exte
93              new ThreadPoolExecutor(1, 1,
94                                     LONG_DELAY_MS, MILLISECONDS,
95                                     new ArrayBlockingQueue<Runnable>(10));
96 <        final CountDownLatch done = new CountDownLatch(1);
97 <        final Runnable task = new CheckedRunnable() {
98 <            public void realRun() {
99 <                done.countDown();
94 <            }};
95 <        try {
96 >        try (PoolCleaner cleaner = cleaner(p)) {
97 >            final CountDownLatch done = new CountDownLatch(1);
98 >            final Runnable task = new CheckedRunnable() {
99 >                public void realRun() { done.countDown(); }};
100              p.execute(task);
101 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
98 <        } finally {
99 <            joinPool(p);
101 >            await(done);
102          }
103      }
104  
# Line 105 | Line 107 | public class ThreadPoolExecutorTest exte
107       * thread becomes active
108       */
109      public void testGetActiveCount() throws InterruptedException {
110 +        final CountDownLatch done = new CountDownLatch(1);
111          final ThreadPoolExecutor p =
112              new ThreadPoolExecutor(2, 2,
113                                     LONG_DELAY_MS, MILLISECONDS,
114                                     new ArrayBlockingQueue<Runnable>(10));
115 <        final CountDownLatch threadStarted = new CountDownLatch(1);
116 <        final CountDownLatch done = new CountDownLatch(1);
114 <        try {
115 >        try (PoolCleaner cleaner = cleaner(p, done)) {
116 >            final CountDownLatch threadStarted = new CountDownLatch(1);
117              assertEquals(0, p.getActiveCount());
118              p.execute(new CheckedRunnable() {
119                  public void realRun() throws InterruptedException {
120                      threadStarted.countDown();
121                      assertEquals(1, p.getActiveCount());
122 <                    done.await();
122 >                    await(done);
123                  }});
124 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
124 >            await(threadStarted);
125              assertEquals(1, p.getActiveCount());
124        } finally {
125            done.countDown();
126            joinPool(p);
126          }
127      }
128  
# Line 193 | Line 192 | public class ThreadPoolExecutorTest exte
192                  public void realRun() throws InterruptedException {
193                      threadStarted.countDown();
194                      assertEquals(0, p.getCompletedTaskCount());
195 <                    threadProceed.await();
195 >                    await(threadProceed);
196                      threadDone.countDown();
197                  }});
198              await(threadStarted);
199              assertEquals(0, p.getCompletedTaskCount());
200              threadProceed.countDown();
201 <            threadDone.await();
201 >            await(threadDone);
202              long startTime = System.nanoTime();
203              while (p.getCompletedTaskCount() != 1) {
204                  if (millisElapsedSince(startTime) > LONG_DELAY_MS)
# Line 283 | Line 282 | public class ThreadPoolExecutorTest exte
282      }
283  
284      /**
285 +     * The default rejected execution handler is AbortPolicy.
286 +     */
287 +    public void testDefaultRejectedExecutionHandler() {
288 +        final ThreadPoolExecutor p =
289 +            new ThreadPoolExecutor(1, 2,
290 +                                   LONG_DELAY_MS, MILLISECONDS,
291 +                                   new ArrayBlockingQueue<Runnable>(10));
292 +        try (PoolCleaner cleaner = cleaner(p)) {
293 +            assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
294 +        }
295 +    }
296 +
297 +    /**
298       * getRejectedExecutionHandler returns handler in constructor if not set
299       */
300      public void testGetRejectedExecutionHandler() {
# Line 335 | Line 347 | public class ThreadPoolExecutorTest exte
347       */
348      public void testGetLargestPoolSize() throws InterruptedException {
349          final int THREADS = 3;
350 +        final CountDownLatch done = new CountDownLatch(1);
351          final ThreadPoolExecutor p =
352              new ThreadPoolExecutor(THREADS, THREADS,
353                                     LONG_DELAY_MS, MILLISECONDS,
354                                     new ArrayBlockingQueue<Runnable>(10));
355 <        try (PoolCleaner cleaner = cleaner(p)) {
343 <            final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
344 <            final CountDownLatch done = new CountDownLatch(1);
355 >        try (PoolCleaner cleaner = cleaner(p, done)) {
356              assertEquals(0, p.getLargestPoolSize());
357 +            final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
358              for (int i = 0; i < THREADS; i++)
359                  p.execute(new CheckedRunnable() {
360                      public void realRun() throws InterruptedException {
361                          threadsStarted.countDown();
362 <                        done.await();
362 >                        await(done);
363                          assertEquals(THREADS, p.getLargestPoolSize());
364                      }});
365 <            assertTrue(threadsStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
365 >            await(threadsStarted);
366              assertEquals(THREADS, p.getLargestPoolSize());
355            done.countDown();   // release pool
367          }
368          assertEquals(THREADS, p.getLargestPoolSize());
369      }
# Line 366 | Line 377 | public class ThreadPoolExecutorTest exte
377              new ThreadPoolExecutor(2, 3,
378                                     LONG_DELAY_MS, MILLISECONDS,
379                                     new ArrayBlockingQueue<Runnable>(10));
380 <        assertEquals(3, p.getMaximumPoolSize());
381 <        joinPool(p);
380 >        try (PoolCleaner cleaner = cleaner(p)) {
381 >            assertEquals(3, p.getMaximumPoolSize());
382 >            p.setMaximumPoolSize(5);
383 >            assertEquals(5, p.getMaximumPoolSize());
384 >            p.setMaximumPoolSize(4);
385 >            assertEquals(4, p.getMaximumPoolSize());
386 >        }
387      }
388  
389      /**
# Line 375 | Line 391 | public class ThreadPoolExecutorTest exte
391       * become active
392       */
393      public void testGetPoolSize() throws InterruptedException {
394 +        final CountDownLatch done = new CountDownLatch(1);
395          final ThreadPoolExecutor p =
396              new ThreadPoolExecutor(1, 1,
397                                     LONG_DELAY_MS, MILLISECONDS,
398                                     new ArrayBlockingQueue<Runnable>(10));
399 <        final CountDownLatch threadStarted = new CountDownLatch(1);
383 <        final CountDownLatch done = new CountDownLatch(1);
384 <        try {
399 >        try (PoolCleaner cleaner = cleaner(p, done)) {
400              assertEquals(0, p.getPoolSize());
401 +            final CountDownLatch threadStarted = new CountDownLatch(1);
402              p.execute(new CheckedRunnable() {
403                  public void realRun() throws InterruptedException {
404                      threadStarted.countDown();
405                      assertEquals(1, p.getPoolSize());
406 <                    done.await();
406 >                    await(done);
407                  }});
408 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
408 >            await(threadStarted);
409              assertEquals(1, p.getPoolSize());
394        } finally {
395            done.countDown();
396            joinPool(p);
410          }
411      }
412  
# Line 401 | Line 414 | public class ThreadPoolExecutorTest exte
414       * getTaskCount increases, but doesn't overestimate, when tasks submitted
415       */
416      public void testGetTaskCount() throws InterruptedException {
417 +        final int TASKS = 3;
418 +        final CountDownLatch done = new CountDownLatch(1);
419          final ThreadPoolExecutor p =
420              new ThreadPoolExecutor(1, 1,
421                                     LONG_DELAY_MS, MILLISECONDS,
422                                     new ArrayBlockingQueue<Runnable>(10));
423 <        final CountDownLatch threadStarted = new CountDownLatch(1);
424 <        final CountDownLatch done = new CountDownLatch(1);
410 <        try {
423 >        try (PoolCleaner cleaner = cleaner(p, done)) {
424 >            final CountDownLatch threadStarted = new CountDownLatch(1);
425              assertEquals(0, p.getTaskCount());
426 +            assertEquals(0, p.getCompletedTaskCount());
427              p.execute(new CheckedRunnable() {
428                  public void realRun() throws InterruptedException {
429                      threadStarted.countDown();
430 <                    assertEquals(1, p.getTaskCount());
416 <                    done.await();
430 >                    await(done);
431                  }});
432 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
432 >            await(threadStarted);
433              assertEquals(1, p.getTaskCount());
434 <        } finally {
435 <            done.countDown();
436 <            joinPool(p);
434 >            assertEquals(0, p.getCompletedTaskCount());
435 >            for (int i = 0; i < TASKS; i++) {
436 >                assertEquals(1 + i, p.getTaskCount());
437 >                p.execute(new CheckedRunnable() {
438 >                    public void realRun() throws InterruptedException {
439 >                        threadStarted.countDown();
440 >                        assertEquals(1 + TASKS, p.getTaskCount());
441 >                        await(done);
442 >                    }});
443 >            }
444 >            assertEquals(1 + TASKS, p.getTaskCount());
445 >            assertEquals(0, p.getCompletedTaskCount());
446          }
447 +        assertEquals(1 + TASKS, p.getTaskCount());
448 +        assertEquals(1 + TASKS, p.getCompletedTaskCount());
449      }
450  
451      /**
# Line 431 | Line 456 | public class ThreadPoolExecutorTest exte
456              new ThreadPoolExecutor(1, 1,
457                                     LONG_DELAY_MS, MILLISECONDS,
458                                     new ArrayBlockingQueue<Runnable>(10));
459 <        assertFalse(p.isShutdown());
460 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
461 <        assertTrue(p.isShutdown());
462 <        joinPool(p);
459 >        try (PoolCleaner cleaner = cleaner(p)) {
460 >            assertFalse(p.isShutdown());
461 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
462 >            assertTrue(p.isShutdown());
463 >        }
464      }
465  
466      /**
# Line 445 | Line 471 | public class ThreadPoolExecutorTest exte
471              new ThreadPoolExecutor(1, 1,
472                                     LONG_DELAY_MS, MILLISECONDS,
473                                     new ArrayBlockingQueue<Runnable>(10));
474 <        assertFalse(p.isTerminated());
475 <        assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
476 <        assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
477 <        assertFalse(p.awaitTermination(-1L, NANOSECONDS));
478 <        assertFalse(p.awaitTermination(-1L, MILLISECONDS));
479 <        assertFalse(p.awaitTermination(0L, NANOSECONDS));
480 <        assertFalse(p.awaitTermination(0L, MILLISECONDS));
481 <        long timeoutNanos = 999999L;
482 <        long startTime = System.nanoTime();
483 <        assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
484 <        assertTrue(System.nanoTime() - startTime >= timeoutNanos);
485 <        assertFalse(p.isTerminated());
486 <        startTime = System.nanoTime();
487 <        long timeoutMillis = timeoutMillis();
488 <        assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
489 <        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
490 <        assertFalse(p.isTerminated());
491 <        p.shutdown();
492 <        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
493 <        assertTrue(p.isTerminated());
474 >        try (PoolCleaner cleaner = cleaner(p)) {
475 >            assertFalse(p.isTerminated());
476 >            assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
477 >            assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
478 >            assertFalse(p.awaitTermination(-1L, NANOSECONDS));
479 >            assertFalse(p.awaitTermination(-1L, MILLISECONDS));
480 >            assertFalse(p.awaitTermination(randomExpiredTimeout(),
481 >                                           randomTimeUnit()));
482 >            long timeoutNanos = 999999L;
483 >            long startTime = System.nanoTime();
484 >            assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
485 >            assertTrue(System.nanoTime() - startTime >= timeoutNanos);
486 >            assertFalse(p.isTerminated());
487 >            startTime = System.nanoTime();
488 >            long timeoutMillis = timeoutMillis();
489 >            assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
490 >            assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
491 >            assertFalse(p.isTerminated());
492 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
493 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
494 >            assertTrue(p.isTerminated());
495 >        }
496      }
497  
498      /**
# Line 475 | Line 503 | public class ThreadPoolExecutorTest exte
503              new ThreadPoolExecutor(1, 1,
504                                     LONG_DELAY_MS, MILLISECONDS,
505                                     new ArrayBlockingQueue<Runnable>(10));
506 <        final CountDownLatch threadStarted = new CountDownLatch(1);
507 <        final CountDownLatch done = new CountDownLatch(1);
508 <        assertFalse(p.isTerminated());
509 <        try {
506 >        try (PoolCleaner cleaner = cleaner(p)) {
507 >            final CountDownLatch threadStarted = new CountDownLatch(1);
508 >            final CountDownLatch done = new CountDownLatch(1);
509 >            assertFalse(p.isTerminating());
510              p.execute(new CheckedRunnable() {
511                  public void realRun() throws InterruptedException {
512 <                    assertFalse(p.isTerminated());
512 >                    assertFalse(p.isTerminating());
513                      threadStarted.countDown();
514 <                    done.await();
514 >                    await(done);
515                  }});
516 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
516 >            await(threadStarted);
517              assertFalse(p.isTerminating());
518              done.countDown();
491        } finally {
519              try { p.shutdown(); } catch (SecurityException ok) { return; }
520 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
521 +            assertTrue(p.isTerminated());
522 +            assertFalse(p.isTerminating());
523          }
494        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
495        assertTrue(p.isTerminated());
524      }
525  
526      /**
# Line 503 | Line 531 | public class ThreadPoolExecutorTest exte
531              new ThreadPoolExecutor(1, 1,
532                                     LONG_DELAY_MS, MILLISECONDS,
533                                     new ArrayBlockingQueue<Runnable>(10));
534 <        final CountDownLatch threadStarted = new CountDownLatch(1);
535 <        final CountDownLatch done = new CountDownLatch(1);
536 <        try {
534 >        try (PoolCleaner cleaner = cleaner(p)) {
535 >            final CountDownLatch threadStarted = new CountDownLatch(1);
536 >            final CountDownLatch done = new CountDownLatch(1);
537              assertFalse(p.isTerminating());
538              p.execute(new CheckedRunnable() {
539                  public void realRun() throws InterruptedException {
540                      assertFalse(p.isTerminating());
541                      threadStarted.countDown();
542 <                    done.await();
542 >                    await(done);
543                  }});
544 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
544 >            await(threadStarted);
545              assertFalse(p.isTerminating());
546              done.countDown();
519        } finally {
547              try { p.shutdown(); } catch (SecurityException ok) { return; }
548 +            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
549 +            assertTrue(p.isTerminated());
550 +            assertFalse(p.isTerminating());
551          }
522        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
523        assertTrue(p.isTerminated());
524        assertFalse(p.isTerminating());
552      }
553  
554      /**
555       * getQueue returns the work queue, which contains queued tasks
556       */
557      public void testGetQueue() throws InterruptedException {
558 <        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
558 >        final CountDownLatch done = new CountDownLatch(1);
559 >        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
560          final ThreadPoolExecutor p =
561              new ThreadPoolExecutor(1, 1,
562                                     LONG_DELAY_MS, MILLISECONDS,
563                                     q);
564 <        final CountDownLatch threadStarted = new CountDownLatch(1);
565 <        final CountDownLatch done = new CountDownLatch(1);
538 <        try {
564 >        try (PoolCleaner cleaner = cleaner(p, done)) {
565 >            final CountDownLatch threadStarted = new CountDownLatch(1);
566              FutureTask[] tasks = new FutureTask[5];
567              for (int i = 0; i < tasks.length; i++) {
568                  Callable task = new CheckedCallable<Boolean>() {
569                      public Boolean realCall() throws InterruptedException {
570                          threadStarted.countDown();
571                          assertSame(q, p.getQueue());
572 <                        done.await();
572 >                        await(done);
573                          return Boolean.TRUE;
574                      }};
575                  tasks[i] = new FutureTask(task);
576                  p.execute(tasks[i]);
577              }
578 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
578 >            await(threadStarted);
579              assertSame(q, p.getQueue());
580              assertFalse(q.contains(tasks[0]));
581              assertTrue(q.contains(tasks[tasks.length - 1]));
582              assertEquals(tasks.length - 1, q.size());
556        } finally {
557            done.countDown();
558            joinPool(p);
583          }
584      }
585  
# Line 563 | Line 587 | public class ThreadPoolExecutorTest exte
587       * remove(task) removes queued task, and fails to remove active task
588       */
589      public void testRemove() throws InterruptedException {
590 <        BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
590 >        final CountDownLatch done = new CountDownLatch(1);
591 >        BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
592          final ThreadPoolExecutor p =
593              new ThreadPoolExecutor(1, 1,
594                                     LONG_DELAY_MS, MILLISECONDS,
595                                     q);
596 <        Runnable[] tasks = new Runnable[5];
597 <        final CountDownLatch threadStarted = new CountDownLatch(1);
598 <        final CountDownLatch done = new CountDownLatch(1);
574 <        try {
596 >        try (PoolCleaner cleaner = cleaner(p, done)) {
597 >            Runnable[] tasks = new Runnable[6];
598 >            final CountDownLatch threadStarted = new CountDownLatch(1);
599              for (int i = 0; i < tasks.length; i++) {
600                  tasks[i] = new CheckedRunnable() {
601                      public void realRun() throws InterruptedException {
602                          threadStarted.countDown();
603 <                        done.await();
603 >                        await(done);
604                      }};
605                  p.execute(tasks[i]);
606              }
607 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
607 >            await(threadStarted);
608              assertFalse(p.remove(tasks[0]));
609              assertTrue(q.contains(tasks[4]));
610              assertTrue(q.contains(tasks[3]));
# Line 590 | Line 614 | public class ThreadPoolExecutorTest exte
614              assertTrue(q.contains(tasks[3]));
615              assertTrue(p.remove(tasks[3]));
616              assertFalse(q.contains(tasks[3]));
593        } finally {
594            done.countDown();
595            joinPool(p);
617          }
618      }
619  
# Line 602 | Line 623 | public class ThreadPoolExecutorTest exte
623      public void testPurge() throws InterruptedException {
624          final CountDownLatch threadStarted = new CountDownLatch(1);
625          final CountDownLatch done = new CountDownLatch(1);
626 <        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
626 >        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
627          final ThreadPoolExecutor p =
628              new ThreadPoolExecutor(1, 1,
629                                     LONG_DELAY_MS, MILLISECONDS,
630                                     q);
631 <        FutureTask[] tasks = new FutureTask[5];
632 <        try {
631 >        try (PoolCleaner cleaner = cleaner(p, done)) {
632 >            FutureTask[] tasks = new FutureTask[5];
633              for (int i = 0; i < tasks.length; i++) {
634                  Callable task = new CheckedCallable<Boolean>() {
635                      public Boolean realCall() throws InterruptedException {
636                          threadStarted.countDown();
637 <                        done.await();
637 >                        await(done);
638                          return Boolean.TRUE;
639                      }};
640                  tasks[i] = new FutureTask(task);
641                  p.execute(tasks[i]);
642              }
643 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
643 >            await(threadStarted);
644              assertEquals(tasks.length, p.getTaskCount());
645              assertEquals(tasks.length - 1, q.size());
646              assertEquals(1L, p.getActiveCount());
# Line 632 | Line 653 | public class ThreadPoolExecutorTest exte
653              p.purge();         // Nothing to do
654              assertEquals(tasks.length - 3, q.size());
655              assertEquals(tasks.length - 2, p.getTaskCount());
635        } finally {
636            done.countDown();
637            joinPool(p);
656          }
657      }
658  
# Line 650 | Line 668 | public class ThreadPoolExecutorTest exte
668              new ThreadPoolExecutor(poolSize, poolSize,
669                                     LONG_DELAY_MS, MILLISECONDS,
670                                     new ArrayBlockingQueue<Runnable>(10));
671 <        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
671 >        final CountDownLatch threadsStarted = new CountDownLatch(poolSize);
672          Runnable waiter = new CheckedRunnable() { public void realRun() {
673              threadsStarted.countDown();
674              try {
# Line 660 | Line 678 | public class ThreadPoolExecutorTest exte
678          }};
679          for (int i = 0; i < count; i++)
680              p.execute(waiter);
681 <        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
681 >        await(threadsStarted);
682          assertEquals(poolSize, p.getActiveCount());
683          assertEquals(0, p.getCompletedTaskCount());
684          final List<Runnable> queuedTasks;
# Line 1022 | Line 1040 | public class ThreadPoolExecutorTest exte
1040       * get of submitted callable throws InterruptedException if interrupted
1041       */
1042      public void testInterruptedSubmit() throws InterruptedException {
1043 +        final CountDownLatch done = new CountDownLatch(1);
1044          final ThreadPoolExecutor p =
1045              new ThreadPoolExecutor(1, 1,
1046                                     60, SECONDS,
1047                                     new ArrayBlockingQueue<Runnable>(10));
1048  
1049 <        final CountDownLatch threadStarted = new CountDownLatch(1);
1050 <        final CountDownLatch done = new CountDownLatch(1);
1032 <        try {
1049 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1050 >            final CountDownLatch threadStarted = new CountDownLatch(1);
1051              Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1052                  public void realRun() throws Exception {
1053                      Callable task = new CheckedCallable<Boolean>() {
1054                          public Boolean realCall() throws InterruptedException {
1055                              threadStarted.countDown();
1056 <                            done.await();
1056 >                            await(done);
1057                              return Boolean.TRUE;
1058                          }};
1059                      p.submit(task).get();
1060                  }});
1061  
1062 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
1062 >            await(threadStarted);
1063              t.interrupt();
1064 <            awaitTermination(t, MEDIUM_DELAY_MS);
1047 <        } finally {
1048 <            done.countDown();
1049 <            joinPool(p);
1064 >            awaitTermination(t);
1065          }
1066      }
1067  
1068      /**
1069 <     * execute throws RejectedExecutionException if saturated.
1069 >     * Submitted tasks are rejected when saturated.
1070       */
1071 <    public void testSaturatedExecute() {
1072 <        ThreadPoolExecutor p =
1073 <            new ThreadPoolExecutor(1, 1,
1059 <                                   LONG_DELAY_MS, MILLISECONDS,
1060 <                                   new ArrayBlockingQueue<Runnable>(1));
1071 >    @SuppressWarnings("FutureReturnValueIgnored")
1072 >    public void testSubmittedTasksRejectedWhenSaturated() {
1073 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1074          final CountDownLatch done = new CountDownLatch(1);
1075 <        try {
1076 <            Runnable task = new CheckedRunnable() {
1077 <                public void realRun() throws InterruptedException {
1078 <                    done.await();
1079 <                }};
1080 <            for (int i = 0; i < 2; ++i)
1081 <                p.execute(task);
1082 <            for (int i = 0; i < 2; ++i) {
1075 >        final Runnable r = awaiter(done);
1076 >        final Callable<Boolean> c = new CheckedCallable() {
1077 >            public Boolean realCall() throws InterruptedException {
1078 >                await(done);
1079 >                return Boolean.TRUE;
1080 >            }};
1081 >        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1082 >            1, 1, 1, SECONDS, new ArrayBlockingQueue<Runnable>(1));
1083 >
1084 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1085 >            // saturate
1086 >            for (int i = saturatedSize(p); i--> 0; ) {
1087 >                switch (rnd.nextInt(3)) {
1088 >                case 0: p.execute(r); break;
1089 >                case 1: assertFalse(p.submit(r).isDone()); break;
1090 >                case 2: assertFalse(p.submit(c).isDone()); break;
1091 >                }
1092 >            }
1093 >
1094 >            // check default handler
1095 >            assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
1096 >            for (int i = 2; i--> 0; ) {
1097                  try {
1098 <                    p.execute(task);
1098 >                    p.execute(r);
1099                      shouldThrow();
1100                  } catch (RejectedExecutionException success) {}
1074                assertTrue(p.getTaskCount() <= 2);
1075            }
1076        } finally {
1077            done.countDown();
1078            joinPool(p);
1079        }
1080    }
1081
1082    /**
1083     * submit(runnable) throws RejectedExecutionException if saturated.
1084     */
1085    public void testSaturatedSubmitRunnable() {
1086        ThreadPoolExecutor p =
1087            new ThreadPoolExecutor(1, 1,
1088                                   LONG_DELAY_MS, MILLISECONDS,
1089                                   new ArrayBlockingQueue<Runnable>(1));
1090        final CountDownLatch done = new CountDownLatch(1);
1091        try {
1092            Runnable task = new CheckedRunnable() {
1093                public void realRun() throws InterruptedException {
1094                    done.await();
1095                }};
1096            for (int i = 0; i < 2; ++i)
1097                p.submit(task);
1098            for (int i = 0; i < 2; ++i) {
1101                  try {
1102 <                    p.execute(task);
1102 >                    p.submit(r);
1103                      shouldThrow();
1104                  } catch (RejectedExecutionException success) {}
1103                assertTrue(p.getTaskCount() <= 2);
1104            }
1105        } finally {
1106            done.countDown();
1107            joinPool(p);
1108        }
1109    }
1110
1111    /**
1112     * submit(callable) throws RejectedExecutionException if saturated.
1113     */
1114    public void testSaturatedSubmitCallable() {
1115        ThreadPoolExecutor p =
1116            new ThreadPoolExecutor(1, 1,
1117                                   LONG_DELAY_MS, MILLISECONDS,
1118                                   new ArrayBlockingQueue<Runnable>(1));
1119        final CountDownLatch done = new CountDownLatch(1);
1120        try {
1121            Runnable task = new CheckedRunnable() {
1122                public void realRun() throws InterruptedException {
1123                    done.await();
1124                }};
1125            for (int i = 0; i < 2; ++i)
1126                p.submit(Executors.callable(task));
1127            for (int i = 0; i < 2; ++i) {
1105                  try {
1106 <                    p.execute(task);
1106 >                    p.submit(c);
1107                      shouldThrow();
1108                  } catch (RejectedExecutionException success) {}
1132                assertTrue(p.getTaskCount() <= 2);
1109              }
1110 <        } finally {
1111 <            done.countDown();
1112 <            joinPool(p);
1110 >
1111 >            // check CallerRunsPolicy runs task in caller thread
1112 >            {
1113 >                RejectedExecutionHandler handler = new CallerRunsPolicy();
1114 >                p.setRejectedExecutionHandler(handler);
1115 >                assertSame(handler, p.getRejectedExecutionHandler());
1116 >                final AtomicReference<Thread> thread = new AtomicReference<>();
1117 >                p.execute(new Runnable() { public void run() {
1118 >                    thread.set(Thread.currentThread()); }});
1119 >                assertSame(Thread.currentThread(), thread.get());
1120 >            }
1121 >
1122 >            // check DiscardPolicy does nothing
1123 >            {
1124 >                RejectedExecutionHandler handler = new DiscardPolicy();
1125 >                p.setRejectedExecutionHandler(handler);
1126 >                assertSame(handler, p.getRejectedExecutionHandler());
1127 >                final AtomicReference<Thread> thread = new AtomicReference<>();
1128 >                p.execute(new Runnable() { public void run() {
1129 >                    thread.set(Thread.currentThread()); }});
1130 >                assertNull(thread.get());
1131 >            }
1132 >
1133 >            class Recorder implements RejectedExecutionHandler {
1134 >                public volatile Runnable r = null;
1135 >                public volatile ThreadPoolExecutor p = null;
1136 >                public void reset() { r = null; p = null; }
1137 >                public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1138 >                    assertNull(this.r);
1139 >                    assertNull(this.p);
1140 >                    this.r = r;
1141 >                    this.p = p;
1142 >                }
1143 >            }
1144 >
1145 >            // check custom handler is invoked exactly once per task
1146 >            Recorder recorder = new Recorder();
1147 >            p.setRejectedExecutionHandler(recorder);
1148 >            assertSame(recorder, p.getRejectedExecutionHandler());
1149 >            for (int i = 2; i--> 0; ) {
1150 >                recorder.reset();
1151 >                p.execute(r);
1152 >                assertSame(r, recorder.r);
1153 >                assertSame(p, recorder.p);
1154 >
1155 >                recorder.reset();
1156 >                assertFalse(p.submit(r).isDone());
1157 >                assertTrue(recorder.r instanceof FutureTask);
1158 >                assertSame(p, recorder.p);
1159 >
1160 >                recorder.reset();
1161 >                assertFalse(p.submit(c).isDone());
1162 >                assertTrue(recorder.r instanceof FutureTask);
1163 >                assertSame(p, recorder.p);
1164 >            }
1165 >
1166 >            // check that pool was not perturbed by handlers
1167 >            assertEquals(2, p.getTaskCount());
1168 >            assertEquals(0, p.getCompletedTaskCount());
1169 >            assertEquals(0, p.getQueue().remainingCapacity());
1170          }
1171 +        assertEquals(saturatedSize(p), p.getCompletedTaskCount());
1172      }
1173  
1174      /**
1175       * executor using CallerRunsPolicy runs task if saturated.
1176       */
1177      public void testSaturatedExecute2() {
1178 <        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1179 <        final ThreadPoolExecutor p =
1180 <            new ThreadPoolExecutor(1, 1,
1181 <                                   LONG_DELAY_MS,
1182 <                                   MILLISECONDS,
1183 <                                   new ArrayBlockingQueue<Runnable>(1),
1184 <                                   h);
1185 <        try {
1186 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1187 <            for (int i = 0; i < tasks.length; ++i)
1188 <                tasks[i] = new TrackedNoOpRunnable();
1189 <            TrackedLongRunnable mr = new TrackedLongRunnable();
1190 <            p.execute(mr);
1191 <            for (int i = 0; i < tasks.length; ++i)
1158 <                p.execute(tasks[i]);
1159 <            for (int i = 1; i < tasks.length; ++i)
1178 >        final RejectedExecutionHandler handler = new CallerRunsPolicy();
1179 >        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1180 >            1, 1, LONG_DELAY_MS, SECONDS, new ArrayBlockingQueue<Runnable>(1),
1181 >            handler);
1182 >        assertSame(handler, p.getRejectedExecutionHandler());
1183 >        final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1184 >        final CountDownLatch done = new CountDownLatch(1);
1185 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1186 >            p.execute(awaiter(done));
1187 >
1188 >            for (int i = 0; i < tasks.length; i++)
1189 >                p.execute(tasks[i] = new TrackedNoOpRunnable());
1190 >
1191 >            for (int i = 1; i < tasks.length; i++)
1192                  assertTrue(tasks[i].done);
1193 <            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1162 <        } finally {
1163 <            joinPool(p);
1193 >            assertFalse(tasks[0].done); // waiting in queue
1194          }
1195 +        for (TrackedNoOpRunnable task : tasks)
1196 +            assertTrue(task.done);
1197      }
1198  
1199      /**
1200       * executor using DiscardPolicy drops task if saturated.
1201       */
1202      public void testSaturatedExecute3() {
1203 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1204 <        final ThreadPoolExecutor p =
1205 <            new ThreadPoolExecutor(1, 1,
1206 <                                   LONG_DELAY_MS, MILLISECONDS,
1207 <                                   new ArrayBlockingQueue<Runnable>(1),
1208 <                                   h);
1209 <        try {
1210 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1211 <            for (int i = 0; i < tasks.length; ++i)
1212 <                tasks[i] = new TrackedNoOpRunnable();
1213 <            p.execute(new TrackedLongRunnable());
1214 <            for (TrackedNoOpRunnable task : tasks)
1215 <                p.execute(task);
1216 <            for (TrackedNoOpRunnable task : tasks)
1217 <                assertFalse(task.done);
1186 <            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1187 <        } finally {
1188 <            joinPool(p);
1203 >        final RejectedExecutionHandler handler = new DiscardPolicy();
1204 >        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1205 >            1, 1, LONG_DELAY_MS, SECONDS, new ArrayBlockingQueue<Runnable>(1),
1206 >            handler);
1207 >        assertSame(handler, p.getRejectedExecutionHandler());
1208 >        final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1209 >        final CountDownLatch done = new CountDownLatch(1);
1210 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1211 >            p.execute(awaiter(done));
1212 >
1213 >            for (int i = 0; i < tasks.length; i++)
1214 >                p.execute(tasks[i] = new TrackedNoOpRunnable());
1215 >
1216 >            for (int i = 1; i < tasks.length; i++)
1217 >                assertFalse(tasks[i].done);
1218          }
1219 +        for (int i = 1; i < tasks.length; i++)
1220 +            assertFalse(tasks[i].done);
1221 +        assertTrue(tasks[0].done); // was waiting in queue
1222      }
1223  
1224      /**
1225       * executor using DiscardOldestPolicy drops oldest task if saturated.
1226       */
1227      public void testSaturatedExecute4() {
1228 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1228 >        final CountDownLatch done = new CountDownLatch(1);
1229 >        LatchAwaiter r1 = awaiter(done);
1230 >        LatchAwaiter r2 = awaiter(done);
1231 >        LatchAwaiter r3 = awaiter(done);
1232          final ThreadPoolExecutor p =
1233              new ThreadPoolExecutor(1, 1,
1234                                     LONG_DELAY_MS, MILLISECONDS,
1235                                     new ArrayBlockingQueue<Runnable>(1),
1236 <                                   h);
1237 <        try {
1238 <            p.execute(new TrackedLongRunnable());
1239 <            TrackedLongRunnable r2 = new TrackedLongRunnable();
1236 >                                   new DiscardOldestPolicy());
1237 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1238 >            assertEquals(LatchAwaiter.NEW, r1.state);
1239 >            assertEquals(LatchAwaiter.NEW, r2.state);
1240 >            assertEquals(LatchAwaiter.NEW, r3.state);
1241 >            p.execute(r1);
1242              p.execute(r2);
1243              assertTrue(p.getQueue().contains(r2));
1207            TrackedNoOpRunnable r3 = new TrackedNoOpRunnable();
1244              p.execute(r3);
1245              assertFalse(p.getQueue().contains(r2));
1246              assertTrue(p.getQueue().contains(r3));
1211            try { p.shutdownNow(); } catch (SecurityException ok) { return; }
1212        } finally {
1213            joinPool(p);
1247          }
1248 +        assertEquals(LatchAwaiter.DONE, r1.state);
1249 +        assertEquals(LatchAwaiter.NEW, r2.state);
1250 +        assertEquals(LatchAwaiter.DONE, r3.state);
1251      }
1252  
1253      /**
1254       * execute throws RejectedExecutionException if shutdown
1255       */
1256      public void testRejectedExecutionExceptionOnShutdown() {
1257 <        ThreadPoolExecutor p =
1257 >        final ThreadPoolExecutor p =
1258              new ThreadPoolExecutor(1, 1,
1259                                     LONG_DELAY_MS, MILLISECONDS,
1260                                     new ArrayBlockingQueue<Runnable>(1));
1261          try { p.shutdown(); } catch (SecurityException ok) { return; }
1262 <        try {
1263 <            p.execute(new NoOpRunnable());
1264 <            shouldThrow();
1265 <        } catch (RejectedExecutionException success) {}
1266 <
1267 <        joinPool(p);
1262 >        try (PoolCleaner cleaner = cleaner(p)) {
1263 >            try {
1264 >                p.execute(new NoOpRunnable());
1265 >                shouldThrow();
1266 >            } catch (RejectedExecutionException success) {}
1267 >        }
1268      }
1269  
1270      /**
1271       * execute using CallerRunsPolicy drops task on shutdown
1272       */
1273      public void testCallerRunsOnShutdown() {
1274 <        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1274 >        RejectedExecutionHandler h = new CallerRunsPolicy();
1275          final ThreadPoolExecutor p =
1276              new ThreadPoolExecutor(1, 1,
1277                                     LONG_DELAY_MS, MILLISECONDS,
1278                                     new ArrayBlockingQueue<Runnable>(1), h);
1279  
1280          try { p.shutdown(); } catch (SecurityException ok) { return; }
1281 <        try {
1281 >        try (PoolCleaner cleaner = cleaner(p)) {
1282              TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1283              p.execute(r);
1284              assertFalse(r.done);
1249        } finally {
1250            joinPool(p);
1285          }
1286      }
1287  
# Line 1255 | Line 1289 | public class ThreadPoolExecutorTest exte
1289       * execute using DiscardPolicy drops task on shutdown
1290       */
1291      public void testDiscardOnShutdown() {
1292 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardPolicy();
1259 <        ThreadPoolExecutor p =
1292 >        final ThreadPoolExecutor p =
1293              new ThreadPoolExecutor(1, 1,
1294                                     LONG_DELAY_MS, MILLISECONDS,
1295                                     new ArrayBlockingQueue<Runnable>(1),
1296 <                                   h);
1296 >                                   new DiscardPolicy());
1297  
1298          try { p.shutdown(); } catch (SecurityException ok) { return; }
1299 <        try {
1299 >        try (PoolCleaner cleaner = cleaner(p)) {
1300              TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1301              p.execute(r);
1302              assertFalse(r.done);
1270        } finally {
1271            joinPool(p);
1303          }
1304      }
1305  
# Line 1276 | Line 1307 | public class ThreadPoolExecutorTest exte
1307       * execute using DiscardOldestPolicy drops task on shutdown
1308       */
1309      public void testDiscardOldestOnShutdown() {
1310 <        RejectedExecutionHandler h = new ThreadPoolExecutor.DiscardOldestPolicy();
1280 <        ThreadPoolExecutor p =
1310 >        final ThreadPoolExecutor p =
1311              new ThreadPoolExecutor(1, 1,
1312                                     LONG_DELAY_MS, MILLISECONDS,
1313                                     new ArrayBlockingQueue<Runnable>(1),
1314 <                                   h);
1314 >                                   new DiscardOldestPolicy());
1315  
1316          try { p.shutdown(); } catch (SecurityException ok) { return; }
1317 <        try {
1317 >        try (PoolCleaner cleaner = cleaner(p)) {
1318              TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1319              p.execute(r);
1320              assertFalse(r.done);
1291        } finally {
1292            joinPool(p);
1321          }
1322      }
1323  
# Line 1297 | Line 1325 | public class ThreadPoolExecutorTest exte
1325       * execute(null) throws NPE
1326       */
1327      public void testExecuteNull() {
1328 <        ThreadPoolExecutor p =
1329 <            new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1328 >        final ThreadPoolExecutor p =
1329 >            new ThreadPoolExecutor(1, 2,
1330 >                                   1L, SECONDS,
1331                                     new ArrayBlockingQueue<Runnable>(10));
1332 <        try {
1333 <            p.execute(null);
1334 <            shouldThrow();
1335 <        } catch (NullPointerException success) {}
1336 <
1337 <        joinPool(p);
1332 >        try (PoolCleaner cleaner = cleaner(p)) {
1333 >            try {
1334 >                p.execute(null);
1335 >                shouldThrow();
1336 >            } catch (NullPointerException success) {}
1337 >        }
1338      }
1339  
1340      /**
1341       * setCorePoolSize of negative value throws IllegalArgumentException
1342       */
1343      public void testCorePoolSizeIllegalArgumentException() {
1344 <        ThreadPoolExecutor p =
1344 >        final ThreadPoolExecutor p =
1345              new ThreadPoolExecutor(1, 2,
1346                                     LONG_DELAY_MS, MILLISECONDS,
1347                                     new ArrayBlockingQueue<Runnable>(10));
1348 <        try {
1349 <            p.setCorePoolSize(-1);
1350 <            shouldThrow();
1351 <        } catch (IllegalArgumentException success) {
1352 <        } finally {
1324 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1348 >        try (PoolCleaner cleaner = cleaner(p)) {
1349 >            try {
1350 >                p.setCorePoolSize(-1);
1351 >                shouldThrow();
1352 >            } catch (IllegalArgumentException success) {}
1353          }
1326        joinPool(p);
1354      }
1355  
1356      /**
# Line 1331 | Line 1358 | public class ThreadPoolExecutorTest exte
1358       * given a value less the core pool size
1359       */
1360      public void testMaximumPoolSizeIllegalArgumentException() {
1361 <        ThreadPoolExecutor p =
1361 >        final ThreadPoolExecutor p =
1362              new ThreadPoolExecutor(2, 3,
1363                                     LONG_DELAY_MS, MILLISECONDS,
1364                                     new ArrayBlockingQueue<Runnable>(10));
1365 <        try {
1366 <            p.setMaximumPoolSize(1);
1367 <            shouldThrow();
1368 <        } catch (IllegalArgumentException success) {
1369 <        } finally {
1343 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1365 >        try (PoolCleaner cleaner = cleaner(p)) {
1366 >            try {
1367 >                p.setMaximumPoolSize(1);
1368 >                shouldThrow();
1369 >            } catch (IllegalArgumentException success) {}
1370          }
1345        joinPool(p);
1371      }
1372  
1373      /**
# Line 1350 | Line 1375 | public class ThreadPoolExecutorTest exte
1375       * if given a negative value
1376       */
1377      public void testMaximumPoolSizeIllegalArgumentException2() {
1378 <        ThreadPoolExecutor p =
1378 >        final ThreadPoolExecutor p =
1379              new ThreadPoolExecutor(2, 3,
1380                                     LONG_DELAY_MS, MILLISECONDS,
1381                                     new ArrayBlockingQueue<Runnable>(10));
1382 <        try {
1383 <            p.setMaximumPoolSize(-1);
1384 <            shouldThrow();
1385 <        } catch (IllegalArgumentException success) {
1386 <        } finally {
1362 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1382 >        try (PoolCleaner cleaner = cleaner(p)) {
1383 >            try {
1384 >                p.setMaximumPoolSize(-1);
1385 >                shouldThrow();
1386 >            } catch (IllegalArgumentException success) {}
1387          }
1364        joinPool(p);
1388      }
1389  
1390      /**
# Line 1369 | Line 1392 | public class ThreadPoolExecutorTest exte
1392       * max pool size result in IllegalArgumentException.
1393       */
1394      public void testPoolSizeInvariants() {
1395 <        ThreadPoolExecutor p =
1395 >        final ThreadPoolExecutor p =
1396              new ThreadPoolExecutor(1, 1,
1397                                     LONG_DELAY_MS, MILLISECONDS,
1398                                     new ArrayBlockingQueue<Runnable>(10));
1399 <        for (int s = 1; s < 5; s++) {
1400 <            p.setMaximumPoolSize(s);
1401 <            p.setCorePoolSize(s);
1402 <            try {
1403 <                p.setMaximumPoolSize(s - 1);
1404 <                shouldThrow();
1405 <            } catch (IllegalArgumentException success) {}
1406 <            assertEquals(s, p.getCorePoolSize());
1407 <            assertEquals(s, p.getMaximumPoolSize());
1408 <            try {
1409 <                p.setCorePoolSize(s + 1);
1410 <                shouldThrow();
1411 <            } catch (IllegalArgumentException success) {}
1412 <            assertEquals(s, p.getCorePoolSize());
1413 <            assertEquals(s, p.getMaximumPoolSize());
1399 >        try (PoolCleaner cleaner = cleaner(p)) {
1400 >            for (int s = 1; s < 5; s++) {
1401 >                p.setMaximumPoolSize(s);
1402 >                p.setCorePoolSize(s);
1403 >                try {
1404 >                    p.setMaximumPoolSize(s - 1);
1405 >                    shouldThrow();
1406 >                } catch (IllegalArgumentException success) {}
1407 >                assertEquals(s, p.getCorePoolSize());
1408 >                assertEquals(s, p.getMaximumPoolSize());
1409 >                try {
1410 >                    p.setCorePoolSize(s + 1);
1411 >                    shouldThrow();
1412 >                } catch (IllegalArgumentException success) {}
1413 >                assertEquals(s, p.getCorePoolSize());
1414 >                assertEquals(s, p.getMaximumPoolSize());
1415 >            }
1416          }
1392        joinPool(p);
1417      }
1418  
1419      /**
# Line 1397 | Line 1421 | public class ThreadPoolExecutorTest exte
1421       * when given a negative value
1422       */
1423      public void testKeepAliveTimeIllegalArgumentException() {
1424 <        ThreadPoolExecutor p =
1424 >        final ThreadPoolExecutor p =
1425              new ThreadPoolExecutor(2, 3,
1426                                     LONG_DELAY_MS, MILLISECONDS,
1427                                     new ArrayBlockingQueue<Runnable>(10));
1428 <        try {
1429 <            p.setKeepAliveTime(-1,MILLISECONDS);
1430 <            shouldThrow();
1431 <        } catch (IllegalArgumentException success) {
1432 <        } finally {
1409 <            try { p.shutdown(); } catch (SecurityException ok) { return; }
1428 >        try (PoolCleaner cleaner = cleaner(p)) {
1429 >            try {
1430 >                p.setKeepAliveTime(-1, MILLISECONDS);
1431 >                shouldThrow();
1432 >            } catch (IllegalArgumentException success) {}
1433          }
1411        joinPool(p);
1434      }
1435  
1436      /**
# Line 1416 | Line 1438 | public class ThreadPoolExecutorTest exte
1438       */
1439      public void testTerminated() {
1440          ExtendedTPE p = new ExtendedTPE();
1441 <        try { p.shutdown(); } catch (SecurityException ok) { return; }
1442 <        assertTrue(p.terminatedCalled());
1443 <        joinPool(p);
1441 >        try (PoolCleaner cleaner = cleaner(p)) {
1442 >            try { p.shutdown(); } catch (SecurityException ok) { return; }
1443 >            assertTrue(p.terminatedCalled());
1444 >            assertTrue(p.isShutdown());
1445 >        }
1446      }
1447  
1448      /**
# Line 1426 | Line 1450 | public class ThreadPoolExecutorTest exte
1450       */
1451      public void testBeforeAfter() throws InterruptedException {
1452          ExtendedTPE p = new ExtendedTPE();
1453 <        try {
1453 >        try (PoolCleaner cleaner = cleaner(p)) {
1454              final CountDownLatch done = new CountDownLatch(1);
1455              p.execute(new CheckedRunnable() {
1456                  public void realRun() {
# Line 1436 | Line 1460 | public class ThreadPoolExecutorTest exte
1460              assertEquals(0, done.getCount());
1461              assertTrue(p.afterCalled());
1462              assertTrue(p.beforeCalled());
1439            try { p.shutdown(); } catch (SecurityException ok) { return; }
1440        } finally {
1441            joinPool(p);
1463          }
1464      }
1465  
# Line 1446 | Line 1467 | public class ThreadPoolExecutorTest exte
1467       * completed submit of callable returns result
1468       */
1469      public void testSubmitCallable() throws Exception {
1470 <        ExecutorService e =
1470 >        final ExecutorService e =
1471              new ThreadPoolExecutor(2, 2,
1472                                     LONG_DELAY_MS, MILLISECONDS,
1473                                     new ArrayBlockingQueue<Runnable>(10));
1474 <        try {
1474 >        try (PoolCleaner cleaner = cleaner(e)) {
1475              Future<String> future = e.submit(new StringTask());
1476              String result = future.get();
1477              assertSame(TEST_STRING, result);
1457        } finally {
1458            joinPool(e);
1478          }
1479      }
1480  
# Line 1463 | Line 1482 | public class ThreadPoolExecutorTest exte
1482       * completed submit of runnable returns successfully
1483       */
1484      public void testSubmitRunnable() throws Exception {
1485 <        ExecutorService e =
1485 >        final ExecutorService e =
1486              new ThreadPoolExecutor(2, 2,
1487                                     LONG_DELAY_MS, MILLISECONDS,
1488                                     new ArrayBlockingQueue<Runnable>(10));
1489 <        try {
1489 >        try (PoolCleaner cleaner = cleaner(e)) {
1490              Future<?> future = e.submit(new NoOpRunnable());
1491              future.get();
1492              assertTrue(future.isDone());
1474        } finally {
1475            joinPool(e);
1493          }
1494      }
1495  
# Line 1480 | Line 1497 | public class ThreadPoolExecutorTest exte
1497       * completed submit of (runnable, result) returns result
1498       */
1499      public void testSubmitRunnable2() throws Exception {
1500 <        ExecutorService e =
1500 >        final ExecutorService e =
1501              new ThreadPoolExecutor(2, 2,
1502                                     LONG_DELAY_MS, MILLISECONDS,
1503                                     new ArrayBlockingQueue<Runnable>(10));
1504 <        try {
1504 >        try (PoolCleaner cleaner = cleaner(e)) {
1505              Future<String> future = e.submit(new NoOpRunnable(), TEST_STRING);
1506              String result = future.get();
1507              assertSame(TEST_STRING, result);
1491        } finally {
1492            joinPool(e);
1508          }
1509      }
1510  
# Line 1497 | Line 1512 | public class ThreadPoolExecutorTest exte
1512       * invokeAny(null) throws NPE
1513       */
1514      public void testInvokeAny1() throws Exception {
1515 <        ExecutorService e =
1515 >        final ExecutorService e =
1516              new ThreadPoolExecutor(2, 2,
1517                                     LONG_DELAY_MS, MILLISECONDS,
1518                                     new ArrayBlockingQueue<Runnable>(10));
1519 <        try {
1520 <            e.invokeAny(null);
1521 <            shouldThrow();
1522 <        } catch (NullPointerException success) {
1523 <        } finally {
1509 <            joinPool(e);
1519 >        try (PoolCleaner cleaner = cleaner(e)) {
1520 >            try {
1521 >                e.invokeAny(null);
1522 >                shouldThrow();
1523 >            } catch (NullPointerException success) {}
1524          }
1525      }
1526  
1527      /**
1528 <     * invokeAny(empty collection) throws IAE
1528 >     * invokeAny(empty collection) throws IllegalArgumentException
1529       */
1530      public void testInvokeAny2() throws Exception {
1531 <        ExecutorService e =
1531 >        final ExecutorService e =
1532              new ThreadPoolExecutor(2, 2,
1533                                     LONG_DELAY_MS, MILLISECONDS,
1534                                     new ArrayBlockingQueue<Runnable>(10));
1535 <        try {
1536 <            e.invokeAny(new ArrayList<Callable<String>>());
1537 <            shouldThrow();
1538 <        } catch (IllegalArgumentException success) {
1539 <        } finally {
1526 <            joinPool(e);
1535 >        try (PoolCleaner cleaner = cleaner(e)) {
1536 >            try {
1537 >                e.invokeAny(new ArrayList<Callable<String>>());
1538 >                shouldThrow();
1539 >            } catch (IllegalArgumentException success) {}
1540          }
1541      }
1542  
# Line 1536 | Line 1549 | public class ThreadPoolExecutorTest exte
1549              new ThreadPoolExecutor(2, 2,
1550                                     LONG_DELAY_MS, MILLISECONDS,
1551                                     new ArrayBlockingQueue<Runnable>(10));
1552 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1553 <        l.add(latchAwaitingStringTask(latch));
1554 <        l.add(null);
1555 <        try {
1556 <            e.invokeAny(l);
1557 <            shouldThrow();
1558 <        } catch (NullPointerException success) {
1559 <        } finally {
1552 >        try (PoolCleaner cleaner = cleaner(e)) {
1553 >            List<Callable<String>> l = new ArrayList<>();
1554 >            l.add(latchAwaitingStringTask(latch));
1555 >            l.add(null);
1556 >            try {
1557 >                e.invokeAny(l);
1558 >                shouldThrow();
1559 >            } catch (NullPointerException success) {}
1560              latch.countDown();
1548            joinPool(e);
1561          }
1562      }
1563  
# Line 1553 | Line 1565 | public class ThreadPoolExecutorTest exte
1565       * invokeAny(c) throws ExecutionException if no task completes
1566       */
1567      public void testInvokeAny4() throws Exception {
1568 <        ExecutorService e =
1568 >        final ExecutorService e =
1569              new ThreadPoolExecutor(2, 2,
1570                                     LONG_DELAY_MS, MILLISECONDS,
1571                                     new ArrayBlockingQueue<Runnable>(10));
1572 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1573 <        l.add(new NPETask());
1574 <        try {
1575 <            e.invokeAny(l);
1576 <            shouldThrow();
1577 <        } catch (ExecutionException success) {
1578 <            assertTrue(success.getCause() instanceof NullPointerException);
1579 <        } finally {
1580 <            joinPool(e);
1572 >        try (PoolCleaner cleaner = cleaner(e)) {
1573 >            List<Callable<String>> l = new ArrayList<>();
1574 >            l.add(new NPETask());
1575 >            try {
1576 >                e.invokeAny(l);
1577 >                shouldThrow();
1578 >            } catch (ExecutionException success) {
1579 >                assertTrue(success.getCause() instanceof NullPointerException);
1580 >            }
1581          }
1582      }
1583  
# Line 1573 | Line 1585 | public class ThreadPoolExecutorTest exte
1585       * invokeAny(c) returns result of some task
1586       */
1587      public void testInvokeAny5() throws Exception {
1588 <        ExecutorService e =
1588 >        final ExecutorService e =
1589              new ThreadPoolExecutor(2, 2,
1590                                     LONG_DELAY_MS, MILLISECONDS,
1591                                     new ArrayBlockingQueue<Runnable>(10));
1592 <        try {
1593 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1592 >        try (PoolCleaner cleaner = cleaner(e)) {
1593 >            List<Callable<String>> l = new ArrayList<>();
1594              l.add(new StringTask());
1595              l.add(new StringTask());
1596              String result = e.invokeAny(l);
1597              assertSame(TEST_STRING, result);
1586        } finally {
1587            joinPool(e);
1598          }
1599      }
1600  
# Line 1592 | Line 1602 | public class ThreadPoolExecutorTest exte
1602       * invokeAll(null) throws NPE
1603       */
1604      public void testInvokeAll1() throws Exception {
1605 <        ExecutorService e =
1605 >        final ExecutorService e =
1606              new ThreadPoolExecutor(2, 2,
1607                                     LONG_DELAY_MS, MILLISECONDS,
1608                                     new ArrayBlockingQueue<Runnable>(10));
1609 <        try {
1610 <            e.invokeAll(null);
1611 <            shouldThrow();
1612 <        } catch (NullPointerException success) {
1613 <        } finally {
1604 <            joinPool(e);
1609 >        try (PoolCleaner cleaner = cleaner(e)) {
1610 >            try {
1611 >                e.invokeAll(null);
1612 >                shouldThrow();
1613 >            } catch (NullPointerException success) {}
1614          }
1615      }
1616  
1617      /**
1618 <     * invokeAll(empty collection) returns empty collection
1618 >     * invokeAll(empty collection) returns empty list
1619       */
1620      public void testInvokeAll2() throws InterruptedException {
1621 <        ExecutorService e =
1621 >        final ExecutorService e =
1622              new ThreadPoolExecutor(2, 2,
1623                                     LONG_DELAY_MS, MILLISECONDS,
1624                                     new ArrayBlockingQueue<Runnable>(10));
1625 <        try {
1626 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1625 >        final Collection<Callable<String>> emptyCollection
1626 >            = Collections.emptyList();
1627 >        try (PoolCleaner cleaner = cleaner(e)) {
1628 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1629              assertTrue(r.isEmpty());
1619        } finally {
1620            joinPool(e);
1630          }
1631      }
1632  
# Line 1625 | Line 1634 | public class ThreadPoolExecutorTest exte
1634       * invokeAll(c) throws NPE if c has null elements
1635       */
1636      public void testInvokeAll3() throws Exception {
1637 <        ExecutorService e =
1637 >        final ExecutorService e =
1638              new ThreadPoolExecutor(2, 2,
1639                                     LONG_DELAY_MS, MILLISECONDS,
1640                                     new ArrayBlockingQueue<Runnable>(10));
1641 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1642 <        l.add(new StringTask());
1643 <        l.add(null);
1644 <        try {
1645 <            e.invokeAll(l);
1646 <            shouldThrow();
1647 <        } catch (NullPointerException success) {
1648 <        } finally {
1640 <            joinPool(e);
1641 >        try (PoolCleaner cleaner = cleaner(e)) {
1642 >            List<Callable<String>> l = new ArrayList<>();
1643 >            l.add(new StringTask());
1644 >            l.add(null);
1645 >            try {
1646 >                e.invokeAll(l);
1647 >                shouldThrow();
1648 >            } catch (NullPointerException success) {}
1649          }
1650      }
1651  
# Line 1645 | Line 1653 | public class ThreadPoolExecutorTest exte
1653       * get of element of invokeAll(c) throws exception on failed task
1654       */
1655      public void testInvokeAll4() throws Exception {
1656 <        ExecutorService e =
1656 >        final ExecutorService e =
1657              new ThreadPoolExecutor(2, 2,
1658                                     LONG_DELAY_MS, MILLISECONDS,
1659                                     new ArrayBlockingQueue<Runnable>(10));
1660 <        try {
1661 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1660 >        try (PoolCleaner cleaner = cleaner(e)) {
1661 >            List<Callable<String>> l = new ArrayList<>();
1662              l.add(new NPETask());
1663              List<Future<String>> futures = e.invokeAll(l);
1664              assertEquals(1, futures.size());
# Line 1660 | Line 1668 | public class ThreadPoolExecutorTest exte
1668              } catch (ExecutionException success) {
1669                  assertTrue(success.getCause() instanceof NullPointerException);
1670              }
1663        } finally {
1664            joinPool(e);
1671          }
1672      }
1673  
# Line 1669 | Line 1675 | public class ThreadPoolExecutorTest exte
1675       * invokeAll(c) returns results of all completed tasks
1676       */
1677      public void testInvokeAll5() throws Exception {
1678 <        ExecutorService e =
1678 >        final ExecutorService e =
1679              new ThreadPoolExecutor(2, 2,
1680                                     LONG_DELAY_MS, MILLISECONDS,
1681                                     new ArrayBlockingQueue<Runnable>(10));
1682 <        try {
1683 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1682 >        try (PoolCleaner cleaner = cleaner(e)) {
1683 >            List<Callable<String>> l = new ArrayList<>();
1684              l.add(new StringTask());
1685              l.add(new StringTask());
1686              List<Future<String>> futures = e.invokeAll(l);
1687              assertEquals(2, futures.size());
1688              for (Future<String> future : futures)
1689                  assertSame(TEST_STRING, future.get());
1684        } finally {
1685            joinPool(e);
1690          }
1691      }
1692  
# Line 1690 | Line 1694 | public class ThreadPoolExecutorTest exte
1694       * timed invokeAny(null) throws NPE
1695       */
1696      public void testTimedInvokeAny1() throws Exception {
1697 <        ExecutorService e =
1697 >        final ExecutorService e =
1698              new ThreadPoolExecutor(2, 2,
1699                                     LONG_DELAY_MS, MILLISECONDS,
1700                                     new ArrayBlockingQueue<Runnable>(10));
1701 <        try {
1702 <            e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1703 <            shouldThrow();
1704 <        } catch (NullPointerException success) {
1705 <        } finally {
1702 <            joinPool(e);
1701 >        try (PoolCleaner cleaner = cleaner(e)) {
1702 >            try {
1703 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1704 >                shouldThrow();
1705 >            } catch (NullPointerException success) {}
1706          }
1707      }
1708  
# Line 1707 | Line 1710 | public class ThreadPoolExecutorTest exte
1710       * timed invokeAny(,,null) throws NPE
1711       */
1712      public void testTimedInvokeAnyNullTimeUnit() throws Exception {
1713 <        ExecutorService e =
1713 >        final ExecutorService e =
1714              new ThreadPoolExecutor(2, 2,
1715                                     LONG_DELAY_MS, MILLISECONDS,
1716                                     new ArrayBlockingQueue<Runnable>(10));
1717 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1718 <        l.add(new StringTask());
1719 <        try {
1720 <            e.invokeAny(l, MEDIUM_DELAY_MS, null);
1721 <            shouldThrow();
1722 <        } catch (NullPointerException success) {
1723 <        } finally {
1721 <            joinPool(e);
1717 >        try (PoolCleaner cleaner = cleaner(e)) {
1718 >            List<Callable<String>> l = new ArrayList<>();
1719 >            l.add(new StringTask());
1720 >            try {
1721 >                e.invokeAny(l, randomTimeout(), null);
1722 >                shouldThrow();
1723 >            } catch (NullPointerException success) {}
1724          }
1725      }
1726  
1727      /**
1728 <     * timed invokeAny(empty collection) throws IAE
1728 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1729       */
1730      public void testTimedInvokeAny2() throws Exception {
1731 <        ExecutorService e =
1731 >        final ExecutorService e =
1732              new ThreadPoolExecutor(2, 2,
1733                                     LONG_DELAY_MS, MILLISECONDS,
1734                                     new ArrayBlockingQueue<Runnable>(10));
1735 <        try {
1736 <            e.invokeAny(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1737 <            shouldThrow();
1738 <        } catch (IllegalArgumentException success) {
1739 <        } finally {
1740 <            joinPool(e);
1735 >        try (PoolCleaner cleaner = cleaner(e)) {
1736 >            try {
1737 >                e.invokeAny(new ArrayList<Callable<String>>(),
1738 >                            randomTimeout(), randomTimeUnit());
1739 >                shouldThrow();
1740 >            } catch (IllegalArgumentException success) {}
1741          }
1742      }
1743  
1744      /**
1745 <     * timed invokeAny(c) throws NPE if c has null elements
1745 >     * timed invokeAny(c) throws NullPointerException if c has null elements
1746       */
1747      public void testTimedInvokeAny3() throws Exception {
1748          final CountDownLatch latch = new CountDownLatch(1);
# Line 1748 | Line 1750 | public class ThreadPoolExecutorTest exte
1750              new ThreadPoolExecutor(2, 2,
1751                                     LONG_DELAY_MS, MILLISECONDS,
1752                                     new ArrayBlockingQueue<Runnable>(10));
1753 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1754 <        l.add(latchAwaitingStringTask(latch));
1755 <        l.add(null);
1756 <        try {
1757 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1758 <            shouldThrow();
1759 <        } catch (NullPointerException success) {
1760 <        } finally {
1753 >        try (PoolCleaner cleaner = cleaner(e)) {
1754 >            List<Callable<String>> l = new ArrayList<>();
1755 >            l.add(latchAwaitingStringTask(latch));
1756 >            l.add(null);
1757 >            try {
1758 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1759 >                shouldThrow();
1760 >            } catch (NullPointerException success) {}
1761              latch.countDown();
1760            joinPool(e);
1762          }
1763      }
1764  
# Line 1765 | Line 1766 | public class ThreadPoolExecutorTest exte
1766       * timed invokeAny(c) throws ExecutionException if no task completes
1767       */
1768      public void testTimedInvokeAny4() throws Exception {
1769 <        ExecutorService e =
1769 >        final ExecutorService e =
1770              new ThreadPoolExecutor(2, 2,
1771                                     LONG_DELAY_MS, MILLISECONDS,
1772                                     new ArrayBlockingQueue<Runnable>(10));
1773 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1774 <        l.add(new NPETask());
1775 <        try {
1776 <            e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1777 <            shouldThrow();
1778 <        } catch (ExecutionException success) {
1779 <            assertTrue(success.getCause() instanceof NullPointerException);
1780 <        } finally {
1781 <            joinPool(e);
1773 >        try (PoolCleaner cleaner = cleaner(e)) {
1774 >            long startTime = System.nanoTime();
1775 >            List<Callable<String>> l = new ArrayList<>();
1776 >            l.add(new NPETask());
1777 >            try {
1778 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1779 >                shouldThrow();
1780 >            } catch (ExecutionException success) {
1781 >                assertTrue(success.getCause() instanceof NullPointerException);
1782 >            }
1783 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1784          }
1785      }
1786  
# Line 1785 | Line 1788 | public class ThreadPoolExecutorTest exte
1788       * timed invokeAny(c) returns result of some task
1789       */
1790      public void testTimedInvokeAny5() throws Exception {
1791 <        ExecutorService e =
1791 >        final ExecutorService e =
1792              new ThreadPoolExecutor(2, 2,
1793                                     LONG_DELAY_MS, MILLISECONDS,
1794                                     new ArrayBlockingQueue<Runnable>(10));
1795 <        try {
1796 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1795 >        try (PoolCleaner cleaner = cleaner(e)) {
1796 >            long startTime = System.nanoTime();
1797 >            List<Callable<String>> l = new ArrayList<>();
1798              l.add(new StringTask());
1799              l.add(new StringTask());
1800 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1800 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1801              assertSame(TEST_STRING, result);
1802 <        } finally {
1799 <            joinPool(e);
1802 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1803          }
1804      }
1805  
# Line 1804 | Line 1807 | public class ThreadPoolExecutorTest exte
1807       * timed invokeAll(null) throws NPE
1808       */
1809      public void testTimedInvokeAll1() throws Exception {
1810 <        ExecutorService e =
1810 >        final ExecutorService e =
1811              new ThreadPoolExecutor(2, 2,
1812                                     LONG_DELAY_MS, MILLISECONDS,
1813                                     new ArrayBlockingQueue<Runnable>(10));
1814 <        try {
1815 <            e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1816 <            shouldThrow();
1817 <        } catch (NullPointerException success) {
1818 <        } finally {
1816 <            joinPool(e);
1814 >        try (PoolCleaner cleaner = cleaner(e)) {
1815 >            try {
1816 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1817 >                shouldThrow();
1818 >            } catch (NullPointerException success) {}
1819          }
1820      }
1821  
# Line 1821 | Line 1823 | public class ThreadPoolExecutorTest exte
1823       * timed invokeAll(,,null) throws NPE
1824       */
1825      public void testTimedInvokeAllNullTimeUnit() throws Exception {
1826 <        ExecutorService e =
1826 >        final ExecutorService e =
1827              new ThreadPoolExecutor(2, 2,
1828                                     LONG_DELAY_MS, MILLISECONDS,
1829                                     new ArrayBlockingQueue<Runnable>(10));
1830 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1831 <        l.add(new StringTask());
1832 <        try {
1833 <            e.invokeAll(l, MEDIUM_DELAY_MS, null);
1834 <            shouldThrow();
1835 <        } catch (NullPointerException success) {
1836 <        } finally {
1835 <            joinPool(e);
1830 >        try (PoolCleaner cleaner = cleaner(e)) {
1831 >            List<Callable<String>> l = new ArrayList<>();
1832 >            l.add(new StringTask());
1833 >            try {
1834 >                e.invokeAll(l, randomTimeout(), null);
1835 >                shouldThrow();
1836 >            } catch (NullPointerException success) {}
1837          }
1838      }
1839  
1840      /**
1841 <     * timed invokeAll(empty collection) returns empty collection
1841 >     * timed invokeAll(empty collection) returns empty list
1842       */
1843      public void testTimedInvokeAll2() throws InterruptedException {
1844 <        ExecutorService e =
1844 >        final ExecutorService e =
1845              new ThreadPoolExecutor(2, 2,
1846                                     LONG_DELAY_MS, MILLISECONDS,
1847                                     new ArrayBlockingQueue<Runnable>(10));
1848 <        try {
1849 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(), MEDIUM_DELAY_MS, MILLISECONDS);
1848 >        final Collection<Callable<String>> emptyCollection
1849 >            = Collections.emptyList();
1850 >        try (PoolCleaner cleaner = cleaner(e)) {
1851 >            List<Future<String>> r =
1852 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1853              assertTrue(r.isEmpty());
1850        } finally {
1851            joinPool(e);
1854          }
1855      }
1856  
# Line 1856 | Line 1858 | public class ThreadPoolExecutorTest exte
1858       * timed invokeAll(c) throws NPE if c has null elements
1859       */
1860      public void testTimedInvokeAll3() throws Exception {
1861 <        ExecutorService e =
1861 >        final ExecutorService e =
1862              new ThreadPoolExecutor(2, 2,
1863                                     LONG_DELAY_MS, MILLISECONDS,
1864                                     new ArrayBlockingQueue<Runnable>(10));
1865 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1866 <        l.add(new StringTask());
1867 <        l.add(null);
1868 <        try {
1869 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1870 <            shouldThrow();
1871 <        } catch (NullPointerException success) {
1872 <        } finally {
1871 <            joinPool(e);
1865 >        try (PoolCleaner cleaner = cleaner(e)) {
1866 >            List<Callable<String>> l = new ArrayList<>();
1867 >            l.add(new StringTask());
1868 >            l.add(null);
1869 >            try {
1870 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1871 >                shouldThrow();
1872 >            } catch (NullPointerException success) {}
1873          }
1874      }
1875  
# Line 1876 | Line 1877 | public class ThreadPoolExecutorTest exte
1877       * get of element of invokeAll(c) throws exception on failed task
1878       */
1879      public void testTimedInvokeAll4() throws Exception {
1880 <        ExecutorService e =
1880 >        final ExecutorService e =
1881              new ThreadPoolExecutor(2, 2,
1882                                     LONG_DELAY_MS, MILLISECONDS,
1883                                     new ArrayBlockingQueue<Runnable>(10));
1884 <        List<Callable<String>> l = new ArrayList<Callable<String>>();
1885 <        l.add(new NPETask());
1886 <        List<Future<String>> futures =
1887 <            e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1888 <        assertEquals(1, futures.size());
1889 <        try {
1890 <            futures.get(0).get();
1891 <            shouldThrow();
1892 <        } catch (ExecutionException success) {
1893 <            assertTrue(success.getCause() instanceof NullPointerException);
1894 <        } finally {
1895 <            joinPool(e);
1884 >        try (PoolCleaner cleaner = cleaner(e)) {
1885 >            List<Callable<String>> l = new ArrayList<>();
1886 >            l.add(new NPETask());
1887 >            List<Future<String>> futures =
1888 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1889 >            assertEquals(1, futures.size());
1890 >            try {
1891 >                futures.get(0).get();
1892 >                shouldThrow();
1893 >            } catch (ExecutionException success) {
1894 >                assertTrue(success.getCause() instanceof NullPointerException);
1895 >            }
1896          }
1897      }
1898  
# Line 1899 | Line 1900 | public class ThreadPoolExecutorTest exte
1900       * timed invokeAll(c) returns results of all completed tasks
1901       */
1902      public void testTimedInvokeAll5() throws Exception {
1903 <        ExecutorService e =
1903 >        final ExecutorService e =
1904              new ThreadPoolExecutor(2, 2,
1905                                     LONG_DELAY_MS, MILLISECONDS,
1906                                     new ArrayBlockingQueue<Runnable>(10));
1907 <        try {
1908 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1907 >        try (PoolCleaner cleaner = cleaner(e)) {
1908 >            List<Callable<String>> l = new ArrayList<>();
1909              l.add(new StringTask());
1910              l.add(new StringTask());
1911              List<Future<String>> futures =
# Line 1912 | Line 1913 | public class ThreadPoolExecutorTest exte
1913              assertEquals(2, futures.size());
1914              for (Future<String> future : futures)
1915                  assertSame(TEST_STRING, future.get());
1915        } finally {
1916            joinPool(e);
1916          }
1917      }
1918  
# Line 1921 | Line 1920 | public class ThreadPoolExecutorTest exte
1920       * timed invokeAll(c) cancels tasks not completed by timeout
1921       */
1922      public void testTimedInvokeAll6() throws Exception {
1923 <        ExecutorService e =
1924 <            new ThreadPoolExecutor(2, 2,
1925 <                                   LONG_DELAY_MS, MILLISECONDS,
1926 <                                   new ArrayBlockingQueue<Runnable>(10));
1927 <        try {
1928 <            for (long timeout = timeoutMillis();;) {
1923 >        for (long timeout = timeoutMillis();;) {
1924 >            final CountDownLatch done = new CountDownLatch(1);
1925 >            final Callable<String> waiter = new CheckedCallable<String>() {
1926 >                public String realCall() {
1927 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1928 >                    catch (InterruptedException ok) {}
1929 >                    return "1"; }};
1930 >            final ExecutorService p =
1931 >                new ThreadPoolExecutor(2, 2,
1932 >                                       LONG_DELAY_MS, MILLISECONDS,
1933 >                                       new ArrayBlockingQueue<Runnable>(10));
1934 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1935                  List<Callable<String>> tasks = new ArrayList<>();
1936                  tasks.add(new StringTask("0"));
1937 <                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1937 >                tasks.add(waiter);
1938                  tasks.add(new StringTask("2"));
1939                  long startTime = System.nanoTime();
1940                  List<Future<String>> futures =
1941 <                    e.invokeAll(tasks, timeout, MILLISECONDS);
1941 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1942                  assertEquals(tasks.size(), futures.size());
1943                  assertTrue(millisElapsedSince(startTime) >= timeout);
1944                  for (Future future : futures)
# Line 1949 | Line 1954 | public class ThreadPoolExecutorTest exte
1954                          fail("expected exactly one task to be cancelled");
1955                  }
1956              }
1952        } finally {
1953            joinPool(e);
1957          }
1958      }
1959  
# Line 1964 | Line 1967 | public class ThreadPoolExecutorTest exte
1967                                     LONG_DELAY_MS, MILLISECONDS,
1968                                     new LinkedBlockingQueue<Runnable>(),
1969                                     new FailingThreadFactory());
1970 <        try {
1970 >        try (PoolCleaner cleaner = cleaner(e)) {
1971              final int TASKS = 100;
1972              final CountDownLatch done = new CountDownLatch(TASKS);
1973              for (int k = 0; k < TASKS; ++k)
# Line 1972 | Line 1975 | public class ThreadPoolExecutorTest exte
1975                      public void realRun() {
1976                          done.countDown();
1977                      }});
1978 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1976 <        } finally {
1977 <            joinPool(e);
1978 >            await(done);
1979          }
1980      }
1981  
# Line 1986 | Line 1987 | public class ThreadPoolExecutorTest exte
1987              new ThreadPoolExecutor(2, 2,
1988                                     1000, MILLISECONDS,
1989                                     new ArrayBlockingQueue<Runnable>(10));
1990 <        assertFalse(p.allowsCoreThreadTimeOut());
1991 <        joinPool(p);
1990 >        try (PoolCleaner cleaner = cleaner(p)) {
1991 >            assertFalse(p.allowsCoreThreadTimeOut());
1992 >        }
1993      }
1994  
1995      /**
# Line 1999 | Line 2001 | public class ThreadPoolExecutorTest exte
2001              new ThreadPoolExecutor(2, 10,
2002                                     keepAliveTime, MILLISECONDS,
2003                                     new ArrayBlockingQueue<Runnable>(10));
2004 <        final CountDownLatch threadStarted = new CountDownLatch(1);
2005 <        try {
2004 >        try (PoolCleaner cleaner = cleaner(p)) {
2005 >            final CountDownLatch threadStarted = new CountDownLatch(1);
2006              p.allowCoreThreadTimeOut(true);
2007              p.execute(new CheckedRunnable() {
2008                  public void realRun() {
# Line 2015 | Line 2017 | public class ThreadPoolExecutorTest exte
2017                  Thread.yield();
2018              assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
2019              assertEquals(0, p.getPoolSize());
2018        } finally {
2019            joinPool(p);
2020          }
2021      }
2022  
# Line 2029 | Line 2029 | public class ThreadPoolExecutorTest exte
2029              new ThreadPoolExecutor(2, 10,
2030                                     keepAliveTime, MILLISECONDS,
2031                                     new ArrayBlockingQueue<Runnable>(10));
2032 <        final CountDownLatch threadStarted = new CountDownLatch(1);
2033 <        try {
2032 >        try (PoolCleaner cleaner = cleaner(p)) {
2033 >            final CountDownLatch threadStarted = new CountDownLatch(1);
2034              p.allowCoreThreadTimeOut(false);
2035              p.execute(new CheckedRunnable() {
2036                  public void realRun() throws InterruptedException {
# Line 2039 | Line 2039 | public class ThreadPoolExecutorTest exte
2039                  }});
2040              delay(2 * keepAliveTime);
2041              assertTrue(p.getPoolSize() >= 1);
2042        } finally {
2043            joinPool(p);
2042          }
2043      }
2044  
# Line 2059 | Line 2057 | public class ThreadPoolExecutorTest exte
2057              new ThreadPoolExecutor(1, 30,
2058                                     60, SECONDS,
2059                                     new ArrayBlockingQueue(30));
2060 <        try {
2060 >        try (PoolCleaner cleaner = cleaner(p)) {
2061              for (int i = 0; i < nTasks; ++i) {
2062                  for (;;) {
2063                      try {
# Line 2070 | Line 2068 | public class ThreadPoolExecutorTest exte
2068                  }
2069              }
2070              // enough time to run all tasks
2071 <            assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS));
2074 <        } finally {
2075 <            joinPool(p);
2071 >            await(done, nTasks * SHORT_DELAY_MS);
2072          }
2073      }
2074  
# Line 2080 | Line 2076 | public class ThreadPoolExecutorTest exte
2076       * get(cancelled task) throws CancellationException
2077       */
2078      public void testGet_cancelled() throws Exception {
2079 +        final CountDownLatch done = new CountDownLatch(1);
2080          final ExecutorService e =
2081              new ThreadPoolExecutor(1, 1,
2082                                     LONG_DELAY_MS, MILLISECONDS,
2083                                     new LinkedBlockingQueue<Runnable>());
2084 <        try {
2084 >        try (PoolCleaner cleaner = cleaner(e, done)) {
2085              final CountDownLatch blockerStarted = new CountDownLatch(1);
2089            final CountDownLatch done = new CountDownLatch(1);
2086              final List<Future<?>> futures = new ArrayList<>();
2087              for (int i = 0; i < 2; i++) {
2088                  Runnable r = new CheckedRunnable() { public void realRun()
# Line 2096 | Line 2092 | public class ThreadPoolExecutorTest exte
2092                  }};
2093                  futures.add(e.submit(r));
2094              }
2095 <            assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS));
2095 >            await(blockerStarted);
2096              for (Future<?> future : futures) future.cancel(false);
2097              for (Future<?> future : futures) {
2098                  try {
# Line 2110 | Line 2106 | public class ThreadPoolExecutorTest exte
2106                  assertTrue(future.isCancelled());
2107                  assertTrue(future.isDone());
2108              }
2113            done.countDown();
2114        } finally {
2115            joinPool(e);
2109          }
2110      }
2111  
2112 +    /** Directly test simple ThreadPoolExecutor RejectedExecutionHandlers. */
2113 +    public void testStandardRejectedExecutionHandlers() {
2114 +        final ThreadPoolExecutor p =
2115 +            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2116 +                                   new ArrayBlockingQueue<Runnable>(1));
2117 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2118 +        final Runnable r = new Runnable() { public void run() {
2119 +            thread.set(Thread.currentThread()); }};
2120 +
2121 +        try {
2122 +            new AbortPolicy().rejectedExecution(r, p);
2123 +            shouldThrow();
2124 +        } catch (RejectedExecutionException success) {}
2125 +        assertNull(thread.get());
2126 +
2127 +        new DiscardPolicy().rejectedExecution(r, p);
2128 +        assertNull(thread.get());
2129 +
2130 +        new CallerRunsPolicy().rejectedExecution(r, p);
2131 +        assertSame(Thread.currentThread(), thread.get());
2132 +
2133 +        // check that pool was not perturbed by handlers
2134 +        assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
2135 +        assertEquals(0, p.getTaskCount());
2136 +        assertTrue(p.getQueue().isEmpty());
2137 +    }
2138 +
2139   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines