ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
(Generate patch)

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.215 by jsr166, Sat Dec 10 18:11:05 2016 UTC vs.
Revision 1.237 by jsr166, Wed Aug 23 05:33:00 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
# Line 8 | Line 9
9  
10   /*
11   * @test
12 < * @summary JSR-166 tck tests (conformance testing mode)
12 > * @summary JSR-166 tck tests, in a number of variations.
13 > *          The first is the conformance testing variant,
14 > *          while others also test implementation details.
15   * @build *
16   * @modules java.management
17   * @run junit/othervm/timeout=1000 JSR166TestCase
15 */
16
17 /*
18 * @test
19 * @summary JSR-166 tck tests (whitebox tests allowed)
20 * @build *
21 * @modules java.base/java.util.concurrent:open
22 *          java.management
18   * @run junit/othervm/timeout=1000
19 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 + *      --add-opens java.base/java.lang=ALL-UNNAMED
21   *      -Djsr166.testImplementationDetails=true
22   *      JSR166TestCase
23   * @run junit/othervm/timeout=1000
24 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 + *      --add-opens java.base/java.lang=ALL-UNNAMED
26   *      -Djsr166.testImplementationDetails=true
27   *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28   *      JSR166TestCase
29   * @run junit/othervm/timeout=1000
30 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 + *      --add-opens java.base/java.lang=ALL-UNNAMED
32   *      -Djsr166.testImplementationDetails=true
33   *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
34   *      -Djava.util.secureRandomSeed=true
35   *      JSR166TestCase
36 + * @run junit/othervm/timeout=1000/policy=tck.policy
37 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 + *      --add-opens java.base/java.lang=ALL-UNNAMED
39 + *      -Djsr166.testImplementationDetails=true
40 + *      JSR166TestCase
41   */
42  
43   import static java.util.concurrent.TimeUnit.MILLISECONDS;
# Line 48 | Line 54 | import java.lang.management.ThreadMXBean
54   import java.lang.reflect.Constructor;
55   import java.lang.reflect.Method;
56   import java.lang.reflect.Modifier;
51 import java.nio.file.Files;
52 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 72 | Line 76 | import java.util.concurrent.Callable;
76   import java.util.concurrent.CountDownLatch;
77   import java.util.concurrent.CyclicBarrier;
78   import java.util.concurrent.ExecutionException;
79 + import java.util.concurrent.Executor;
80   import java.util.concurrent.Executors;
81   import java.util.concurrent.ExecutorService;
82   import java.util.concurrent.ForkJoinPool;
83   import java.util.concurrent.Future;
84 + import java.util.concurrent.FutureTask;
85   import java.util.concurrent.RecursiveAction;
86   import java.util.concurrent.RecursiveTask;
87 + import java.util.concurrent.RejectedExecutionException;
88   import java.util.concurrent.RejectedExecutionHandler;
89   import java.util.concurrent.Semaphore;
90 + import java.util.concurrent.ScheduledExecutorService;
91 + import java.util.concurrent.ScheduledFuture;
92   import java.util.concurrent.SynchronousQueue;
93   import java.util.concurrent.ThreadFactory;
94   import java.util.concurrent.ThreadLocalRandom;
95   import java.util.concurrent.ThreadPoolExecutor;
96 + import java.util.concurrent.TimeUnit;
97   import java.util.concurrent.TimeoutException;
98   import java.util.concurrent.atomic.AtomicBoolean;
99   import java.util.concurrent.atomic.AtomicReference;
90 import java.util.regex.Matcher;
100   import java.util.regex.Pattern;
101  
102   import junit.framework.AssertionFailedError;
# Line 297 | Line 306 | public class JSR166TestCase extends Test
306  
307   //     public static String cpuModel() {
308   //         try {
309 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
309 > //             java.util.regex.Matcher matcher
310 > //               = Pattern.compile("model name\\s*: (.*)")
311   //                 .matcher(new String(
312 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
312 > //                     java.nio.file.Files.readAllBytes(
313 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
314   //             matcher.find();
315   //             return matcher.group(1);
316   //         } catch (Exception ex) { return null; }
# Line 533 | Line 544 | public class JSR166TestCase extends Test
544                  "DoubleAdderTest",
545                  "ForkJoinPool8Test",
546                  "ForkJoinTask8Test",
547 +                "HashMapTest",
548                  "LinkedBlockingDeque8Test",
549                  "LinkedBlockingQueue8Test",
550                  "LongAccumulatorTest",
# Line 557 | Line 569 | public class JSR166TestCase extends Test
569                  "AtomicReference9Test",
570                  "AtomicReferenceArray9Test",
571                  "ExecutorCompletionService9Test",
572 +                "ForkJoinPool9Test",
573              };
574              addNamedTestClasses(suite, java9TestClassNames);
575          }
# Line 567 | Line 580 | public class JSR166TestCase extends Test
580      /** Returns list of junit-style test method names in given class. */
581      public static ArrayList<String> testMethodNames(Class<?> testClass) {
582          Method[] methods = testClass.getDeclaredMethods();
583 <        ArrayList<String> names = new ArrayList<String>(methods.length);
583 >        ArrayList<String> names = new ArrayList<>(methods.length);
584          for (Method method : methods) {
585              if (method.getName().startsWith("test")
586                  && Modifier.isPublic(method.getModifiers())
# Line 632 | Line 645 | public class JSR166TestCase extends Test
645      public static long MEDIUM_DELAY_MS;
646      public static long LONG_DELAY_MS;
647  
648 +    private static final long RANDOM_TIMEOUT;
649 +    private static final long RANDOM_EXPIRED_TIMEOUT;
650 +    private static final TimeUnit RANDOM_TIMEUNIT;
651 +    static {
652 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
653 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
654 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
655 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
656 +        TimeUnit[] timeUnits = TimeUnit.values();
657 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
658 +    }
659 +
660 +    /**
661 +     * Returns a timeout for use when any value at all will do.
662 +     */
663 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
664 +
665 +    /**
666 +     * Returns a timeout that means "no waiting", i.e. not positive.
667 +     */
668 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
669 +
670 +    /**
671 +     * Returns a random non-null TimeUnit.
672 +     */
673 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
674 +
675      /**
676       * Returns the shortest timed delay. This can be scaled up for
677       * slow machines using the jsr166.delay.factor system property,
# Line 652 | Line 692 | public class JSR166TestCase extends Test
692          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
693      }
694  
695 +    private static final long TIMEOUT_DELAY_MS
696 +        = (long) (12.0 * Math.cbrt(delayFactor));
697 +
698      /**
699 <     * Returns a timeout in milliseconds to be used in tests that
700 <     * verify that operations block or time out.
699 >     * Returns a timeout in milliseconds to be used in tests that verify
700 >     * that operations block or time out.  We want this to be longer
701 >     * than the OS scheduling quantum, but not too long, so don't scale
702 >     * linearly with delayFactor; we use "crazy" cube root instead.
703       */
704 <    long timeoutMillis() {
705 <        return SHORT_DELAY_MS / 4;
704 >    static long timeoutMillis() {
705 >        return TIMEOUT_DELAY_MS;
706      }
707  
708      /**
# Line 673 | Line 718 | public class JSR166TestCase extends Test
718       * The first exception encountered if any threadAssertXXX method fails.
719       */
720      private final AtomicReference<Throwable> threadFailure
721 <        = new AtomicReference<Throwable>(null);
721 >        = new AtomicReference<>(null);
722  
723      /**
724       * Records an exception so that it can be rethrown later in the test
# Line 1052 | Line 1097 | public class JSR166TestCase extends Test
1097      }
1098  
1099      /**
1100 <     * Checks that thread does not terminate within the default
1056 <     * millisecond delay of {@code timeoutMillis()}.
1057 <     */
1058 <    void assertThreadStaysAlive(Thread thread) {
1059 <        assertThreadStaysAlive(thread, timeoutMillis());
1060 <    }
1061 <
1062 <    /**
1063 <     * Checks that thread does not terminate within the given millisecond delay.
1100 >     * Checks that thread eventually enters the expected blocked thread state.
1101       */
1102 <    void assertThreadStaysAlive(Thread thread, long millis) {
1103 <        try {
1104 <            // No need to optimize the failing case via Thread.join.
1105 <            delay(millis);
1106 <            assertTrue(thread.isAlive());
1107 <        } catch (InterruptedException fail) {
1108 <            threadFail("Unexpected InterruptedException");
1109 <        }
1110 <    }
1111 <
1112 <    /**
1113 <     * Checks that the threads do not terminate within the default
1114 <     * millisecond delay of {@code timeoutMillis()}.
1078 <     */
1079 <    void assertThreadsStayAlive(Thread... threads) {
1080 <        assertThreadsStayAlive(timeoutMillis(), threads);
1081 <    }
1082 <
1083 <    /**
1084 <     * Checks that the threads do not terminate within the given millisecond delay.
1085 <     */
1086 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1087 <        try {
1088 <            // No need to optimize the failing case via Thread.join.
1089 <            delay(millis);
1090 <            for (Thread thread : threads)
1091 <                assertTrue(thread.isAlive());
1092 <        } catch (InterruptedException fail) {
1093 <            threadFail("Unexpected InterruptedException");
1102 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1103 >        // always sleep at least 1 ms, with high probability avoiding
1104 >        // transitory states
1105 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1106 >            try { delay(1); }
1107 >            catch (InterruptedException fail) {
1108 >                fail("Unexpected InterruptedException");
1109 >            }
1110 >            Thread.State s = thread.getState();
1111 >            if (s == expected)
1112 >                return;
1113 >            else if (s == Thread.State.TERMINATED)
1114 >                fail("Unexpected thread termination");
1115          }
1116 +        fail("timed out waiting for thread to enter thread state " + expected);
1117      }
1118  
1119      /**
# Line 1132 | Line 1154 | public class JSR166TestCase extends Test
1154      }
1155  
1156      /**
1157 +     * The maximum number of consecutive spurious wakeups we should
1158 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1159 +     */
1160 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1161 +
1162 +    /**
1163       * The number of elements to place in collections, arrays, etc.
1164       */
1165      public static final int SIZE = 20;
# Line 1235 | Line 1263 | public class JSR166TestCase extends Test
1263          }
1264          public void refresh() {}
1265          public String toString() {
1266 <            List<Permission> ps = new ArrayList<Permission>();
1266 >            List<Permission> ps = new ArrayList<>();
1267              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1268                  ps.add(e.nextElement());
1269              return "AdjustablePolicy with permissions " + ps;
# Line 1294 | Line 1322 | public class JSR166TestCase extends Test
1322                  startTime = System.nanoTime();
1323              else if (millisElapsedSince(startTime) > timeoutMillis) {
1324                  threadAssertTrue(thread.isAlive());
1325 <                return;
1325 >                fail("timed out waiting for thread to enter wait state");
1326 >            }
1327 >            Thread.yield();
1328 >        }
1329 >    }
1330 >
1331 >    /**
1332 >     * Spin-waits up to the specified number of milliseconds for the given
1333 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1334 >     * and additionally satisfy the given condition.
1335 >     */
1336 >    void waitForThreadToEnterWaitState(
1337 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1338 >        long startTime = 0L;
1339 >        for (;;) {
1340 >            Thread.State s = thread.getState();
1341 >            if (s == Thread.State.BLOCKED ||
1342 >                s == Thread.State.WAITING ||
1343 >                s == Thread.State.TIMED_WAITING) {
1344 >                try {
1345 >                    if (waitingForGodot.call())
1346 >                        return;
1347 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1348 >            }
1349 >            else if (s == Thread.State.TERMINATED)
1350 >                fail("Unexpected thread termination");
1351 >            else if (startTime == 0L)
1352 >                startTime = System.nanoTime();
1353 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1354 >                threadAssertTrue(thread.isAlive());
1355 >                fail("timed out waiting for thread to enter wait state");
1356              }
1357              Thread.yield();
1358          }
1359      }
1360  
1361      /**
1362 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1363 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1362 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1363 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1364       */
1365      void waitForThreadToEnterWaitState(Thread thread) {
1366          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1367      }
1368  
1369      /**
1370 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1371 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1372 +     * and additionally satisfy the given condition.
1373 +     */
1374 +    void waitForThreadToEnterWaitState(
1375 +        Thread thread, Callable<Boolean> waitingForGodot) {
1376 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1377 +    }
1378 +
1379 +    /**
1380       * Returns the number of milliseconds since time given by
1381       * startNanoTime, which must have been previously returned from a
1382       * call to {@link System#nanoTime()}.
# Line 1560 | Line 1628 | public class JSR166TestCase extends Test
1628          }
1629      }
1630  
1631 +    public void await(CyclicBarrier barrier) {
1632 +        try {
1633 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1634 +        } catch (Throwable fail) {
1635 +            threadUnexpectedException(fail);
1636 +        }
1637 +    }
1638 +
1639   //     /**
1640   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1641   //      */
# Line 1583 | Line 1659 | public class JSR166TestCase extends Test
1659          public String call() { throw new NullPointerException(); }
1660      }
1661  
1586    public static class CallableOne implements Callable<Integer> {
1587        public Integer call() { return one; }
1588    }
1589
1590    public class ShortRunnable extends CheckedRunnable {
1591        protected void realRun() throws Throwable {
1592            delay(SHORT_DELAY_MS);
1593        }
1594    }
1595
1596    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1597        protected void realRun() throws InterruptedException {
1598            delay(SHORT_DELAY_MS);
1599        }
1600    }
1601
1602    public class SmallRunnable extends CheckedRunnable {
1603        protected void realRun() throws Throwable {
1604            delay(SMALL_DELAY_MS);
1605        }
1606    }
1607
1662      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1663          protected void realRun() {
1664              try {
# Line 1613 | Line 1667 | public class JSR166TestCase extends Test
1667          }
1668      }
1669  
1616    public class SmallCallable extends CheckedCallable {
1617        protected Object realCall() throws InterruptedException {
1618            delay(SMALL_DELAY_MS);
1619            return Boolean.TRUE;
1620        }
1621    }
1622
1623    public class MediumRunnable extends CheckedRunnable {
1624        protected void realRun() throws Throwable {
1625            delay(MEDIUM_DELAY_MS);
1626        }
1627    }
1628
1629    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1630        protected void realRun() throws InterruptedException {
1631            delay(MEDIUM_DELAY_MS);
1632        }
1633    }
1634
1670      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1671          return new CheckedRunnable() {
1672              protected void realRun() {
# Line 1641 | Line 1676 | public class JSR166TestCase extends Test
1676              }};
1677      }
1678  
1644    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1645        protected void realRun() {
1646            try {
1647                delay(MEDIUM_DELAY_MS);
1648            } catch (InterruptedException ok) {}
1649        }
1650    }
1651
1652    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1653        protected void realRun() {
1654            try {
1655                delay(LONG_DELAY_MS);
1656            } catch (InterruptedException ok) {}
1657        }
1658    }
1659
1679      /**
1680       * For use as ThreadFactory in constructors
1681       */
# Line 1670 | Line 1689 | public class JSR166TestCase extends Test
1689          boolean isDone();
1690      }
1691  
1673    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1674        return new TrackedRunnable() {
1675                private volatile boolean done = false;
1676                public boolean isDone() { return done; }
1677                public void run() {
1678                    try {
1679                        delay(timeoutMillis);
1680                        done = true;
1681                    } catch (InterruptedException ok) {}
1682                }
1683            };
1684    }
1685
1686    public static class TrackedShortRunnable implements Runnable {
1687        public volatile boolean done = false;
1688        public void run() {
1689            try {
1690                delay(SHORT_DELAY_MS);
1691                done = true;
1692            } catch (InterruptedException ok) {}
1693        }
1694    }
1695
1696    public static class TrackedSmallRunnable implements Runnable {
1697        public volatile boolean done = false;
1698        public void run() {
1699            try {
1700                delay(SMALL_DELAY_MS);
1701                done = true;
1702            } catch (InterruptedException ok) {}
1703        }
1704    }
1705
1706    public static class TrackedMediumRunnable implements Runnable {
1707        public volatile boolean done = false;
1708        public void run() {
1709            try {
1710                delay(MEDIUM_DELAY_MS);
1711                done = true;
1712            } catch (InterruptedException ok) {}
1713        }
1714    }
1715
1716    public static class TrackedLongRunnable implements Runnable {
1717        public volatile boolean done = false;
1718        public void run() {
1719            try {
1720                delay(LONG_DELAY_MS);
1721                done = true;
1722            } catch (InterruptedException ok) {}
1723        }
1724    }
1725
1692      public static class TrackedNoOpRunnable implements Runnable {
1693          public volatile boolean done = false;
1694          public void run() {
# Line 1730 | Line 1696 | public class JSR166TestCase extends Test
1696          }
1697      }
1698  
1733    public static class TrackedCallable implements Callable {
1734        public volatile boolean done = false;
1735        public Object call() {
1736            try {
1737                delay(SMALL_DELAY_MS);
1738                done = true;
1739            } catch (InterruptedException ok) {}
1740            return Boolean.TRUE;
1741        }
1742    }
1743
1699      /**
1700       * Analog of CheckedRunnable for RecursiveAction
1701       */
# Line 1807 | Line 1762 | public class JSR166TestCase extends Test
1762              assertEquals(0, q.size());
1763              assertNull(q.peek());
1764              assertNull(q.poll());
1765 <            assertNull(q.poll(0, MILLISECONDS));
1765 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1766              assertEquals(q.toString(), "[]");
1767              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1768              assertFalse(q.iterator().hasNext());
# Line 1958 | Line 1913 | public class JSR166TestCase extends Test
1913      static <T> void shuffle(T[] array) {
1914          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1915      }
1916 +
1917 +    /**
1918 +     * Returns the same String as would be returned by {@link
1919 +     * Object#toString}, whether or not the given object's class
1920 +     * overrides toString().
1921 +     *
1922 +     * @see System#identityHashCode
1923 +     */
1924 +    static String identityString(Object x) {
1925 +        return x.getClass().getName()
1926 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1927 +    }
1928 +
1929 +    // --- Shared assertions for Executor tests ---
1930 +
1931 +    /**
1932 +     * Returns maximum number of tasks that can be submitted to given
1933 +     * pool (with bounded queue) before saturation (when submission
1934 +     * throws RejectedExecutionException).
1935 +     */
1936 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1937 +        BlockingQueue<Runnable> q = pool.getQueue();
1938 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1939 +    }
1940 +
1941 +    @SuppressWarnings("FutureReturnValueIgnored")
1942 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1943 +        try {
1944 +            e.execute((Runnable) null);
1945 +            shouldThrow();
1946 +        } catch (NullPointerException success) {}
1947 +
1948 +        if (! (e instanceof ExecutorService)) return;
1949 +        ExecutorService es = (ExecutorService) e;
1950 +        try {
1951 +            es.submit((Runnable) null);
1952 +            shouldThrow();
1953 +        } catch (NullPointerException success) {}
1954 +        try {
1955 +            es.submit((Runnable) null, Boolean.TRUE);
1956 +            shouldThrow();
1957 +        } catch (NullPointerException success) {}
1958 +        try {
1959 +            es.submit((Callable) null);
1960 +            shouldThrow();
1961 +        } catch (NullPointerException success) {}
1962 +
1963 +        if (! (e instanceof ScheduledExecutorService)) return;
1964 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1965 +        try {
1966 +            ses.schedule((Runnable) null,
1967 +                         randomTimeout(), randomTimeUnit());
1968 +            shouldThrow();
1969 +        } catch (NullPointerException success) {}
1970 +        try {
1971 +            ses.schedule((Callable) null,
1972 +                         randomTimeout(), randomTimeUnit());
1973 +            shouldThrow();
1974 +        } catch (NullPointerException success) {}
1975 +        try {
1976 +            ses.scheduleAtFixedRate((Runnable) null,
1977 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1978 +            shouldThrow();
1979 +        } catch (NullPointerException success) {}
1980 +        try {
1981 +            ses.scheduleWithFixedDelay((Runnable) null,
1982 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1983 +            shouldThrow();
1984 +        } catch (NullPointerException success) {}
1985 +    }
1986 +
1987 +    void setRejectedExecutionHandler(
1988 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1989 +        p.setRejectedExecutionHandler(handler);
1990 +        assertSame(handler, p.getRejectedExecutionHandler());
1991 +    }
1992 +
1993 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1994 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1995 +        final long savedTaskCount = p.getTaskCount();
1996 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1997 +        final int savedQueueSize = p.getQueue().size();
1998 +        final boolean stock = (p.getClass().getClassLoader() == null);
1999 +
2000 +        Runnable r = () -> {};
2001 +        Callable<Boolean> c = () -> Boolean.TRUE;
2002 +
2003 +        class Recorder implements RejectedExecutionHandler {
2004 +            public volatile Runnable r = null;
2005 +            public volatile ThreadPoolExecutor p = null;
2006 +            public void reset() { r = null; p = null; }
2007 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2008 +                assertNull(this.r);
2009 +                assertNull(this.p);
2010 +                this.r = r;
2011 +                this.p = p;
2012 +            }
2013 +        }
2014 +
2015 +        // check custom handler is invoked exactly once per task
2016 +        Recorder recorder = new Recorder();
2017 +        setRejectedExecutionHandler(p, recorder);
2018 +        for (int i = 2; i--> 0; ) {
2019 +            recorder.reset();
2020 +            p.execute(r);
2021 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2022 +                assertSame(r, recorder.r);
2023 +            assertSame(p, recorder.p);
2024 +
2025 +            recorder.reset();
2026 +            assertFalse(p.submit(r).isDone());
2027 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2028 +            assertSame(p, recorder.p);
2029 +
2030 +            recorder.reset();
2031 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2032 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2033 +            assertSame(p, recorder.p);
2034 +
2035 +            recorder.reset();
2036 +            assertFalse(p.submit(c).isDone());
2037 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2038 +            assertSame(p, recorder.p);
2039 +
2040 +            if (p instanceof ScheduledExecutorService) {
2041 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2042 +                ScheduledFuture<?> future;
2043 +
2044 +                recorder.reset();
2045 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2046 +                assertFalse(future.isDone());
2047 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2048 +                assertSame(p, recorder.p);
2049 +
2050 +                recorder.reset();
2051 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2052 +                assertFalse(future.isDone());
2053 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2054 +                assertSame(p, recorder.p);
2055 +
2056 +                recorder.reset();
2057 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2058 +                assertFalse(future.isDone());
2059 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2060 +                assertSame(p, recorder.p);
2061 +
2062 +                recorder.reset();
2063 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2064 +                assertFalse(future.isDone());
2065 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2066 +                assertSame(p, recorder.p);
2067 +            }
2068 +        }
2069 +
2070 +        // Checking our custom handler above should be sufficient, but
2071 +        // we add some integration tests of standard handlers.
2072 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2073 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2074 +
2075 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2076 +        try {
2077 +            p.execute(setThread);
2078 +            shouldThrow();
2079 +        } catch (RejectedExecutionException success) {}
2080 +        assertNull(thread.get());
2081 +
2082 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2083 +        p.execute(setThread);
2084 +        assertNull(thread.get());
2085 +
2086 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2087 +        p.execute(setThread);
2088 +        if (p.isShutdown())
2089 +            assertNull(thread.get());
2090 +        else
2091 +            assertSame(Thread.currentThread(), thread.get());
2092 +
2093 +        setRejectedExecutionHandler(p, savedHandler);
2094 +
2095 +        // check that pool was not perturbed by handlers
2096 +        assertEquals(savedTaskCount, p.getTaskCount());
2097 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2098 +        assertEquals(savedQueueSize, p.getQueue().size());
2099 +    }
2100   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines