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.123 by jsr166, Sat Jul 15 23:15:21 2017 UTC vs.
Revision 1.128 by jsr166, Wed Jan 27 01:57:24 2021 UTC

# Line 563 | Line 563 | public class ThreadPoolExecutorTest exte
563                                     q);
564          try (PoolCleaner cleaner = cleaner(p, done)) {
565              final CountDownLatch threadStarted = new CountDownLatch(1);
566 <            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<>() {
571                      public Boolean realCall() throws InterruptedException {
572                          threadStarted.countDown();
573                          assertSame(q, p.getQueue());
574                          await(done);
575                          return Boolean.TRUE;
576                      }};
577 <                tasks[i] = new FutureTask(task);
577 >                tasks[i] = new FutureTask<>(task);
578                  p.execute(tasks[i]);
579              }
580              await(threadStarted);
# Line 629 | Line 631 | public class ThreadPoolExecutorTest exte
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<>() {
639                      public Boolean realCall() throws InterruptedException {
640                          threadStarted.countDown();
641                          await(done);
642                          return Boolean.TRUE;
643                      }};
644 <                tasks[i] = new FutureTask(task);
644 >                tasks[i] = new FutureTask<>(task);
645                  p.execute(tasks[i]);
646              }
647              await(threadStarted);
# Line 672 | 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          }};
# Line 759 | 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 830 | 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 914 | 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 1003 | 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 1050 | Line 1054 | public class ThreadPoolExecutorTest exte
1054              final CountDownLatch threadStarted = 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<>() {
1058                          public Boolean realCall() throws InterruptedException {
1059                              threadStarted.countDown();
1060                              await(done);
# Line 1059 | Line 1063 | public class ThreadPoolExecutorTest exte
1063                      p.submit(task).get();
1064                  }});
1065  
1066 <            await(threadStarted);
1066 >            await(threadStarted); // ensure quiescence
1067              t.interrupt();
1068              awaitTermination(t);
1069          }
1070      }
1071  
1072      /**
1073 <     * Submitted tasks are rejected when saturated.
1073 >     * Submitted tasks are rejected when saturated or shutdown
1074       */
1075 <    @SuppressWarnings("FutureReturnValueIgnored")
1076 <    public void testSubmittedTasksRejectedWhenSaturated() {
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 = awaiter(done);
1083 <        final Callable<Boolean> c = new CheckedCallable() {
1084 <            public Boolean realCall() throws InterruptedException {
1085 <                await(done);
1086 <                return Boolean.TRUE;
1082 >        final Runnable r = () -> {
1083 >            threadsStarted.countDown();
1084 >            for (;;) {
1085 >                try {
1086 >                    done.await();
1087 >                    return;
1088 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1089              }};
1090 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1091 <            1, 1, 1, SECONDS, new ArrayBlockingQueue<Runnable>(1));
1090 >        final Callable<Boolean> c = () -> {
1091 >            threadsStarted.countDown();
1092 >            for (;;) {
1093 >                try {
1094 >                    done.await();
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(p); i--> 0; ) {
1103 <                switch (rnd.nextInt(3)) {
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(c).isDone()); break;
1106 >                case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
1107 >                case 3: assertFalse(p.submit(c).isDone()); break;
1108                  }
1109              }
1110  
1111 <            // check default handler
1112 <            assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
1096 <            for (int i = 2; i--> 0; ) {
1097 <                try {
1098 <                    p.execute(r);
1099 <                    shouldThrow();
1100 <                } catch (RejectedExecutionException success) {}
1101 <                try {
1102 <                    p.submit(r);
1103 <                    shouldThrow();
1104 <                } catch (RejectedExecutionException success) {}
1105 <                try {
1106 <                    p.submit(c);
1107 <                    shouldThrow();
1108 <                } catch (RejectedExecutionException success) {}
1109 <            }
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 <            }
1111 >            await(threadsStarted);
1112 >            assertTaskSubmissionsAreRejected(p);
1113  
1114 <            class Recorder implements RejectedExecutionHandler {
1115 <                public volatile Runnable r = null;
1116 <                public volatile ThreadPoolExecutor p = null;
1117 <                public void reset() { r = null; p = null; }
1118 <                public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1119 <                    assertNull(this.r);
1120 <                    assertNull(this.p);
1121 <                    this.r = r;
1122 <                    this.p = p;
1123 <                }
1124 <            }
1125 <
1126 <            // check custom handler is invoked exactly once per task
1127 <            Recorder recorder = new Recorder();
1128 <            p.setRejectedExecutionHandler(recorder);
1129 <            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 RejectedExecutionHandler handler = new CallerRunsPolicy();
1179 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1180 <            1, 1, LONG_DELAY_MS, SECONDS, new ArrayBlockingQueue<Runnable>(1),
1181 <            handler);
1182 <        assertSame(handler, p.getRejectedExecutionHandler());
1183 <        final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1184 <        final CountDownLatch done = new CountDownLatch(1);
1185 <        try (PoolCleaner cleaner = cleaner(p, done)) {
1186 <            p.execute(awaiter(done));
1187 <
1188 <            for (int i = 0; i < tasks.length; i++)
1189 <                p.execute(tasks[i] = new TrackedNoOpRunnable());
1190 <
1191 <            for (int i = 1; i < tasks.length; i++)
1192 <                assertTrue(tasks[i].done);
1193 <            assertFalse(tasks[0].done); // waiting in queue
1194 <        }
1195 <        for (TrackedNoOpRunnable task : tasks)
1196 <            assertTrue(task.done);
1197 <    }
1198 <
1199 <    /**
1200 <     * executor using DiscardPolicy drops task if saturated.
1201 <     */
1202 <    public void testSaturatedExecute3() {
1203 <        final RejectedExecutionHandler handler = new DiscardPolicy();
1204 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1205 <            1, 1, LONG_DELAY_MS, SECONDS, new ArrayBlockingQueue<Runnable>(1),
1206 <            handler);
1207 <        assertSame(handler, p.getRejectedExecutionHandler());
1208 <        final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1209 <        final CountDownLatch done = new CountDownLatch(1);
1210 <        try (PoolCleaner cleaner = cleaner(p, done)) {
1211 <            p.execute(awaiter(done));
1212 <
1213 <            for (int i = 0; i < tasks.length; i++)
1214 <                p.execute(tasks[i] = new TrackedNoOpRunnable());
1215 <
1216 <            for (int i = 1; i < tasks.length; i++)
1217 <                assertFalse(tasks[i].done);
1218 <        }
1219 <        for (int i = 1; i < tasks.length; i++)
1220 <            assertFalse(tasks[i].done);
1221 <        assertTrue(tasks[0].done); // was waiting in queue
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 >            done.countDown();   // release blocking tasks
1123 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
1124 >
1125 >            assertTaskSubmissionsAreRejected(p);
1126 >        }
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 1251 | Line 1159 | public class ThreadPoolExecutorTest exte
1159      }
1160  
1161      /**
1254     * execute throws RejectedExecutionException if shutdown
1255     */
1256    public void testRejectedExecutionExceptionOnShutdown() {
1257        final ThreadPoolExecutor p =
1258            new ThreadPoolExecutor(1, 1,
1259                                   LONG_DELAY_MS, MILLISECONDS,
1260                                   new ArrayBlockingQueue<Runnable>(1));
1261        try { p.shutdown(); } catch (SecurityException ok) { return; }
1262        try (PoolCleaner cleaner = cleaner(p)) {
1263            try {
1264                p.execute(new NoOpRunnable());
1265                shouldThrow();
1266            } catch (RejectedExecutionException success) {}
1267        }
1268    }
1269
1270    /**
1271     * execute using CallerRunsPolicy drops task on shutdown
1272     */
1273    public void testCallerRunsOnShutdown() {
1274        RejectedExecutionHandler h = new CallerRunsPolicy();
1275        final ThreadPoolExecutor p =
1276            new ThreadPoolExecutor(1, 1,
1277                                   LONG_DELAY_MS, MILLISECONDS,
1278                                   new ArrayBlockingQueue<Runnable>(1), h);
1279
1280        try { p.shutdown(); } catch (SecurityException ok) { return; }
1281        try (PoolCleaner cleaner = cleaner(p)) {
1282            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1283            p.execute(r);
1284            assertFalse(r.done);
1285        }
1286    }
1287
1288    /**
1289     * execute using DiscardPolicy drops task on shutdown
1290     */
1291    public void testDiscardOnShutdown() {
1292        final ThreadPoolExecutor p =
1293            new ThreadPoolExecutor(1, 1,
1294                                   LONG_DELAY_MS, MILLISECONDS,
1295                                   new ArrayBlockingQueue<Runnable>(1),
1296                                   new DiscardPolicy());
1297
1298        try { p.shutdown(); } catch (SecurityException ok) { return; }
1299        try (PoolCleaner cleaner = cleaner(p)) {
1300            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1301            p.execute(r);
1302            assertFalse(r.done);
1303        }
1304    }
1305
1306    /**
1162       * execute using DiscardOldestPolicy drops task on shutdown
1163       */
1164      public void testDiscardOldestOnShutdown() {
# Line 1322 | 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 {
1334 <                p.execute(null);
1335 <                shouldThrow();
1336 <            } catch (NullPointerException success) {}
1188 >            assertNullTaskSubmissionThrowsNullPointerException(p);
1189          }
1190      }
1191  
# Line 1922 | Line 1774 | public class ThreadPoolExecutorTest exte
1774      public void testTimedInvokeAll6() throws Exception {
1775          for (long timeout = timeoutMillis();;) {
1776              final CountDownLatch done = new CountDownLatch(1);
1777 <            final Callable<String> waiter = new CheckedCallable<String>() {
1777 >            final Callable<String> waiter = new CheckedCallable<>() {
1778                  public String realCall() {
1779                      try { done.await(LONG_DELAY_MS, MILLISECONDS); }
1780                      catch (InterruptedException ok) {}
# Line 1941 | Line 1793 | public class ThreadPoolExecutorTest exte
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 2056 | 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 2136 | Line 1988 | public class ThreadPoolExecutorTest exte
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 +
2036   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines