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.103 by jsr166, Mon Oct 5 22:19:00 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 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(LONG_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 341 | Line 359 | public class ThreadPoolExecutorTest exte
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(LONG_DELAY_MS, MILLISECONDS));
365 >            await(threadsStarted);
366              assertEquals(THREADS, p.getLargestPoolSize());
367          }
368          assertEquals(THREADS, p.getLargestPoolSize());
# Line 385 | Line 403 | public class ThreadPoolExecutorTest exte
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(LONG_DELAY_MS, MILLISECONDS));
408 >            await(threadStarted);
409              assertEquals(1, p.getPoolSize());
410          }
411      }
# Line 409 | 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 420 | 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 459 | 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 493 | 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(LONG_DELAY_MS, MILLISECONDS));
516 >            await(threadStarted);
517              assertFalse(p.isTerminating());
518              done.countDown();
519              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 521 | 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(LONG_DELAY_MS, MILLISECONDS));
544 >            await(threadStarted);
545              assertFalse(p.isTerminating());
546              done.countDown();
547              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 537 | 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);
547            final CountDownLatch done = 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(LONG_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());
565            done.countDown();
583          }
584      }
585  
# Line 570 | 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 <        try (PoolCleaner cleaner = cleaner(p)) {
596 >        try (PoolCleaner cleaner = cleaner(p, done)) {
597              Runnable[] tasks = new Runnable[6];
598              final CountDownLatch threadStarted = new CountDownLatch(1);
581            final CountDownLatch done = 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(LONG_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 597 | Line 614 | public class ThreadPoolExecutorTest exte
614              assertTrue(q.contains(tasks[3]));
615              assertTrue(p.remove(tasks[3]));
616              assertFalse(q.contains(tasks[3]));
600            done.countDown();
617          }
618      }
619  
# Line 607 | 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,
# Line 618 | Line 634 | public class ThreadPoolExecutorTest exte
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(LONG_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 662 | 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 1024 | 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 <        try (PoolCleaner cleaner = cleaner(p)) {
1049 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1050              final CountDownLatch threadStarted = new CountDownLatch(1);
1034            final CountDownLatch done = 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(LONG_DELAY_MS, MILLISECONDS));
1062 >            await(threadStarted);
1063              t.interrupt();
1064 <            awaitTermination(t, MEDIUM_DELAY_MS);
1049 <            done.countDown();
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 <        final ThreadPoolExecutor p =
1073 <            new ThreadPoolExecutor(1, 1,
1074 <                                   LONG_DELAY_MS, MILLISECONDS,
1075 <                                   new ArrayBlockingQueue<Runnable>(1));
1076 <        try (PoolCleaner cleaner = cleaner(p)) {
1077 <            final CountDownLatch done = new CountDownLatch(1);
1078 <            Runnable task = new CheckedRunnable() {
1079 <                public void realRun() throws InterruptedException {
1080 <                    done.await();
1081 <                }};
1082 <            for (int i = 0; i < 2; ++i)
1083 <                p.execute(task);
1084 <            for (int i = 0; i < 2; ++i) {
1071 >    @SuppressWarnings("FutureReturnValueIgnored")
1072 >    public void testSubmittedTasksRejectedWhenSaturated() {
1073 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1074 >        final CountDownLatch done = new CountDownLatch(1);
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            done.countDown();
1077        }
1078    }
1079
1080    /**
1081     * submit(runnable) throws RejectedExecutionException if saturated.
1082     */
1083    public void testSaturatedSubmitRunnable() {
1084        final ThreadPoolExecutor p =
1085            new ThreadPoolExecutor(1, 1,
1086                                   LONG_DELAY_MS, MILLISECONDS,
1087                                   new ArrayBlockingQueue<Runnable>(1));
1088        try (PoolCleaner cleaner = cleaner(p)) {
1089            final CountDownLatch done = new CountDownLatch(1);
1090            Runnable task = new CheckedRunnable() {
1091                public void realRun() throws InterruptedException {
1092                    done.await();
1093                }};
1094            for (int i = 0; i < 2; ++i)
1095                p.submit(task);
1096            for (int i = 0; i < 2; ++i) {
1101                  try {
1102 <                    p.execute(task);
1102 >                    p.submit(r);
1103                      shouldThrow();
1104                  } catch (RejectedExecutionException success) {}
1101                assertTrue(p.getTaskCount() <= 2);
1102            }
1103            done.countDown();
1104        }
1105    }
1106
1107    /**
1108     * submit(callable) throws RejectedExecutionException if saturated.
1109     */
1110    public void testSaturatedSubmitCallable() {
1111        final ThreadPoolExecutor p =
1112            new ThreadPoolExecutor(1, 1,
1113                                   LONG_DELAY_MS, MILLISECONDS,
1114                                   new ArrayBlockingQueue<Runnable>(1));
1115        try (PoolCleaner cleaner = cleaner(p)) {
1116            final CountDownLatch done = new CountDownLatch(1);
1117            Runnable task = new CheckedRunnable() {
1118                public void realRun() throws InterruptedException {
1119                    done.await();
1120                }};
1121            for (int i = 0; i < 2; ++i)
1122                p.submit(Executors.callable(task));
1123            for (int i = 0; i < 2; ++i) {
1105                  try {
1106 <                    p.execute(task);
1106 >                    p.submit(c);
1107                      shouldThrow();
1108                  } catch (RejectedExecutionException success) {}
1128                assertTrue(p.getTaskCount() <= 2);
1109              }
1110 <            done.countDown();
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 <        final ThreadPoolExecutor p =
1179 <            new ThreadPoolExecutor(1, 1,
1180 <                                   LONG_DELAY_MS,
1181 <                                   MILLISECONDS,
1182 <                                   new ArrayBlockingQueue<Runnable>(1),
1183 <                                   new ThreadPoolExecutor.CallerRunsPolicy());
1184 <        try (PoolCleaner cleaner = cleaner(p)) {
1185 <            final CountDownLatch done = new CountDownLatch(1);
1186 <            Runnable blocker = new CheckedRunnable() {
1187 <                public void realRun() throws InterruptedException {
1148 <                    done.await();
1149 <                }};
1150 <            p.execute(blocker);
1151 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1152 <            for (int i = 0; i < tasks.length; i++)
1153 <                tasks[i] = new TrackedNoOpRunnable();
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]);
1189 >                p.execute(tasks[i] = new TrackedNoOpRunnable());
1190 >
1191              for (int i = 1; i < tasks.length; i++)
1192                  assertTrue(tasks[i].done);
1193              assertFalse(tasks[0].done); // waiting in queue
1159            done.countDown();
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 +        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 <        for (int i = 0; i < tasks.length; ++i)
1210 <            tasks[i] = new TrackedNoOpRunnable();
1170 <        final ThreadPoolExecutor p =
1171 <            new ThreadPoolExecutor(1, 1,
1172 <                          LONG_DELAY_MS, MILLISECONDS,
1173 <                          new ArrayBlockingQueue<Runnable>(1),
1174 <                          new ThreadPoolExecutor.DiscardPolicy());
1175 <        try (PoolCleaner cleaner = cleaner(p)) {
1176 <            final CountDownLatch done = new CountDownLatch(1);
1209 >        final CountDownLatch done = new CountDownLatch(1);
1210 >        try (PoolCleaner cleaner = cleaner(p, done)) {
1211              p.execute(awaiter(done));
1212  
1213 <            for (TrackedNoOpRunnable task : tasks)
1214 <                p.execute(task);
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);
1183            done.countDown();
1218          }
1219          for (int i = 1; i < tasks.length; i++)
1220              assertFalse(tasks[i].done);
# Line 1199 | Line 1233 | public class ThreadPoolExecutorTest exte
1233              new ThreadPoolExecutor(1, 1,
1234                                     LONG_DELAY_MS, MILLISECONDS,
1235                                     new ArrayBlockingQueue<Runnable>(1),
1236 <                                   new ThreadPoolExecutor.DiscardOldestPolicy());
1237 <        try (PoolCleaner cleaner = cleaner(p)) {
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);
# Line 1210 | Line 1244 | public class ThreadPoolExecutorTest exte
1244              p.execute(r3);
1245              assertFalse(p.getQueue().contains(r2));
1246              assertTrue(p.getQueue().contains(r3));
1213            done.countDown();
1247          }
1248          assertEquals(LatchAwaiter.DONE, r1.state);
1249          assertEquals(LatchAwaiter.NEW, r2.state);
# Line 1238 | Line 1271 | public class ThreadPoolExecutorTest exte
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,
# Line 1260 | Line 1293 | public class ThreadPoolExecutorTest exte
1293              new ThreadPoolExecutor(1, 1,
1294                                     LONG_DELAY_MS, MILLISECONDS,
1295                                     new ArrayBlockingQueue<Runnable>(1),
1296 <                                   new ThreadPoolExecutor.DiscardPolicy());
1296 >                                   new DiscardPolicy());
1297  
1298          try { p.shutdown(); } catch (SecurityException ok) { return; }
1299          try (PoolCleaner cleaner = cleaner(p)) {
# Line 1278 | Line 1311 | public class ThreadPoolExecutorTest exte
1311              new ThreadPoolExecutor(1, 1,
1312                                     LONG_DELAY_MS, MILLISECONDS,
1313                                     new ArrayBlockingQueue<Runnable>(1),
1314 <                                   new ThreadPoolExecutor.DiscardOldestPolicy());
1314 >                                   new DiscardOldestPolicy());
1315  
1316          try { p.shutdown(); } catch (SecurityException ok) { return; }
1317          try (PoolCleaner cleaner = cleaner(p)) {
# Line 1492 | Line 1525 | public class ThreadPoolExecutorTest exte
1525      }
1526  
1527      /**
1528 <     * invokeAny(empty collection) throws IAE
1528 >     * invokeAny(empty collection) throws IllegalArgumentException
1529       */
1530      public void testInvokeAny2() throws Exception {
1531          final ExecutorService e =
# Line 1517 | Line 1550 | public class ThreadPoolExecutorTest exte
1550                                     LONG_DELAY_MS, MILLISECONDS,
1551                                     new ArrayBlockingQueue<Runnable>(10));
1552          try (PoolCleaner cleaner = cleaner(e)) {
1553 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1553 >            List<Callable<String>> l = new ArrayList<>();
1554              l.add(latchAwaitingStringTask(latch));
1555              l.add(null);
1556              try {
# Line 1537 | Line 1570 | public class ThreadPoolExecutorTest exte
1570                                     LONG_DELAY_MS, MILLISECONDS,
1571                                     new ArrayBlockingQueue<Runnable>(10));
1572          try (PoolCleaner cleaner = cleaner(e)) {
1573 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1573 >            List<Callable<String>> l = new ArrayList<>();
1574              l.add(new NPETask());
1575              try {
1576                  e.invokeAny(l);
# Line 1557 | Line 1590 | public class ThreadPoolExecutorTest exte
1590                                     LONG_DELAY_MS, MILLISECONDS,
1591                                     new ArrayBlockingQueue<Runnable>(10));
1592          try (PoolCleaner cleaner = cleaner(e)) {
1593 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1593 >            List<Callable<String>> l = new ArrayList<>();
1594              l.add(new StringTask());
1595              l.add(new StringTask());
1596              String result = e.invokeAny(l);
# Line 1582 | Line 1615 | public class ThreadPoolExecutorTest exte
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          final ExecutorService e =
1622              new ThreadPoolExecutor(2, 2,
1623                                     LONG_DELAY_MS, MILLISECONDS,
1624                                     new ArrayBlockingQueue<Runnable>(10));
1625 +        final Collection<Callable<String>> emptyCollection
1626 +            = Collections.emptyList();
1627          try (PoolCleaner cleaner = cleaner(e)) {
1628 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>());
1628 >            List<Future<String>> r = e.invokeAll(emptyCollection);
1629              assertTrue(r.isEmpty());
1630          }
1631      }
# Line 1604 | Line 1639 | public class ThreadPoolExecutorTest exte
1639                                     LONG_DELAY_MS, MILLISECONDS,
1640                                     new ArrayBlockingQueue<Runnable>(10));
1641          try (PoolCleaner cleaner = cleaner(e)) {
1642 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1642 >            List<Callable<String>> l = new ArrayList<>();
1643              l.add(new StringTask());
1644              l.add(null);
1645              try {
# Line 1623 | Line 1658 | public class ThreadPoolExecutorTest exte
1658                                     LONG_DELAY_MS, MILLISECONDS,
1659                                     new ArrayBlockingQueue<Runnable>(10));
1660          try (PoolCleaner cleaner = cleaner(e)) {
1661 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
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 1645 | 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              l.add(new StringTask());
1686              List<Future<String>> futures = e.invokeAll(l);
# Line 1665 | Line 1700 | public class ThreadPoolExecutorTest exte
1700                                     new ArrayBlockingQueue<Runnable>(10));
1701          try (PoolCleaner cleaner = cleaner(e)) {
1702              try {
1703 <                e.invokeAny(null, MEDIUM_DELAY_MS, MILLISECONDS);
1703 >                e.invokeAny(null, randomTimeout(), randomTimeUnit());
1704                  shouldThrow();
1705              } catch (NullPointerException success) {}
1706          }
# Line 1680 | 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              try {
1721 <                e.invokeAny(l, MEDIUM_DELAY_MS, null);
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          final ExecutorService e =
# Line 1700 | Line 1735 | public class ThreadPoolExecutorTest exte
1735          try (PoolCleaner cleaner = cleaner(e)) {
1736              try {
1737                  e.invokeAny(new ArrayList<Callable<String>>(),
1738 <                            MEDIUM_DELAY_MS, MILLISECONDS);
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 1716 | Line 1751 | public class ThreadPoolExecutorTest exte
1751                                     LONG_DELAY_MS, MILLISECONDS,
1752                                     new ArrayBlockingQueue<Runnable>(10));
1753          try (PoolCleaner cleaner = cleaner(e)) {
1754 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1754 >            List<Callable<String>> l = new ArrayList<>();
1755              l.add(latchAwaitingStringTask(latch));
1756              l.add(null);
1757              try {
1758 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
1758 >                e.invokeAny(l, randomTimeout(), randomTimeUnit());
1759                  shouldThrow();
1760              } catch (NullPointerException success) {}
1761              latch.countDown();
# Line 1736 | Line 1771 | public class ThreadPoolExecutorTest exte
1771                                     LONG_DELAY_MS, MILLISECONDS,
1772                                     new ArrayBlockingQueue<Runnable>(10));
1773          try (PoolCleaner cleaner = cleaner(e)) {
1774 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1774 >            long startTime = System.nanoTime();
1775 >            List<Callable<String>> l = new ArrayList<>();
1776              l.add(new NPETask());
1777              try {
1778 <                e.invokeAny(l, MEDIUM_DELAY_MS, MILLISECONDS);
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 1756 | Line 1793 | public class ThreadPoolExecutorTest exte
1793                                     LONG_DELAY_MS, MILLISECONDS,
1794                                     new ArrayBlockingQueue<Runnable>(10));
1795          try (PoolCleaner cleaner = cleaner(e)) {
1796 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
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 +            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1803          }
1804      }
1805  
# Line 1774 | Line 1813 | public class ThreadPoolExecutorTest exte
1813                                     new ArrayBlockingQueue<Runnable>(10));
1814          try (PoolCleaner cleaner = cleaner(e)) {
1815              try {
1816 <                e.invokeAll(null, MEDIUM_DELAY_MS, MILLISECONDS);
1816 >                e.invokeAll(null, randomTimeout(), randomTimeUnit());
1817                  shouldThrow();
1818              } catch (NullPointerException success) {}
1819          }
# Line 1789 | Line 1828 | public class ThreadPoolExecutorTest exte
1828                                     LONG_DELAY_MS, MILLISECONDS,
1829                                     new ArrayBlockingQueue<Runnable>(10));
1830          try (PoolCleaner cleaner = cleaner(e)) {
1831 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1831 >            List<Callable<String>> l = new ArrayList<>();
1832              l.add(new StringTask());
1833              try {
1834 <                e.invokeAll(l, MEDIUM_DELAY_MS, null);
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          final ExecutorService e =
1845              new ThreadPoolExecutor(2, 2,
1846                                     LONG_DELAY_MS, MILLISECONDS,
1847                                     new ArrayBlockingQueue<Runnable>(10));
1848 +        final Collection<Callable<String>> emptyCollection
1849 +            = Collections.emptyList();
1850          try (PoolCleaner cleaner = cleaner(e)) {
1851 <            List<Future<String>> r = e.invokeAll(new ArrayList<Callable<String>>(),
1852 <                                                 MEDIUM_DELAY_MS, MILLISECONDS);
1851 >            List<Future<String>> r =
1852 >                e.invokeAll(emptyCollection, randomTimeout(), randomTimeUnit());
1853              assertTrue(r.isEmpty());
1854          }
1855      }
# Line 1822 | Line 1863 | public class ThreadPoolExecutorTest exte
1863                                     LONG_DELAY_MS, MILLISECONDS,
1864                                     new ArrayBlockingQueue<Runnable>(10));
1865          try (PoolCleaner cleaner = cleaner(e)) {
1866 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1866 >            List<Callable<String>> l = new ArrayList<>();
1867              l.add(new StringTask());
1868              l.add(null);
1869              try {
1870 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1870 >                e.invokeAll(l, randomTimeout(), randomTimeUnit());
1871                  shouldThrow();
1872              } catch (NullPointerException success) {}
1873          }
# Line 1841 | Line 1882 | public class ThreadPoolExecutorTest exte
1882                                     LONG_DELAY_MS, MILLISECONDS,
1883                                     new ArrayBlockingQueue<Runnable>(10));
1884          try (PoolCleaner cleaner = cleaner(e)) {
1885 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1885 >            List<Callable<String>> l = new ArrayList<>();
1886              l.add(new NPETask());
1887              List<Future<String>> futures =
1888 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1888 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1889              assertEquals(1, futures.size());
1890              try {
1891                  futures.get(0).get();
# Line 1864 | Line 1905 | public class ThreadPoolExecutorTest exte
1905                                     LONG_DELAY_MS, MILLISECONDS,
1906                                     new ArrayBlockingQueue<Runnable>(10));
1907          try (PoolCleaner cleaner = cleaner(e)) {
1908 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1908 >            List<Callable<String>> l = new ArrayList<>();
1909              l.add(new StringTask());
1910              l.add(new StringTask());
1911              List<Future<String>> futures =
# Line 1879 | Line 1920 | public class ThreadPoolExecutorTest exte
1920       * timed invokeAll(c) cancels tasks not completed by timeout
1921       */
1922      public void testTimedInvokeAll6() throws Exception {
1923 <        final ExecutorService e =
1924 <            new ThreadPoolExecutor(2, 2,
1925 <                                   LONG_DELAY_MS, MILLISECONDS,
1926 <                                   new ArrayBlockingQueue<Runnable>(10));
1927 <        try (PoolCleaner cleaner = cleaner(e)) {
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 1928 | Line 1975 | public class ThreadPoolExecutorTest exte
1975                      public void realRun() {
1976                          done.countDown();
1977                      }});
1978 <            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
1978 >            await(done);
1979          }
1980      }
1981  
# Line 2021 | Line 2068 | public class ThreadPoolExecutorTest exte
2068                  }
2069              }
2070              // enough time to run all tasks
2071 <            assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS));
2071 >            await(done, nTasks * SHORT_DELAY_MS);
2072          }
2073      }
2074  
# Line 2029 | 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 (PoolCleaner cleaner = cleaner(e)) {
2084 >        try (PoolCleaner cleaner = cleaner(e, done)) {
2085              final CountDownLatch blockerStarted = new CountDownLatch(1);
2038            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 2045 | 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 2059 | Line 2106 | public class ThreadPoolExecutorTest exte
2106                  assertTrue(future.isCancelled());
2107                  assertTrue(future.isDone());
2108              }
2062            done.countDown();
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