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.117 by jsr166, Sat Mar 25 21:41:10 2017 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 26 | 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 282 | 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()
286 <                       instanceof ThreadPoolExecutor.AbortPolicy);
293 >            assertTrue(p.getRejectedExecutionHandler() instanceof AbortPolicy);
294          }
295      }
296  
# Line 470 | 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 1059 | Line 1066 | public class ThreadPoolExecutorTest exte
1066      }
1067  
1068      /**
1069 <     * execute throws RejectedExecutionException if saturated.
1069 >     * Submitted tasks are rejected when saturated.
1070       */
1071 <    public void testSaturatedExecute() {
1071 >    @SuppressWarnings("FutureReturnValueIgnored")
1072 >    public void testSubmittedTasksRejectedWhenSaturated() {
1073 >        final ThreadLocalRandom rnd = ThreadLocalRandom.current();
1074          final CountDownLatch done = new CountDownLatch(1);
1075 <        final ThreadPoolExecutor p =
1076 <            new ThreadPoolExecutor(1, 1,
1077 <                                   LONG_DELAY_MS, MILLISECONDS,
1078 <                                   new ArrayBlockingQueue<Runnable>(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 <            Runnable task = new CheckedRunnable() {
1086 <                public void realRun() throws InterruptedException {
1087 <                    await(done);
1088 <                }};
1089 <            for (int i = 0; i < 2; ++i)
1090 <                p.execute(task);
1091 <            for (int i = 0; i < 2; ++i) {
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) {}
1082                assertTrue(p.getTaskCount() <= 2);
1083            }
1084        }
1085    }
1086
1087    /**
1088     * submit(runnable) throws RejectedExecutionException if saturated.
1089     */
1090    public void testSaturatedSubmitRunnable() {
1091        final CountDownLatch done = new CountDownLatch(1);
1092        final ThreadPoolExecutor p =
1093            new ThreadPoolExecutor(1, 1,
1094                                   LONG_DELAY_MS, MILLISECONDS,
1095                                   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.submit(task);
1103            for (int i = 0; i < 2; ++i) {
1101                  try {
1102 <                    p.execute(task);
1102 >                    p.submit(r);
1103                      shouldThrow();
1104                  } catch (RejectedExecutionException success) {}
1108                assertTrue(p.getTaskCount() <= 2);
1109            }
1110        }
1111    }
1112
1113    /**
1114     * submit(callable) throws RejectedExecutionException if saturated.
1115     */
1116    public void testSaturatedSubmitCallable() {
1117        final CountDownLatch done = new CountDownLatch(1);
1118        final ThreadPoolExecutor p =
1119            new ThreadPoolExecutor(1, 1,
1120                                   LONG_DELAY_MS, MILLISECONDS,
1121                                   new ArrayBlockingQueue<Runnable>(1));
1122        try (PoolCleaner cleaner = cleaner(p, done)) {
1123            Runnable task = new CheckedRunnable() {
1124                public void realRun() throws InterruptedException {
1125                    await(done);
1126                }};
1127            for (int i = 0; i < 2; ++i)
1128                p.execute(task);
1129            for (int i = 0; i < 2; ++i) {
1105                  try {
1106 <                    p.execute(task);
1106 >                    p.submit(c);
1107                      shouldThrow();
1108                  } catch (RejectedExecutionException success) {}
1134                assertTrue(p.getTaskCount() <= 2);
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 +            }
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 {
1153 <                    await(done);
1154 <                }};
1155 <            p.execute(blocker);
1156 <            TrackedNoOpRunnable[] tasks = new TrackedNoOpRunnable[5];
1157 <            for (int i = 0; i < tasks.length; i++)
1158 <                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
1164            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 CountDownLatch done = new CountDownLatch(1);
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)
1175 <            tasks[i] = new TrackedNoOpRunnable();
1176 <        final ThreadPoolExecutor p =
1177 <            new ThreadPoolExecutor(1, 1,
1178 <                          LONG_DELAY_MS, MILLISECONDS,
1179 <                          new ArrayBlockingQueue<Runnable>(1),
1180 <                          new ThreadPoolExecutor.DiscardPolicy());
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);
1218          }
# Line 1203 | 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());
1236 >                                   new DiscardOldestPolicy());
1237          try (PoolCleaner cleaner = cleaner(p, done)) {
1238              assertEquals(LatchAwaiter.NEW, r1.state);
1239              assertEquals(LatchAwaiter.NEW, r2.state);
# Line 1241 | 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 1263 | 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 1281 | 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 1495 | 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 1585 | 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 1668 | 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 1686 | Line 1718 | public class ThreadPoolExecutorTest exte
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 1703 | 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 1723 | Line 1755 | public class ThreadPoolExecutorTest exte
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 1781 | 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 1799 | Line 1831 | public class ThreadPoolExecutorTest exte
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 1833 | Line 1867 | public class ThreadPoolExecutorTest exte
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 2075 | Line 2109 | public class ThreadPoolExecutorTest exte
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