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.120 by jsr166, Sat Jul 15 18:17:40 2017 UTC vs.
Revision 1.126 by jsr166, Fri Sep 6 18:43:35 2019 UTC

# Line 28 | 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.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 284 | Line 290 | public class ThreadPoolExecutorTest exte
290                                     LONG_DELAY_MS, MILLISECONDS,
291                                     new ArrayBlockingQueue<Runnable>(10));
292          try (PoolCleaner cleaner = cleaner(p)) {
293 <            assertTrue(p.getRejectedExecutionHandler()
288 <                       instanceof ThreadPoolExecutor.AbortPolicy);
293 >            assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
294          }
295      }
296  
# Line 667 | Line 672 | public class ThreadPoolExecutorTest exte
672          Runnable waiter = new CheckedRunnable() { public void realRun() {
673              threadsStarted.countDown();
674              try {
675 <                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
675 >                MILLISECONDS.sleep(LONGER_DELAY_MS);
676              } catch (InterruptedException success) {}
677              ran.getAndIncrement();
678          }};
# Line 1054 | Line 1059 | public class ThreadPoolExecutorTest exte
1059                      p.submit(task).get();
1060                  }});
1061  
1062 <            await(threadStarted);
1062 >            await(threadStarted); // ensure quiescence
1063              t.interrupt();
1064              awaitTermination(t);
1065          }
1066      }
1067  
1068      /**
1069 <     * execute throws RejectedExecutionException if saturated.
1069 >     * Submitted tasks are rejected when saturated or shutdown
1070       */
1071 <    public void testSaturatedExecute() {
1071 >    public void testSubmittedTasksRejectedWhenSaturatedOrShutdown() throws InterruptedException {
1072 >        final ThreadPoolExecutor p = new ThreadPoolExecutor(
1073 >            1, 1, 1, SECONDS, new ArrayBlockingQueue<Runnable>(1));
1074 >        final int saturatedSize = saturatedSize(p);
1075 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1076 >        final CountDownLatch threadsStarted = new CountDownLatch(p.getMaximumPoolSize());
1077          final CountDownLatch done = new CountDownLatch(1);
1078 <        final ThreadPoolExecutor p =
1079 <            new ThreadPoolExecutor(1, 1,
1080 <                                   LONG_DELAY_MS, MILLISECONDS,
1071 <                                   new ArrayBlockingQueue<Runnable>(1));
1072 <        try (PoolCleaner cleaner = cleaner(p, done)) {
1073 <            Runnable task = new CheckedRunnable() {
1074 <                public void realRun() throws InterruptedException {
1075 <                    await(done);
1076 <                }};
1077 <            for (int i = 0; i < 2; ++i)
1078 <                p.execute(task);
1079 <            for (int i = 0; i < 2; ++i) {
1078 >        final Runnable r = () -> {
1079 >            threadsStarted.countDown();
1080 >            for (;;) {
1081                  try {
1082 <                    p.execute(task);
1083 <                    shouldThrow();
1084 <                } catch (RejectedExecutionException success) {}
1085 <                assertTrue(p.getTaskCount() <= 2);
1086 <            }
1087 <        }
1088 <    }
1088 <
1089 <    /**
1090 <     * submit(runnable) throws RejectedExecutionException if saturated.
1091 <     */
1092 <    public void testSaturatedSubmitRunnable() {
1093 <        final CountDownLatch done = new CountDownLatch(1);
1094 <        final ThreadPoolExecutor p =
1095 <            new ThreadPoolExecutor(1, 1,
1096 <                                   LONG_DELAY_MS, MILLISECONDS,
1097 <                                   new ArrayBlockingQueue<Runnable>(1));
1098 <        try (PoolCleaner cleaner = cleaner(p, done)) {
1099 <            Runnable task = new CheckedRunnable() {
1100 <                public void realRun() throws InterruptedException {
1101 <                    await(done);
1102 <                }};
1103 <            for (int i = 0; i < 2; ++i)
1104 <                p.submit(task);
1105 <            for (int i = 0; i < 2; ++i) {
1082 >                    done.await();
1083 >                    return;
1084 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1085 >            }};
1086 >        final Callable<Boolean> c = () -> {
1087 >            threadsStarted.countDown();
1088 >            for (;;) {
1089                  try {
1090 <                    p.execute(task);
1091 <                    shouldThrow();
1092 <                } catch (RejectedExecutionException success) {}
1093 <                assertTrue(p.getTaskCount() <= 2);
1094 <            }
1112 <        }
1113 <    }
1090 >                    done.await();
1091 >                    return Boolean.TRUE;
1092 >                } catch (InterruptedException shutdownNowDeliberatelyIgnored) {}
1093 >            }};
1094 >        final boolean shutdownNow = rnd.nextBoolean();
1095  
1115    /**
1116     * submit(callable) throws RejectedExecutionException if saturated.
1117     */
1118    public void testSaturatedSubmitCallable() {
1119        final CountDownLatch done = new CountDownLatch(1);
1120        final ThreadPoolExecutor p =
1121            new ThreadPoolExecutor(1, 1,
1122                                   LONG_DELAY_MS, MILLISECONDS,
1123                                   new ArrayBlockingQueue<Runnable>(1));
1096          try (PoolCleaner cleaner = cleaner(p, done)) {
1097 <            Runnable task = new CheckedRunnable() {
1098 <                public void realRun() throws InterruptedException {
1099 <                    await(done);
1100 <                }};
1101 <            for (int i = 0; i < 2; ++i)
1102 <                p.execute(task);
1103 <            for (int i = 0; i < 2; ++i) {
1104 <                try {
1133 <                    p.execute(task);
1134 <                    shouldThrow();
1135 <                } catch (RejectedExecutionException success) {}
1136 <                assertTrue(p.getTaskCount() <= 2);
1097 >            // saturate
1098 >            for (int i = saturatedSize; i--> 0; ) {
1099 >                switch (rnd.nextInt(4)) {
1100 >                case 0: p.execute(r); break;
1101 >                case 1: assertFalse(p.submit(r).isDone()); break;
1102 >                case 2: assertFalse(p.submit(r, Boolean.TRUE).isDone()); break;
1103 >                case 3: assertFalse(p.submit(c).isDone()); break;
1104 >                }
1105              }
1138        }
1139    }
1106  
1107 <    /**
1108 <     * executor using CallerRunsPolicy runs task if saturated.
1143 <     */
1144 <    public void testSaturatedExecute2() {
1145 <        final ThreadPoolExecutor p =
1146 <            new ThreadPoolExecutor(1, 1,
1147 <                                   LONG_DELAY_MS,
1148 <                                   MILLISECONDS,
1149 <                                   new ArrayBlockingQueue<Runnable>(1),
1150 <                                   new ThreadPoolExecutor.CallerRunsPolicy());
1151 <        try (PoolCleaner cleaner = cleaner(p)) {
1152 <            final CountDownLatch done = new CountDownLatch(1);
1153 <            Runnable blocker = new CheckedRunnable() {
1154 <                public void realRun() throws InterruptedException {
1155 <                    await(done);
1156 <                }};
1157 <            p.execute(blocker);
1158 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1159 <            for (int i = 0; i < tasks.length; i++)
1160 <                tasks[i] = new TrackedNoOpRunnable();
1161 <            for (int i = 0; i < tasks.length; i++)
1162 <                p.execute(tasks[i]);
1163 <            for (int i = 1; i < tasks.length; i++)
1164 <                assertTrue(tasks[i].done);
1165 <            assertFalse(tasks[0].done); // waiting in queue
1166 <            done.countDown();
1167 <        }
1168 <    }
1107 >            await(threadsStarted);
1108 >            assertTaskSubmissionsAreRejected(p);
1109  
1110 <    /**
1111 <     * executor using DiscardPolicy drops task if saturated.
1112 <     */
1113 <    public void testSaturatedExecute3() {
1114 <        final CountDownLatch done = new CountDownLatch(1);
1115 <        final TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1116 <        for (int i = 0; i < tasks.length; ++i)
1117 <            tasks[i] = new TrackedNoOpRunnable();
1118 <        final ThreadPoolExecutor p =
1119 <            new ThreadPoolExecutor(1, 1,
1180 <                          LONG_DELAY_MS, MILLISECONDS,
1181 <                          new ArrayBlockingQueue<Runnable>(1),
1182 <                          new ThreadPoolExecutor.DiscardPolicy());
1183 <        try (PoolCleaner cleaner = cleaner(p, done)) {
1184 <            p.execute(awaiter(done));
1110 >            if (shutdownNow)
1111 >                p.shutdownNow();
1112 >            else
1113 >                p.shutdown();
1114 >            // Pool is shutdown, but not yet terminated
1115 >            assertTaskSubmissionsAreRejected(p);
1116 >            assertFalse(p.isTerminated());
1117 >
1118 >            done.countDown();   // release blocking tasks
1119 >            assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
1120  
1121 <            for (TrackedNoOpRunnable task : tasks)
1122 <                p.execute(task);
1123 <            for (int i = 1; i < tasks.length; i++)
1124 <                assertFalse(tasks[i].done);
1125 <        }
1191 <        for (int i = 1; i < tasks.length; i++)
1192 <            assertFalse(tasks[i].done);
1193 <        assertTrue(tasks[0].done); // was waiting in queue
1121 >            assertTaskSubmissionsAreRejected(p);
1122 >        }
1123 >        assertEquals(saturatedSize(p)
1124 >                     - (shutdownNow ? p.getQueue().remainingCapacity() : 0),
1125 >                     p.getCompletedTaskCount());
1126      }
1127  
1128      /**
1129       * executor using DiscardOldestPolicy drops oldest task if saturated.
1130       */
1131 <    public void testSaturatedExecute4() {
1131 >    public void testSaturatedExecute_DiscardOldestPolicy() {
1132          final CountDownLatch done = new CountDownLatch(1);
1133          LatchAwaiter r1 = awaiter(done);
1134          LatchAwaiter r2 = awaiter(done);
# Line 1205 | Line 1137 | public class ThreadPoolExecutorTest exte
1137              new ThreadPoolExecutor(1, 1,
1138                                     LONG_DELAY_MS, MILLISECONDS,
1139                                     new ArrayBlockingQueue<Runnable>(1),
1140 <                                   new ThreadPoolExecutor.DiscardOldestPolicy());
1140 >                                   new DiscardOldestPolicy());
1141          try (PoolCleaner cleaner = cleaner(p, done)) {
1142              assertEquals(LatchAwaiter.NEW, r1.state);
1143              assertEquals(LatchAwaiter.NEW, r2.state);
# Line 1223 | Line 1155 | public class ThreadPoolExecutorTest exte
1155      }
1156  
1157      /**
1226     * execute throws RejectedExecutionException if shutdown
1227     */
1228    public void testRejectedExecutionExceptionOnShutdown() {
1229        final ThreadPoolExecutor p =
1230            new ThreadPoolExecutor(1, 1,
1231                                   LONG_DELAY_MS, MILLISECONDS,
1232                                   new ArrayBlockingQueue<Runnable>(1));
1233        try { p.shutdown(); } catch (SecurityException ok) { return; }
1234        try (PoolCleaner cleaner = cleaner(p)) {
1235            try {
1236                p.execute(new NoOpRunnable());
1237                shouldThrow();
1238            } catch (RejectedExecutionException success) {}
1239        }
1240    }
1241
1242    /**
1243     * execute using CallerRunsPolicy drops task on shutdown
1244     */
1245    public void testCallerRunsOnShutdown() {
1246        RejectedExecutionHandler h = new ThreadPoolExecutor.CallerRunsPolicy();
1247        final ThreadPoolExecutor p =
1248            new ThreadPoolExecutor(1, 1,
1249                                   LONG_DELAY_MS, MILLISECONDS,
1250                                   new ArrayBlockingQueue<Runnable>(1), h);
1251
1252        try { p.shutdown(); } catch (SecurityException ok) { return; }
1253        try (PoolCleaner cleaner = cleaner(p)) {
1254            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1255            p.execute(r);
1256            assertFalse(r.done);
1257        }
1258    }
1259
1260    /**
1261     * execute using DiscardPolicy drops task on shutdown
1262     */
1263    public void testDiscardOnShutdown() {
1264        final ThreadPoolExecutor p =
1265            new ThreadPoolExecutor(1, 1,
1266                                   LONG_DELAY_MS, MILLISECONDS,
1267                                   new ArrayBlockingQueue<Runnable>(1),
1268                                   new ThreadPoolExecutor.DiscardPolicy());
1269
1270        try { p.shutdown(); } catch (SecurityException ok) { return; }
1271        try (PoolCleaner cleaner = cleaner(p)) {
1272            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1273            p.execute(r);
1274            assertFalse(r.done);
1275        }
1276    }
1277
1278    /**
1158       * execute using DiscardOldestPolicy drops task on shutdown
1159       */
1160      public void testDiscardOldestOnShutdown() {
# Line 1283 | Line 1162 | public class ThreadPoolExecutorTest exte
1162              new ThreadPoolExecutor(1, 1,
1163                                     LONG_DELAY_MS, MILLISECONDS,
1164                                     new ArrayBlockingQueue<Runnable>(1),
1165 <                                   new ThreadPoolExecutor.DiscardOldestPolicy());
1165 >                                   new DiscardOldestPolicy());
1166  
1167          try { p.shutdown(); } catch (SecurityException ok) { return; }
1168          try (PoolCleaner cleaner = cleaner(p)) {
# Line 1294 | Line 1173 | public class ThreadPoolExecutorTest exte
1173      }
1174  
1175      /**
1176 <     * execute(null) throws NPE
1176 >     * Submitting null tasks throws NullPointerException
1177       */
1178 <    public void testExecuteNull() {
1178 >    public void testNullTaskSubmission() {
1179          final ThreadPoolExecutor p =
1180              new ThreadPoolExecutor(1, 2,
1181                                     1L, SECONDS,
1182                                     new ArrayBlockingQueue<Runnable>(10));
1183          try (PoolCleaner cleaner = cleaner(p)) {
1184 <            try {
1306 <                p.execute(null);
1307 <                shouldThrow();
1308 <            } catch (NullPointerException success) {}
1184 >            assertNullTaskSubmissionThrowsNullPointerException(p);
1185          }
1186      }
1187  
# Line 2081 | Line 1957 | public class ThreadPoolExecutorTest exte
1957          }
1958      }
1959  
1960 <    public void testAbortPolicy() {
1961 <        final RejectedExecutionHandler handler =
2086 <            new ThreadPoolExecutor.AbortPolicy();
1960 >    /** Directly test simple ThreadPoolExecutor RejectedExecutionHandlers. */
1961 >    public void testStandardRejectedExecutionHandlers() {
1962          final ThreadPoolExecutor p =
1963 <            new ThreadPoolExecutor(1, 1,
1964 <                                   LONG_DELAY_MS, MILLISECONDS,
1965 <                                   new ArrayBlockingQueue<Runnable>(10));
1966 <        final TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1963 >            new ThreadPoolExecutor(1, 1, 1, SECONDS,
1964 >                                   new ArrayBlockingQueue<Runnable>(1));
1965 >        final AtomicReference<Thread> thread = new AtomicReference<>();
1966 >        final Runnable r = new Runnable() { public void run() {
1967 >            thread.set(Thread.currentThread()); }};
1968 >
1969          try {
1970 <            handler.rejectedExecution(r, p);
1970 >            new AbortPolicy().rejectedExecution(r, p);
1971              shouldThrow();
1972          } catch (RejectedExecutionException success) {}
1973 <        assertFalse(r.done);
1973 >        assertNull(thread.get());
1974 >
1975 >        new DiscardPolicy().rejectedExecution(r, p);
1976 >        assertNull(thread.get());
1977 >
1978 >        new CallerRunsPolicy().rejectedExecution(r, p);
1979 >        assertSame(Thread.currentThread(), thread.get());
1980 >
1981 >        // check that pool was not perturbed by handlers
1982 >        assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
1983          assertEquals(0, p.getTaskCount());
1984          assertTrue(p.getQueue().isEmpty());
1985      }
1986  
1987 +    public void testThreadFactoryReturnsTerminatedThread_shouldThrow() {
1988 +        if (!testImplementationDetails)
1989 +            return;
1990 +
1991 +        ThreadFactory returnsTerminatedThread = runnableIgnored -> {
1992 +            Thread thread = new Thread(() -> {});
1993 +            thread.start();
1994 +            try { thread.join(); }
1995 +            catch (InterruptedException ex) { throw new Error(ex); }
1996 +            return thread;
1997 +        };
1998 +        ThreadPoolExecutor p =
1999 +            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2000 +                                   new ArrayBlockingQueue<Runnable>(1),
2001 +                                   returnsTerminatedThread);
2002 +        try (PoolCleaner cleaner = cleaner(p)) {
2003 +            assertThrows(IllegalThreadStateException.class,
2004 +                         () -> p.execute(() -> {}));
2005 +        }
2006 +    }
2007 +
2008 +    public void testThreadFactoryReturnsStartedThread_shouldThrow() {
2009 +        if (!testImplementationDetails)
2010 +            return;
2011 +
2012 +        CountDownLatch latch = new CountDownLatch(1);
2013 +        Runnable awaitLatch = () -> {
2014 +            try { latch.await(); }
2015 +            catch (InterruptedException ex) { throw new Error(ex); }};
2016 +        ThreadFactory returnsStartedThread = runnable -> {
2017 +            Thread thread = new Thread(awaitLatch);
2018 +            thread.start();
2019 +            return thread;
2020 +        };
2021 +        ThreadPoolExecutor p =
2022 +            new ThreadPoolExecutor(1, 1, 1, SECONDS,
2023 +                                   new ArrayBlockingQueue<Runnable>(1),
2024 +                                   returnsStartedThread);
2025 +        try (PoolCleaner cleaner = cleaner(p)) {
2026 +            assertThrows(IllegalThreadStateException.class,
2027 +                         () -> p.execute(() -> {}));
2028 +            latch.countDown();
2029 +        }
2030 +    }
2031 +
2032   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines