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.101 by jsr166, Mon Oct 5 21:54:33 2015 UTC vs.
Revision 1.127 by dl, Tue Jan 26 13:33:06 2021 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 92 | Line 98 | public class ThreadPoolExecutorTest exte
98              final Runnable task = new CheckedRunnable() {
99                  public void realRun() { done.countDown(); }};
100              p.execute(task);
101 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
101 >            await(done);
102          }
103      }
104  
# Line 101 | 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 <        try (PoolCleaner cleaner = cleaner(p)) {
115 >        try (PoolCleaner cleaner = cleaner(p, done)) {
116              final CountDownLatch threadStarted = new CountDownLatch(1);
110            final CountDownLatch done = 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(MEDIUM_DELAY_MS, MILLISECONDS));
124 >            await(threadStarted);
125              assertEquals(1, p.getActiveCount());
120            done.countDown();
126          }
127      }
128  
# Line 187 | 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 277 | 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 329 | 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)) {
337 <            final CountDownLatch threadsStarted = new CountDownLatch(THREADS);
338 <            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());
349            done.countDown();   // release pool
367          }
368          assertEquals(THREADS, p.getLargestPoolSize());
369      }
# Line 374 | 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 <        try (PoolCleaner cleaner = cleaner(p)) {
382 <            final CountDownLatch threadStarted = new CountDownLatch(1);
383 <            final CountDownLatch done = new CountDownLatch(1);
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(MEDIUM_DELAY_MS, MILLISECONDS));
408 >            await(threadStarted);
409              assertEquals(1, p.getPoolSize());
393            done.countDown();   // release pool
410          }
411      }
412  
# Line 411 | Line 427 | public class ThreadPoolExecutorTest exte
427              p.execute(new CheckedRunnable() {
428                  public void realRun() throws InterruptedException {
429                      threadStarted.countDown();
430 <                    done.await();
430 >                    await(done);
431                  }});
432 <            assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS));
432 >            await(threadStarted);
433              assertEquals(1, p.getTaskCount());
434              assertEquals(0, p.getCompletedTaskCount());
435              for (int i = 0; i < TASKS; i++) {
# Line 422 | Line 438 | public class ThreadPoolExecutorTest exte
438                      public void realRun() throws InterruptedException {
439                          threadStarted.countDown();
440                          assertEquals(1 + TASKS, p.getTaskCount());
441 <                        done.await();
441 >                        await(done);
442                      }});
443              }
444              assertEquals(1 + TASKS, p.getTaskCount());
# Line 461 | Line 477 | public class ThreadPoolExecutorTest exte
477              assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
478              assertFalse(p.awaitTermination(-1L, NANOSECONDS));
479              assertFalse(p.awaitTermination(-1L, MILLISECONDS));
480 <            assertFalse(p.awaitTermination(0L, NANOSECONDS));
481 <            assertFalse(p.awaitTermination(0L, MILLISECONDS));
480 >            assertFalse(p.awaitTermination(randomExpiredTimeout(),
481 >                                           randomTimeUnit()));
482              long timeoutNanos = 999999L;
483              long startTime = System.nanoTime();
484              assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
# Line 495 | Line 511 | public class ThreadPoolExecutorTest exte
511                  public void realRun() throws InterruptedException {
512                      assertFalse(p.isTerminating());
513                      threadStarted.countDown();
514 <                    done.await();
514 >                    await(done);
515                  }});
516 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
516 >            await(threadStarted);
517              assertFalse(p.isTerminating());
518              done.countDown();
519              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 523 | Line 539 | public class ThreadPoolExecutorTest exte
539                  public void realRun() throws InterruptedException {
540                      assertFalse(p.isTerminating());
541                      threadStarted.countDown();
542 <                    done.await();
542 >                    await(done);
543                  }});
544 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
544 >            await(threadStarted);
545              assertFalse(p.isTerminating());
546              done.countDown();
547              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 539 | Line 555 | public class ThreadPoolExecutorTest exte
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 <        try (PoolCleaner cleaner = cleaner(p)) {
564 >        try (PoolCleaner cleaner = cleaner(p, done)) {
565              final CountDownLatch threadStarted = new CountDownLatch(1);
566 <            final CountDownLatch done = new CountDownLatch(1);
567 <            FutureTask[] tasks = new FutureTask[5];
566 >            FutureTask[] rtasks = new FutureTask[5];
567 >            @SuppressWarnings("unchecked")
568 >            FutureTask<Boolean>[] tasks = (FutureTask<Boolean>[])rtasks;
569              for (int i = 0; i < tasks.length; i++) {
570 <                Callable task = new CheckedCallable<Boolean>() {
570 >                Callable<Boolean> task = new CheckedCallable<Boolean>() {
571                      public Boolean realCall() throws InterruptedException {
572                          threadStarted.countDown();
573                          assertSame(q, p.getQueue());
574 <                        done.await();
574 >                        await(done);
575                          return Boolean.TRUE;
576                      }};
577 <                tasks[i] = new FutureTask(task);
577 >                tasks[i] = new FutureTask<Boolean>(task);
578                  p.execute(tasks[i]);
579              }
580 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
580 >            await(threadStarted);
581              assertSame(q, p.getQueue());
582              assertFalse(q.contains(tasks[0]));
583              assertTrue(q.contains(tasks[tasks.length - 1]));
584              assertEquals(tasks.length - 1, q.size());
567            done.countDown();
585          }
586      }
587  
# Line 572 | Line 589 | public class ThreadPoolExecutorTest exte
589       * remove(task) removes queued task, and fails to remove active task
590       */
591      public void testRemove() throws InterruptedException {
592 <        BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
592 >        final CountDownLatch done = new CountDownLatch(1);
593 >        BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
594          final ThreadPoolExecutor p =
595              new ThreadPoolExecutor(1, 1,
596                                     LONG_DELAY_MS, MILLISECONDS,
597                                     q);
598 <        try (PoolCleaner cleaner = cleaner(p)) {
598 >        try (PoolCleaner cleaner = cleaner(p, done)) {
599              Runnable[] tasks = new Runnable[6];
600              final CountDownLatch threadStarted = new CountDownLatch(1);
583            final CountDownLatch done = new CountDownLatch(1);
601              for (int i = 0; i < tasks.length; i++) {
602                  tasks[i] = new CheckedRunnable() {
603                      public void realRun() throws InterruptedException {
604                          threadStarted.countDown();
605 <                        done.await();
605 >                        await(done);
606                      }};
607                  p.execute(tasks[i]);
608              }
609 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
609 >            await(threadStarted);
610              assertFalse(p.remove(tasks[0]));
611              assertTrue(q.contains(tasks[4]));
612              assertTrue(q.contains(tasks[3]));
# Line 599 | Line 616 | public class ThreadPoolExecutorTest exte
616              assertTrue(q.contains(tasks[3]));
617              assertTrue(p.remove(tasks[3]));
618              assertFalse(q.contains(tasks[3]));
602            done.countDown();
619          }
620      }
621  
# Line 609 | Line 625 | public class ThreadPoolExecutorTest exte
625      public void testPurge() throws InterruptedException {
626          final CountDownLatch threadStarted = new CountDownLatch(1);
627          final CountDownLatch done = new CountDownLatch(1);
628 <        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<Runnable>(10);
628 >        final BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(10);
629          final ThreadPoolExecutor p =
630              new ThreadPoolExecutor(1, 1,
631                                     LONG_DELAY_MS, MILLISECONDS,
632                                     q);
633          try (PoolCleaner cleaner = cleaner(p, done)) {
634 <            FutureTask[] tasks = new FutureTask[5];
634 >            FutureTask[] rtasks = new FutureTask[5];
635 >            @SuppressWarnings("unchecked")
636 >            FutureTask<Boolean>[] tasks = (FutureTask<Boolean>[])rtasks;
637              for (int i = 0; i < tasks.length; i++) {
638 <                Callable task = new CheckedCallable<Boolean>() {
638 >                Callable<Boolean> task = new CheckedCallable<Boolean>() {
639                      public Boolean realCall() throws InterruptedException {
640                          threadStarted.countDown();
641 <                        done.await();
641 >                        await(done);
642                          return Boolean.TRUE;
643                      }};
644 <                tasks[i] = new FutureTask(task);
644 >                tasks[i] = new FutureTask<Boolean>(task);
645                  p.execute(tasks[i]);
646              }
647 <            assertTrue(threadStarted.await(LONG_DELAY_MS, MILLISECONDS));
647 >            await(threadStarted);
648              assertEquals(tasks.length, p.getTaskCount());
649              assertEquals(tasks.length - 1, q.size());
650              assertEquals(1L, p.getActiveCount());
# Line 658 | Line 676 | public class ThreadPoolExecutorTest exte
676          Runnable waiter = new CheckedRunnable() { public void realRun() {
677              threadsStarted.countDown();
678              try {
679 <                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
679 >                MILLISECONDS.sleep(LONGER_DELAY_MS);
680              } catch (InterruptedException success) {}
681              ran.getAndIncrement();
682          }};
683          for (int i = 0; i < count; i++)
684              p.execute(waiter);
685 <        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
685 >        await(threadsStarted);
686          assertEquals(poolSize, p.getActiveCount());
687          assertEquals(0, p.getCompletedTaskCount());
688          final List<Runnable> queuedTasks;
# Line 745 | Line 763 | public class ThreadPoolExecutorTest exte
763      public void testConstructorNullPointerException() {
764          try {
765              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
766 <                                   (BlockingQueue) null);
766 >                                   (BlockingQueue<Runnable>) null);
767              shouldThrow();
768          } catch (NullPointerException success) {}
769      }
# Line 816 | Line 834 | public class ThreadPoolExecutorTest exte
834      public void testConstructorNullPointerException2() {
835          try {
836              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
837 <                                   (BlockingQueue) null,
837 >                                   (BlockingQueue<Runnable>) null,
838                                     new SimpleThreadFactory());
839              shouldThrow();
840          } catch (NullPointerException success) {}
# Line 900 | Line 918 | public class ThreadPoolExecutorTest exte
918      public void testConstructorNullPointerException4() {
919          try {
920              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
921 <                                   (BlockingQueue) null,
921 >                                   (BlockingQueue<Runnable>) null,
922                                     new NoOpREHandler());
923              shouldThrow();
924          } catch (NullPointerException success) {}
# Line 989 | Line 1007 | public class ThreadPoolExecutorTest exte
1007      public void testConstructorNullPointerException6() {
1008          try {
1009              new ThreadPoolExecutor(1, 2, 1L, SECONDS,
1010 <                                   (BlockingQueue) null,
1010 >                                   (BlockingQueue<Runnable>) null,
1011                                     new SimpleThreadFactory(),
1012                                     new NoOpREHandler());
1013              shouldThrow();
# Line 1026 | Line 1044 | public class ThreadPoolExecutorTest exte
1044       * get of submitted callable throws InterruptedException if interrupted
1045       */
1046      public void testInterruptedSubmit() throws InterruptedException {
1047 +        final CountDownLatch done = new CountDownLatch(1);
1048          final ThreadPoolExecutor p =
1049              new ThreadPoolExecutor(1, 1,
1050                                     60, SECONDS,
1051                                     new ArrayBlockingQueue<Runnable>(10));
1052  
1053 <        try (PoolCleaner cleaner = cleaner(p)) {
1053 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1054              final CountDownLatch threadStarted = new CountDownLatch(1);
1036            final CountDownLatch done = new CountDownLatch(1);
1055              Thread t = newStartedThread(new CheckedInterruptedRunnable() {
1056                  public void realRun() throws Exception {
1057 <                    Callable task = new CheckedCallable<Boolean>() {
1057 >                    Callable<Boolean> task = new CheckedCallable<Boolean>() {
1058                          public Boolean realCall() throws InterruptedException {
1059                              threadStarted.countDown();
1060 <                            done.await();
1060 >                            await(done);
1061                              return Boolean.TRUE;
1062                          }};
1063                      p.submit(task).get();
1064                  }});
1065  
1066 <            assertTrue(threadStarted.await(MEDIUM_DELAY_MS, MILLISECONDS));
1066 >            await(threadStarted); // ensure quiescence
1067              t.interrupt();
1068 <            awaitTermination(t, MEDIUM_DELAY_MS);
1051 <            done.countDown();
1068 >            awaitTermination(t);
1069          }
1070      }
1071  
1072      /**
1073 <     * execute throws RejectedExecutionException if saturated.
1073 >     * Submitted tasks are rejected when saturated or shutdown
1074       */
1075 <    public void testSaturatedExecute() {
1076 <        final ThreadPoolExecutor p =
1077 <            new ThreadPoolExecutor(1, 1,
1078 <                                   LONG_DELAY_MS, MILLISECONDS,
1079 <                                   new ArrayBlockingQueue<Runnable>(1));
1080 <        try (PoolCleaner cleaner = cleaner(p)) {
1081 <            final CountDownLatch done = new CountDownLatch(1);
1082 <            Runnable task = new CheckedRunnable() {
1083 <                public void realRun() throws InterruptedException {
1084 <                    done.await();
1068 <                }};
1069 <            for (int i = 0; i < 2; ++i)
1070 <                p.execute(task);
1071 <            for (int i = 0; i < 2; ++i) {
1075 >    public void testSubmittedTasksRejectedWhenSaturatedOrShutdown() throws InterruptedException {
1076 >        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1077 >            1, 1, 1, SECONDS, new ArrayBlockingQueue<Runnable>(1));
1078 >        final int saturatedSize = saturatedSize(p);
1079 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1080 >        final CountDownLatch threadsStarted = new CountDownLatch(p.getMaximumPoolSize());
1081 >        final CountDownLatch done = new CountDownLatch(1);
1082 >        final Runnable r = () -> {
1083 >            threadsStarted.countDown();
1084 >            for (;;) {
1085                  try {
1073                    p.execute(task);
1074                    shouldThrow();
1075                } catch (RejectedExecutionException success) {}
1076                assertTrue(p.getTaskCount() <= 2);
1077            }
1078            done.countDown();
1079        }
1080    }
1081
1082    /**
1083     * submit(runnable) throws RejectedExecutionException if saturated.
1084     */
1085    public void testSaturatedSubmitRunnable() {
1086        final ThreadPoolExecutor p =
1087            new ThreadPoolExecutor(1, 1,
1088                                   LONG_DELAY_MS, MILLISECONDS,
1089                                   new ArrayBlockingQueue<Runnable>(1));
1090        try (PoolCleaner cleaner = cleaner(p)) {
1091            final CountDownLatch done = new CountDownLatch(1);
1092            Runnable task = new CheckedRunnable() {
1093                public void realRun() throws InterruptedException {
1086                      done.await();
1087 <                }};
1088 <            for (int i = 0; i < 2; ++i)
1089 <                p.submit(task);
1090 <            for (int i = 0; i < 2; ++i) {
1087 >                    return;
1088 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1089 >            }};
1090 >        final Callable<Boolean> c = () -> {
1091 >            threadsStarted.countDown();
1092 >            for (;;) {
1093                  try {
1100                    p.execute(task);
1101                    shouldThrow();
1102                } catch (RejectedExecutionException success) {}
1103                assertTrue(p.getTaskCount() <= 2);
1104            }
1105            done.countDown();
1106        }
1107    }
1108
1109    /**
1110     * submit(callable) throws RejectedExecutionException if saturated.
1111     */
1112    public void testSaturatedSubmitCallable() {
1113        final ThreadPoolExecutor p =
1114            new ThreadPoolExecutor(1, 1,
1115                                   LONG_DELAY_MS, MILLISECONDS,
1116                                   new ArrayBlockingQueue<Runnable>(1));
1117        try (PoolCleaner cleaner = cleaner(p)) {
1118            final CountDownLatch done = new CountDownLatch(1);
1119            Runnable task = new CheckedRunnable() {
1120                public void realRun() throws InterruptedException {
1094                      done.await();
1095 <                }};
1096 <            for (int i = 0; i < 2; ++i)
1097 <                p.submit(Executors.callable(task));
1098 <            for (int i = 0; i < 2; ++i) {
1099 <                try {
1100 <                    p.execute(task);
1101 <                    shouldThrow();
1102 <                } catch (RejectedExecutionException success) {}
1103 <                assertTrue(p.getTaskCount() <= 2);
1095 >                    return Boolean.TRUE;
1096 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1097 >            }};
1098 >        final boolean shutdownNow = rnd.nextBoolean();
1099 >
1100 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1101 >            // saturate
1102 >            for (int i = saturatedSize; i--> 0; ) {
1103 >                switch (rnd.nextInt(4)) {
1104 >                case 0: p.execute(r); break;
1105 >                case 1: assertFalse(p.submit(r).isDone()); break;
1106 >                case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
1107 >                case 3: assertFalse(p.submit(c).isDone()); break;
1108 >                }
1109              }
1132            done.countDown();
1133        }
1134    }
1110  
1111 <    /**
1112 <     * executor using CallerRunsPolicy runs task if saturated.
1138 <     */
1139 <    public void testSaturatedExecute2() {
1140 <        final ThreadPoolExecutor p =
1141 <            new ThreadPoolExecutor(1, 1,
1142 <                                   LONG_DELAY_MS,
1143 <                                   MILLISECONDS,
1144 <                                   new ArrayBlockingQueue<Runnable>(1),
1145 <                                   new ThreadPoolExecutor.CallerRunsPolicy());
1146 <        try (PoolCleaner cleaner = cleaner(p)) {
1147 <            final CountDownLatch done = new CountDownLatch(1);
1148 <            Runnable blocker = new CheckedRunnable() {
1149 <                public void realRun() throws InterruptedException {
1150 <                    done.await();
1151 <                }};
1152 <            p.execute(blocker);
1153 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1154 <            for (int i = 0; i < tasks.length; i++)
1155 <                tasks[i] = new TrackedNoOpRunnable();
1156 <            for (int i = 0; i < tasks.length; i++)
1157 <                p.execute(tasks[i]);
1158 <            for (int i = 1; i < tasks.length; i++)
1159 <                assertTrue(tasks[i].done);
1160 <            assertFalse(tasks[0].done); // waiting in queue
1161 <            done.countDown();
1162 <        }
1163 <    }
1111 >            await(threadsStarted);
1112 >            assertTaskSubmissionsAreRejected(p);
1113  
1114 <    /**
1115 <     * executor using DiscardPolicy drops task if saturated.
1116 <     */
1117 <    public void testSaturatedExecute3() {
1118 <        final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1119 <        for (int i = 0; i < tasks.length; ++i)
1120 <            tasks[i] = new TrackedNoOpRunnable();
1172 <        final ThreadPoolExecutor p =
1173 <            new ThreadPoolExecutor(1, 1,
1174 <                          LONG_DELAY_MS, MILLISECONDS,
1175 <                          new ArrayBlockingQueue<Runnable>(1),
1176 <                          new ThreadPoolExecutor.DiscardPolicy());
1177 <        try (PoolCleaner cleaner = cleaner(p)) {
1178 <            final CountDownLatch done = new CountDownLatch(1);
1179 <            p.execute(awaiter(done));
1114 >            if (shutdownNow)
1115 >                p.shutdownNow();
1116 >            else
1117 >                p.shutdown();
1118 >            // Pool is shutdown, but not yet terminated
1119 >            assertTaskSubmissionsAreRejected(p);
1120 >            assertFalse(p.isTerminated());
1121  
1122 <            for (TrackedNoOpRunnable task : tasks)
1123 <                p.execute(task);
1124 <            for (int i = 1; i < tasks.length; i++)
1125 <                assertFalse(tasks[i].done);
1185 <            done.countDown();
1122 >            done.countDown();   // release blocking tasks
1123 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
1124 >
1125 >            assertTaskSubmissionsAreRejected(p);
1126          }
1127 <        for (int i = 1; i < tasks.length; i++)
1128 <            assertFalse(tasks[i].done);
1129 <        assertTrue(tasks[0].done); // was waiting in queue
1127 >        assertEquals(saturatedSize(p)
1128 >                     - (shutdownNow ? p.getQueue().remainingCapacity() : 0),
1129 >                     p.getCompletedTaskCount());
1130      }
1131  
1132      /**
1133       * executor using DiscardOldestPolicy drops oldest task if saturated.
1134       */
1135 <    public void testSaturatedExecute4() {
1135 >    public void testSaturatedExecute_DiscardOldestPolicy() {
1136          final CountDownLatch done = new CountDownLatch(1);
1137          LatchAwaiter r1 = awaiter(done);
1138          LatchAwaiter r2 = awaiter(done);
# Line 1201 | Line 1141 | public class ThreadPoolExecutorTest exte
1141              new ThreadPoolExecutor(1, 1,
1142                                     LONG_DELAY_MS, MILLISECONDS,
1143                                     new ArrayBlockingQueue<Runnable>(1),
1144 <                                   new ThreadPoolExecutor.DiscardOldestPolicy());
1145 <        try (PoolCleaner cleaner = cleaner(p)) {
1144 >                                   new DiscardOldestPolicy());
1145 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1146              assertEquals(LatchAwaiter.NEW, r1.state);
1147              assertEquals(LatchAwaiter.NEW, r2.state);
1148              assertEquals(LatchAwaiter.NEW, r3.state);
# Line 1212 | Line 1152 | public class ThreadPoolExecutorTest exte
1152              p.execute(r3);
1153              assertFalse(p.getQueue().contains(r2));
1154              assertTrue(p.getQueue().contains(r3));
1215            done.countDown();
1155          }
1156          assertEquals(LatchAwaiter.DONE, r1.state);
1157          assertEquals(LatchAwaiter.NEW, r2.state);
# Line 1220 | Line 1159 | public class ThreadPoolExecutorTest exte
1159      }
1160  
1161      /**
1223     * execute throws RejectedExecutionException if shutdown
1224     */
1225    public void testRejectedExecutionExceptionOnShutdown() {
1226        final ThreadPoolExecutor p =
1227            new ThreadPoolExecutor(1, 1,
1228                                   LONG_DELAY_MS, MILLISECONDS,
1229                                   new ArrayBlockingQueue<Runnable>(1));
1230        try { p.shutdown(); } catch (SecurityException ok) { return; }
1231        try (PoolCleaner cleaner = cleaner(p)) {
1232            try {
1233                p.execute(new NoOpRunnable());
1234                shouldThrow();
1235            } catch (RejectedExecutionException success) {}
1236        }
1237    }
1238
1239    /**
1240     * execute using CallerRunsPolicy drops task on shutdown
1241     */
1242    public void testCallerRunsOnShutdown() {
1243        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1244        final ThreadPoolExecutor p =
1245            new ThreadPoolExecutor(1, 1,
1246                                   LONG_DELAY_MS, MILLISECONDS,
1247                                   new ArrayBlockingQueue<Runnable>(1), h);
1248
1249        try { p.shutdown(); } catch (SecurityException ok) { return; }
1250        try (PoolCleaner cleaner = cleaner(p)) {
1251            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1252            p.execute(r);
1253            assertFalse(r.done);
1254        }
1255    }
1256
1257    /**
1258     * execute using DiscardPolicy drops task on shutdown
1259     */
1260    public void testDiscardOnShutdown() {
1261        final ThreadPoolExecutor p =
1262            new ThreadPoolExecutor(1, 1,
1263                                   LONG_DELAY_MS, MILLISECONDS,
1264                                   new ArrayBlockingQueue<Runnable>(1),
1265                                   new ThreadPoolExecutor.DiscardPolicy());
1266
1267        try { p.shutdown(); } catch (SecurityException ok) { return; }
1268        try (PoolCleaner cleaner = cleaner(p)) {
1269            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1270            p.execute(r);
1271            assertFalse(r.done);
1272        }
1273    }
1274
1275    /**
1162       * execute using DiscardOldestPolicy drops task on shutdown
1163       */
1164      public void testDiscardOldestOnShutdown() {
# Line 1280 | Line 1166 | public class ThreadPoolExecutorTest exte
1166              new ThreadPoolExecutor(1, 1,
1167                                     LONG_DELAY_MS, MILLISECONDS,
1168                                     new ArrayBlockingQueue<Runnable>(1),
1169 <                                   new ThreadPoolExecutor.DiscardOldestPolicy());
1169 >                                   new DiscardOldestPolicy());
1170  
1171          try { p.shutdown(); } catch (SecurityException ok) { return; }
1172          try (PoolCleaner cleaner = cleaner(p)) {
# Line 1291 | Line 1177 | public class ThreadPoolExecutorTest exte
1177      }
1178  
1179      /**
1180 <     * execute(null) throws NPE
1180 >     * Submitting null tasks throws NullPointerException
1181       */
1182 <    public void testExecuteNull() {
1182 >    public void testNullTaskSubmission() {
1183          final ThreadPoolExecutor p =
1184              new ThreadPoolExecutor(1, 2,
1185                                     1L, SECONDS,
1186                                     new ArrayBlockingQueue<Runnable>(10));
1187          try (PoolCleaner cleaner = cleaner(p)) {
1188 <            try {
1303 <                p.execute(null);
1304 <                shouldThrow();
1305 <            } catch (NullPointerException success) {}
1188 >            assertNullTaskSubmissionThrowsNullPointerException(p);
1189          }
1190      }
1191  
# Line 1494 | Line 1377 | public class ThreadPoolExecutorTest exte
1377      }
1378  
1379      /**
1380 <     * invokeAny(empty collection) throws IAE
1380 >     * invokeAny(empty collection) throws IllegalArgumentException
1381       */
1382      public void testInvokeAny2() throws Exception {
1383          final ExecutorService e =
# Line 1519 | Line 1402 | public class ThreadPoolExecutorTest exte
1402                                     LONG_DELAY_MS, MILLISECONDS,
1403                                     new ArrayBlockingQueue<Runnable>(10));
1404          try (PoolCleaner cleaner = cleaner(e)) {
1405 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1405 >            List<Callable<String>> l = new ArrayList<>();
1406              l.add(latchAwaitingStringTask(latch));
1407              l.add(null);
1408              try {
# Line 1539 | Line 1422 | public class ThreadPoolExecutorTest exte
1422                                     LONG_DELAY_MS, MILLISECONDS,
1423                                     new ArrayBlockingQueue<Runnable>(10));
1424          try (PoolCleaner cleaner = cleaner(e)) {
1425 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1425 >            List<Callable<String>> l = new ArrayList<>();
1426              l.add(new NPETask());
1427              try {
1428                  e.invokeAny(l);
# Line 1559 | Line 1442 | public class ThreadPoolExecutorTest exte
1442                                     LONG_DELAY_MS, MILLISECONDS,
1443                                     new ArrayBlockingQueue<Runnable>(10));
1444          try (PoolCleaner cleaner = cleaner(e)) {
1445 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1445 >            List<Callable<String>> l = new ArrayList<>();
1446              l.add(new StringTask());
1447              l.add(new StringTask());
1448              String result = e.invokeAny(l);
# Line 1584 | Line 1467 | public class ThreadPoolExecutorTest exte
1467      }
1468  
1469      /**
1470 <     * invokeAll(empty collection) returns empty collection
1470 >     * invokeAll(empty collection) returns empty list
1471       */
1472      public void testInvokeAll2() throws InterruptedException {
1473          final ExecutorService e =
1474              new ThreadPoolExecutor(2, 2,
1475                                     LONG_DELAY_MS, MILLISECONDS,
1476                                     new ArrayBlockingQueue<Runnable>(10));
1477 +        final Collection<Callable<String>> emptyCollection
1478 +            = Collections.emptyList();
1479          try (PoolCleaner cleaner = cleaner(e)) {
1480 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1480 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1481              assertTrue(r.isEmpty());
1482          }
1483      }
# Line 1606 | Line 1491 | public class ThreadPoolExecutorTest exte
1491                                     LONG_DELAY_MS, MILLISECONDS,
1492                                     new ArrayBlockingQueue<Runnable>(10));
1493          try (PoolCleaner cleaner = cleaner(e)) {
1494 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1494 >            List<Callable<String>> l = new ArrayList<>();
1495              l.add(new StringTask());
1496              l.add(null);
1497              try {
# Line 1625 | Line 1510 | public class ThreadPoolExecutorTest exte
1510                                     LONG_DELAY_MS, MILLISECONDS,
1511                                     new ArrayBlockingQueue<Runnable>(10));
1512          try (PoolCleaner cleaner = cleaner(e)) {
1513 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1513 >            List<Callable<String>> l = new ArrayList<>();
1514              l.add(new NPETask());
1515              List<Future<String>> futures = e.invokeAll(l);
1516              assertEquals(1, futures.size());
# Line 1647 | Line 1532 | public class ThreadPoolExecutorTest exte
1532                                     LONG_DELAY_MS, MILLISECONDS,
1533                                     new ArrayBlockingQueue<Runnable>(10));
1534          try (PoolCleaner cleaner = cleaner(e)) {
1535 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1535 >            List<Callable<String>> l = new ArrayList<>();
1536              l.add(new StringTask());
1537              l.add(new StringTask());
1538              List<Future<String>> futures = e.invokeAll(l);
# Line 1667 | Line 1552 | public class ThreadPoolExecutorTest exte
1552                                     new ArrayBlockingQueue<Runnable>(10));
1553          try (PoolCleaner cleaner = cleaner(e)) {
1554              try {
1555 <                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1555 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1556                  shouldThrow();
1557              } catch (NullPointerException success) {}
1558          }
# Line 1682 | Line 1567 | public class ThreadPoolExecutorTest exte
1567                                     LONG_DELAY_MS, MILLISECONDS,
1568                                     new ArrayBlockingQueue<Runnable>(10));
1569          try (PoolCleaner cleaner = cleaner(e)) {
1570 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1570 >            List<Callable<String>> l = new ArrayList<>();
1571              l.add(new StringTask());
1572              try {
1573 <                e.invokeAny(l, MEDIUM_DELAY_MS, null);
1573 >                e.invokeAny(l, randomTimeout(), null);
1574                  shouldThrow();
1575              } catch (NullPointerException success) {}
1576          }
1577      }
1578  
1579      /**
1580 <     * timed invokeAny(empty collection) throws IAE
1580 >     * timed invokeAny(empty collection) throws IllegalArgumentException
1581       */
1582      public void testTimedInvokeAny2() throws Exception {
1583          final ExecutorService e =
# Line 1702 | Line 1587 | public class ThreadPoolExecutorTest exte
1587          try (PoolCleaner cleaner = cleaner(e)) {
1588              try {
1589                  e.invokeAny(new ArrayList<Callable<String>>(),
1590 <                            MEDIUM_DELAY_MS, MILLISECONDS);
1590 >                            randomTimeout(), randomTimeUnit());
1591                  shouldThrow();
1592              } catch (IllegalArgumentException success) {}
1593          }
1594      }
1595  
1596      /**
1597 <     * timed invokeAny(c) throws NPE if c has null elements
1597 >     * timed invokeAny(c) throws NullPointerException if c has null elements
1598       */
1599      public void testTimedInvokeAny3() throws Exception {
1600          final CountDownLatch latch = new CountDownLatch(1);
# Line 1718 | Line 1603 | public class ThreadPoolExecutorTest exte
1603                                     LONG_DELAY_MS, MILLISECONDS,
1604                                     new ArrayBlockingQueue<Runnable>(10));
1605          try (PoolCleaner cleaner = cleaner(e)) {
1606 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1606 >            List<Callable<String>> l = new ArrayList<>();
1607              l.add(latchAwaitingStringTask(latch));
1608              l.add(null);
1609              try {
1610 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1610 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1611                  shouldThrow();
1612              } catch (NullPointerException success) {}
1613              latch.countDown();
# Line 1738 | Line 1623 | public class ThreadPoolExecutorTest exte
1623                                     LONG_DELAY_MS, MILLISECONDS,
1624                                     new ArrayBlockingQueue<Runnable>(10));
1625          try (PoolCleaner cleaner = cleaner(e)) {
1626 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1626 >            long startTime = System.nanoTime();
1627 >            List<Callable<String>> l = new ArrayList<>();
1628              l.add(new NPETask());
1629              try {
1630 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1630 >                e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1631                  shouldThrow();
1632              } catch (ExecutionException success) {
1633                  assertTrue(success.getCause() instanceof NullPointerException);
1634              }
1635 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1636          }
1637      }
1638  
# Line 1758 | Line 1645 | public class ThreadPoolExecutorTest exte
1645                                     LONG_DELAY_MS, MILLISECONDS,
1646                                     new ArrayBlockingQueue<Runnable>(10));
1647          try (PoolCleaner cleaner = cleaner(e)) {
1648 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1648 >            long startTime = System.nanoTime();
1649 >            List<Callable<String>> l = new ArrayList<>();
1650              l.add(new StringTask());
1651              l.add(new StringTask());
1652 <            String result = e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1652 >            String result = e.invokeAny(l, LONG_DELAY_MS, MILLISECONDS);
1653              assertSame(TEST_STRING, result);
1654 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1655          }
1656      }
1657  
# Line 1776 | Line 1665 | public class ThreadPoolExecutorTest exte
1665                                     new ArrayBlockingQueue<Runnable>(10));
1666          try (PoolCleaner cleaner = cleaner(e)) {
1667              try {
1668 <                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1668 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1669                  shouldThrow();
1670              } catch (NullPointerException success) {}
1671          }
# Line 1791 | Line 1680 | public class ThreadPoolExecutorTest exte
1680                                     LONG_DELAY_MS, MILLISECONDS,
1681                                     new ArrayBlockingQueue<Runnable>(10));
1682          try (PoolCleaner cleaner = cleaner(e)) {
1683 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1683 >            List<Callable<String>> l = new ArrayList<>();
1684              l.add(new StringTask());
1685              try {
1686 <                e.invokeAll(l, MEDIUM_DELAY_MS, null);
1686 >                e.invokeAll(l, randomTimeout(), null);
1687                  shouldThrow();
1688              } catch (NullPointerException success) {}
1689          }
1690      }
1691  
1692      /**
1693 <     * timed invokeAll(empty collection) returns empty collection
1693 >     * timed invokeAll(empty collection) returns empty list
1694       */
1695      public void testTimedInvokeAll2() throws InterruptedException {
1696          final ExecutorService e =
1697              new ThreadPoolExecutor(2, 2,
1698                                     LONG_DELAY_MS, MILLISECONDS,
1699                                     new ArrayBlockingQueue<Runnable>(10));
1700 +        final Collection<Callable<String>> emptyCollection
1701 +            = Collections.emptyList();
1702          try (PoolCleaner cleaner = cleaner(e)) {
1703 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1704 <                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1703 >            List<Future<String>> r =
1704 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1705              assertTrue(r.isEmpty());
1706          }
1707      }
# Line 1824 | Line 1715 | public class ThreadPoolExecutorTest exte
1715                                     LONG_DELAY_MS, MILLISECONDS,
1716                                     new ArrayBlockingQueue<Runnable>(10));
1717          try (PoolCleaner cleaner = cleaner(e)) {
1718 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1718 >            List<Callable<String>> l = new ArrayList<>();
1719              l.add(new StringTask());
1720              l.add(null);
1721              try {
1722 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1722 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1723                  shouldThrow();
1724              } catch (NullPointerException success) {}
1725          }
# Line 1843 | Line 1734 | public class ThreadPoolExecutorTest exte
1734                                     LONG_DELAY_MS, MILLISECONDS,
1735                                     new ArrayBlockingQueue<Runnable>(10));
1736          try (PoolCleaner cleaner = cleaner(e)) {
1737 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1737 >            List<Callable<String>> l = new ArrayList<>();
1738              l.add(new NPETask());
1739              List<Future<String>> futures =
1740 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1740 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1741              assertEquals(1, futures.size());
1742              try {
1743                  futures.get(0).get();
# Line 1866 | Line 1757 | public class ThreadPoolExecutorTest exte
1757                                     LONG_DELAY_MS, MILLISECONDS,
1758                                     new ArrayBlockingQueue<Runnable>(10));
1759          try (PoolCleaner cleaner = cleaner(e)) {
1760 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1760 >            List<Callable<String>> l = new ArrayList<>();
1761              l.add(new StringTask());
1762              l.add(new StringTask());
1763              List<Future<String>> futures =
# Line 1881 | Line 1772 | public class ThreadPoolExecutorTest exte
1772       * timed invokeAll(c) cancels tasks not completed by timeout
1773       */
1774      public void testTimedInvokeAll6() throws Exception {
1775 <        final ExecutorService e =
1776 <            new ThreadPoolExecutor(2, 2,
1777 <                                   LONG_DELAY_MS, MILLISECONDS,
1778 <                                   new ArrayBlockingQueue<Runnable>(10));
1779 <        try (PoolCleaner cleaner = cleaner(e)) {
1780 <            for (long timeout = timeoutMillis();;) {
1775 >        for (long timeout = timeoutMillis();;) {
1776 >            final CountDownLatch done = new CountDownLatch(1);
1777 >            final Callable<String> waiter = new CheckedCallable<String>() {
1778 >                public String realCall() {
1779 >                    try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1780 >                    catch (InterruptedException ok) {}
1781 >                    return "1"; }};
1782 >            final ExecutorService p =
1783 >                new ThreadPoolExecutor(2, 2,
1784 >                                       LONG_DELAY_MS, MILLISECONDS,
1785 >                                       new ArrayBlockingQueue<Runnable>(10));
1786 >            try (PoolCleaner cleaner = cleaner(p, done)) {
1787                  List<Callable<String>> tasks = new ArrayList<>();
1788                  tasks.add(new StringTask("0"));
1789 <                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1789 >                tasks.add(waiter);
1790                  tasks.add(new StringTask("2"));
1791                  long startTime = System.nanoTime();
1792                  List<Future<String>> futures =
1793 <                    e.invokeAll(tasks, timeout, MILLISECONDS);
1793 >                    p.invokeAll(tasks, timeout, MILLISECONDS);
1794                  assertEquals(tasks.size(), futures.size());
1795                  assertTrue(millisElapsedSince(startTime) >= timeout);
1796 <                for (Future future : futures)
1796 >                for (Future<?> future : futures)
1797                      assertTrue(future.isDone());
1798                  assertTrue(futures.get(1).isCancelled());
1799                  try {
# Line 1930 | Line 1827 | public class ThreadPoolExecutorTest exte
1827                      public void realRun() {
1828                          done.countDown();
1829                      }});
1830 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1830 >            await(done);
1831          }
1832      }
1833  
# Line 2011 | Line 1908 | public class ThreadPoolExecutorTest exte
1908          final ThreadPoolExecutor p =
1909              new ThreadPoolExecutor(1, 30,
1910                                     60, SECONDS,
1911 <                                   new ArrayBlockingQueue(30));
1911 >                                   new ArrayBlockingQueue<Runnable>(30));
1912          try (PoolCleaner cleaner = cleaner(p)) {
1913              for (int i = 0; i < nTasks; ++i) {
1914                  for (;;) {
# Line 2023 | Line 1920 | public class ThreadPoolExecutorTest exte
1920                  }
1921              }
1922              // enough time to run all tasks
1923 <            assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS));
1923 >            await(done, nTasks * SHORT_DELAY_MS);
1924          }
1925      }
1926  
# Line 2031 | Line 1928 | public class ThreadPoolExecutorTest exte
1928       * get(cancelled task) throws CancellationException
1929       */
1930      public void testGet_cancelled() throws Exception {
1931 +        final CountDownLatch done = new CountDownLatch(1);
1932          final ExecutorService e =
1933              new ThreadPoolExecutor(1, 1,
1934                                     LONG_DELAY_MS, MILLISECONDS,
1935                                     new LinkedBlockingQueue<Runnable>());
1936 <        try (PoolCleaner cleaner = cleaner(e)) {
1936 >        try (PoolCleaner cleaner = cleaner(e, done)) {
1937              final CountDownLatch blockerStarted = new CountDownLatch(1);
2040            final CountDownLatch done = new CountDownLatch(1);
1938              final List<Future<?>> futures = new ArrayList<>();
1939              for (int i = 0; i < 2; i++) {
1940                  Runnable r = new CheckedRunnable() { public void realRun()
# Line 2047 | Line 1944 | public class ThreadPoolExecutorTest exte
1944                  }};
1945                  futures.add(e.submit(r));
1946              }
1947 <            assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS));
1947 >            await(blockerStarted);
1948              for (Future<?> future : futures) future.cancel(false);
1949              for (Future<?> future : futures) {
1950                  try {
# Line 2061 | Line 1958 | public class ThreadPoolExecutorTest exte
1958                  assertTrue(future.isCancelled());
1959                  assertTrue(future.isDone());
1960              }
1961 <            done.countDown();
1961 >        }
1962 >    }
1963 >
1964 >    /** Directly test simple ThreadPoolExecutor RejectedExecutionHandlers. */
1965 >    public void testStandardRejectedExecutionHandlers() {
1966 >        final ThreadPoolExecutor p =
1967 >            new ThreadPoolExecutor(1, 1, 1, SECONDS,
1968 >                                   new ArrayBlockingQueue<Runnable>(1));
1969 >        final AtomicReference<Thread> thread = new AtomicReference<>();
1970 >        final Runnable r = new Runnable() { public void run() {
1971 >            thread.set(Thread.currentThread()); }};
1972 >
1973 >        try {
1974 >            new AbortPolicy().rejectedExecution(r, p);
1975 >            shouldThrow();
1976 >        } catch (RejectedExecutionException success) {}
1977 >        assertNull(thread.get());
1978 >
1979 >        new DiscardPolicy().rejectedExecution(r, p);
1980 >        assertNull(thread.get());
1981 >
1982 >        new CallerRunsPolicy().rejectedExecution(r, p);
1983 >        assertSame(Thread.currentThread(), thread.get());
1984 >
1985 >        // check that pool was not perturbed by handlers
1986 >        assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
1987 >        assertEquals(0, p.getTaskCount());
1988 >        assertTrue(p.getQueue().isEmpty());
1989 >    }
1990 >
1991 >    public void testThreadFactoryReturnsTerminatedThread_shouldThrow() {
1992 >        if (!testImplementationDetails)
1993 >            return;
1994 >
1995 >        ThreadFactory returnsTerminatedThread = runnableIgnored -> {
1996 >            Thread thread = new Thread(() -> {});
1997 >            thread.start();
1998 >            try { thread.join(); }
1999 >            catch (InterruptedException ex) { throw new Error(ex); }
2000 >            return thread;
2001 >        };
2002 >        ThreadPoolExecutor p =
2003 >            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2004 >                                   new ArrayBlockingQueue<Runnable>(1),
2005 >                                   returnsTerminatedThread);
2006 >        try (PoolCleaner cleaner = cleaner(p)) {
2007 >            assertThrows(IllegalThreadStateException.class,
2008 >                         () -> p.execute(() -> {}));
2009 >        }
2010 >    }
2011 >
2012 >    public void testThreadFactoryReturnsStartedThread_shouldThrow() {
2013 >        if (!testImplementationDetails)
2014 >            return;
2015 >
2016 >        CountDownLatch latch = new CountDownLatch(1);
2017 >        Runnable awaitLatch = () -> {
2018 >            try { latch.await(); }
2019 >            catch (InterruptedException ex) { throw new Error(ex); }};
2020 >        ThreadFactory returnsStartedThread = runnable -> {
2021 >            Thread thread = new Thread(awaitLatch);
2022 >            thread.start();
2023 >            return thread;
2024 >        };
2025 >        ThreadPoolExecutor p =
2026 >            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2027 >                                   new ArrayBlockingQueue<Runnable>(1),
2028 >                                   returnsStartedThread);
2029 >        try (PoolCleaner cleaner = cleaner(p)) {
2030 >            assertThrows(IllegalThreadStateException.class,
2031 >                         () -> p.execute(() -> {}));
2032 >            latch.countDown();
2033          }
2034      }
2035  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines