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.220 by jsr166, Sat Mar 11 17:33:32 2017 UTC vs.
Revision 1.234 by jsr166, Mon Jul 17 22:27:31 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.base/java.lang:open
23 *          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   */
# Line 74 | 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;
# Line 636 | Line 644 | public class JSR166TestCase extends Test
644      public static long MEDIUM_DELAY_MS;
645      public static long LONG_DELAY_MS;
646  
647 +    private static final long RANDOM_TIMEOUT;
648 +    private static final long RANDOM_EXPIRED_TIMEOUT;
649 +    private static final TimeUnit RANDOM_TIMEUNIT;
650 +    static {
651 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
652 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
653 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
654 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
655 +        TimeUnit[] timeUnits = TimeUnit.values();
656 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
657 +    }
658 +
659 +    /**
660 +     * Returns a timeout for use when any value at all will do.
661 +     */
662 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
663 +
664 +    /**
665 +     * Returns a timeout that means "no waiting", i.e. not positive.
666 +     */
667 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
668 +
669 +    /**
670 +     * Returns a random non-null TimeUnit.
671 +     */
672 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
673 +
674      /**
675       * Returns the shortest timed delay. This can be scaled up for
676       * slow machines using the jsr166.delay.factor system property,
# Line 656 | Line 691 | public class JSR166TestCase extends Test
691          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
692      }
693  
694 +    private static final long TIMEOUT_DELAY_MS
695 +        = (long) (12.0 * Math.cbrt(delayFactor));
696 +
697      /**
698 <     * Returns a timeout in milliseconds to be used in tests that
699 <     * verify that operations block or time out.
698 >     * Returns a timeout in milliseconds to be used in tests that verify
699 >     * that operations block or time out.  We want this to be longer
700 >     * than the OS scheduling quantum, but not too long, so don't scale
701 >     * linearly with delayFactor; we use "crazy" cube root instead.
702       */
703 <    long timeoutMillis() {
704 <        return SHORT_DELAY_MS / 4;
703 >    static long timeoutMillis() {
704 >        return TIMEOUT_DELAY_MS;
705      }
706  
707      /**
# Line 1056 | Line 1096 | public class JSR166TestCase extends Test
1096      }
1097  
1098      /**
1099 +     * Checks that thread eventually enters the expected blocked thread state.
1100 +     */
1101 +    void assertThreadBlocks(Thread thread, Thread.State expected) {
1102 +        // always sleep at least 1 ms, with high probability avoiding
1103 +        // transitory states
1104 +        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1105 +            try { delay(1); }
1106 +            catch (InterruptedException fail) {
1107 +                fail("Unexpected InterruptedException");
1108 +            }
1109 +            Thread.State s = thread.getState();
1110 +            if (s == expected)
1111 +                return;
1112 +            else if (s == Thread.State.TERMINATED)
1113 +                fail("Unexpected thread termination");
1114 +        }
1115 +        fail("timed out waiting for thread to enter thread state " + expected);
1116 +    }
1117 +
1118 +    /**
1119       * Checks that thread does not terminate within the default
1120       * millisecond delay of {@code timeoutMillis()}.
1121 +     * TODO: REMOVEME
1122       */
1123      void assertThreadStaysAlive(Thread thread) {
1124          assertThreadStaysAlive(thread, timeoutMillis());
# Line 1065 | Line 1126 | public class JSR166TestCase extends Test
1126  
1127      /**
1128       * Checks that thread does not terminate within the given millisecond delay.
1129 +     * TODO: REMOVEME
1130       */
1131      void assertThreadStaysAlive(Thread thread, long millis) {
1132          try {
# Line 1079 | Line 1141 | public class JSR166TestCase extends Test
1141      /**
1142       * Checks that the threads do not terminate within the default
1143       * millisecond delay of {@code timeoutMillis()}.
1144 +     * TODO: REMOVEME
1145       */
1146      void assertThreadsStayAlive(Thread... threads) {
1147          assertThreadsStayAlive(timeoutMillis(), threads);
# Line 1086 | Line 1149 | public class JSR166TestCase extends Test
1149  
1150      /**
1151       * Checks that the threads do not terminate within the given millisecond delay.
1152 +     * TODO: REMOVEME
1153       */
1154      void assertThreadsStayAlive(long millis, Thread... threads) {
1155          try {
# Line 1136 | Line 1200 | public class JSR166TestCase extends Test
1200      }
1201  
1202      /**
1203 +     * The maximum number of consecutive spurious wakeups we should
1204 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1205 +     */
1206 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1207 +
1208 +    /**
1209       * The number of elements to place in collections, arrays, etc.
1210       */
1211      public static final int SIZE = 20;
# Line 1604 | Line 1674 | public class JSR166TestCase extends Test
1674          }
1675      }
1676  
1677 +    public void await(CyclicBarrier barrier) {
1678 +        try {
1679 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1680 +        } catch (Throwable fail) {
1681 +            threadUnexpectedException(fail);
1682 +        }
1683 +    }
1684 +
1685   //     /**
1686   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1687   //      */
# Line 1627 | Line 1705 | public class JSR166TestCase extends Test
1705          public String call() { throw new NullPointerException(); }
1706      }
1707  
1630    public static class CallableOne implements Callable<Integer> {
1631        public Integer call() { return one; }
1632    }
1633
1634    public class ShortRunnable extends CheckedRunnable {
1635        protected void realRun() throws Throwable {
1636            delay(SHORT_DELAY_MS);
1637        }
1638    }
1639
1640    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1641        protected void realRun() throws InterruptedException {
1642            delay(SHORT_DELAY_MS);
1643        }
1644    }
1645
1646    public class SmallRunnable extends CheckedRunnable {
1647        protected void realRun() throws Throwable {
1648            delay(SMALL_DELAY_MS);
1649        }
1650    }
1651
1708      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1709          protected void realRun() {
1710              try {
# Line 1657 | Line 1713 | public class JSR166TestCase extends Test
1713          }
1714      }
1715  
1660    public class SmallCallable extends CheckedCallable {
1661        protected Object realCall() throws InterruptedException {
1662            delay(SMALL_DELAY_MS);
1663            return Boolean.TRUE;
1664        }
1665    }
1666
1667    public class MediumRunnable extends CheckedRunnable {
1668        protected void realRun() throws Throwable {
1669            delay(MEDIUM_DELAY_MS);
1670        }
1671    }
1672
1673    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1674        protected void realRun() throws InterruptedException {
1675            delay(MEDIUM_DELAY_MS);
1676        }
1677    }
1678
1716      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1717          return new CheckedRunnable() {
1718              protected void realRun() {
# Line 1685 | Line 1722 | public class JSR166TestCase extends Test
1722              }};
1723      }
1724  
1688    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1689        protected void realRun() {
1690            try {
1691                delay(MEDIUM_DELAY_MS);
1692            } catch (InterruptedException ok) {}
1693        }
1694    }
1695
1696    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1697        protected void realRun() {
1698            try {
1699                delay(LONG_DELAY_MS);
1700            } catch (InterruptedException ok) {}
1701        }
1702    }
1703
1725      /**
1726       * For use as ThreadFactory in constructors
1727       */
# Line 1714 | Line 1735 | public class JSR166TestCase extends Test
1735          boolean isDone();
1736      }
1737  
1717    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1718        return new TrackedRunnable() {
1719                private volatile boolean done = false;
1720                public boolean isDone() { return done; }
1721                public void run() {
1722                    try {
1723                        delay(timeoutMillis);
1724                        done = true;
1725                    } catch (InterruptedException ok) {}
1726                }
1727            };
1728    }
1729
1730    public static class TrackedShortRunnable implements Runnable {
1731        public volatile boolean done = false;
1732        public void run() {
1733            try {
1734                delay(SHORT_DELAY_MS);
1735                done = true;
1736            } catch (InterruptedException ok) {}
1737        }
1738    }
1739
1740    public static class TrackedSmallRunnable implements Runnable {
1741        public volatile boolean done = false;
1742        public void run() {
1743            try {
1744                delay(SMALL_DELAY_MS);
1745                done = true;
1746            } catch (InterruptedException ok) {}
1747        }
1748    }
1749
1750    public static class TrackedMediumRunnable implements Runnable {
1751        public volatile boolean done = false;
1752        public void run() {
1753            try {
1754                delay(MEDIUM_DELAY_MS);
1755                done = true;
1756            } catch (InterruptedException ok) {}
1757        }
1758    }
1759
1760    public static class TrackedLongRunnable implements Runnable {
1761        public volatile boolean done = false;
1762        public void run() {
1763            try {
1764                delay(LONG_DELAY_MS);
1765                done = true;
1766            } catch (InterruptedException ok) {}
1767        }
1768    }
1769
1738      public static class TrackedNoOpRunnable implements Runnable {
1739          public volatile boolean done = false;
1740          public void run() {
# Line 1774 | Line 1742 | public class JSR166TestCase extends Test
1742          }
1743      }
1744  
1777    public static class TrackedCallable implements Callable {
1778        public volatile boolean done = false;
1779        public Object call() {
1780            try {
1781                delay(SMALL_DELAY_MS);
1782                done = true;
1783            } catch (InterruptedException ok) {}
1784            return Boolean.TRUE;
1785        }
1786    }
1787
1745      /**
1746       * Analog of CheckedRunnable for RecursiveAction
1747       */
# Line 1851 | Line 1808 | public class JSR166TestCase extends Test
1808              assertEquals(0, q.size());
1809              assertNull(q.peek());
1810              assertNull(q.poll());
1811 <            assertNull(q.poll(0, MILLISECONDS));
1811 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1812              assertEquals(q.toString(), "[]");
1813              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1814              assertFalse(q.iterator().hasNext());
# Line 2002 | Line 1959 | public class JSR166TestCase extends Test
1959      static <T> void shuffle(T[] array) {
1960          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1961      }
1962 +
1963 +    // --- Shared assertions for Executor tests ---
1964 +
1965 +    /**
1966 +     * Returns maximum number of tasks that can be submitted to given
1967 +     * pool (with bounded queue) before saturation (when submission
1968 +     * throws RejectedExecutionException).
1969 +     */
1970 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1971 +        BlockingQueue<Runnable> q = pool.getQueue();
1972 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1973 +    }
1974 +
1975 +    @SuppressWarnings("FutureReturnValueIgnored")
1976 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1977 +        try {
1978 +            e.execute((Runnable) null);
1979 +            shouldThrow();
1980 +        } catch (NullPointerException success) {}
1981 +
1982 +        if (! (e instanceof ExecutorService)) return;
1983 +        ExecutorService es = (ExecutorService) e;
1984 +        try {
1985 +            es.submit((Runnable) null);
1986 +            shouldThrow();
1987 +        } catch (NullPointerException success) {}
1988 +        try {
1989 +            es.submit((Runnable) null, Boolean.TRUE);
1990 +            shouldThrow();
1991 +        } catch (NullPointerException success) {}
1992 +        try {
1993 +            es.submit((Callable) null);
1994 +            shouldThrow();
1995 +        } catch (NullPointerException success) {}
1996 +
1997 +        if (! (e instanceof ScheduledExecutorService)) return;
1998 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1999 +        try {
2000 +            ses.schedule((Runnable) null,
2001 +                         randomTimeout(), randomTimeUnit());
2002 +            shouldThrow();
2003 +        } catch (NullPointerException success) {}
2004 +        try {
2005 +            ses.schedule((Callable) null,
2006 +                         randomTimeout(), randomTimeUnit());
2007 +            shouldThrow();
2008 +        } catch (NullPointerException success) {}
2009 +        try {
2010 +            ses.scheduleAtFixedRate((Runnable) null,
2011 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2012 +            shouldThrow();
2013 +        } catch (NullPointerException success) {}
2014 +        try {
2015 +            ses.scheduleWithFixedDelay((Runnable) null,
2016 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2017 +            shouldThrow();
2018 +        } catch (NullPointerException success) {}
2019 +    }
2020 +
2021 +    void setRejectedExecutionHandler(
2022 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2023 +        p.setRejectedExecutionHandler(handler);
2024 +        assertSame(handler, p.getRejectedExecutionHandler());
2025 +    }
2026 +
2027 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2028 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2029 +        final long savedTaskCount = p.getTaskCount();
2030 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2031 +        final int savedQueueSize = p.getQueue().size();
2032 +        final boolean stock = (p.getClass().getClassLoader() == null);
2033 +
2034 +        Runnable r = () -> {};
2035 +        Callable<Boolean> c = () -> Boolean.TRUE;
2036 +
2037 +        class Recorder implements RejectedExecutionHandler {
2038 +            public volatile Runnable r = null;
2039 +            public volatile ThreadPoolExecutor p = null;
2040 +            public void reset() { r = null; p = null; }
2041 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2042 +                assertNull(this.r);
2043 +                assertNull(this.p);
2044 +                this.r = r;
2045 +                this.p = p;
2046 +            }
2047 +        }
2048 +
2049 +        // check custom handler is invoked exactly once per task
2050 +        Recorder recorder = new Recorder();
2051 +        setRejectedExecutionHandler(p, recorder);
2052 +        for (int i = 2; i--> 0; ) {
2053 +            recorder.reset();
2054 +            p.execute(r);
2055 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2056 +                assertSame(r, recorder.r);
2057 +            assertSame(p, recorder.p);
2058 +
2059 +            recorder.reset();
2060 +            assertFalse(p.submit(r).isDone());
2061 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2062 +            assertSame(p, recorder.p);
2063 +
2064 +            recorder.reset();
2065 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2066 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2067 +            assertSame(p, recorder.p);
2068 +
2069 +            recorder.reset();
2070 +            assertFalse(p.submit(c).isDone());
2071 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2072 +            assertSame(p, recorder.p);
2073 +
2074 +            if (p instanceof ScheduledExecutorService) {
2075 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2076 +                ScheduledFuture<?> future;
2077 +
2078 +                recorder.reset();
2079 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2080 +                assertFalse(future.isDone());
2081 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2082 +                assertSame(p, recorder.p);
2083 +
2084 +                recorder.reset();
2085 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2086 +                assertFalse(future.isDone());
2087 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2088 +                assertSame(p, recorder.p);
2089 +
2090 +                recorder.reset();
2091 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2092 +                assertFalse(future.isDone());
2093 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2094 +                assertSame(p, recorder.p);
2095 +
2096 +                recorder.reset();
2097 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2098 +                assertFalse(future.isDone());
2099 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2100 +                assertSame(p, recorder.p);
2101 +            }
2102 +        }
2103 +
2104 +        // Checking our custom handler above should be sufficient, but
2105 +        // we add some integration tests of standard handlers.
2106 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2107 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2108 +
2109 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2110 +        try {
2111 +            p.execute(setThread);
2112 +            shouldThrow();
2113 +        } catch (RejectedExecutionException success) {}
2114 +        assertNull(thread.get());
2115 +
2116 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2117 +        p.execute(setThread);
2118 +        assertNull(thread.get());
2119 +
2120 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2121 +        p.execute(setThread);
2122 +        if (p.isShutdown())
2123 +            assertNull(thread.get());
2124 +        else
2125 +            assertSame(Thread.currentThread(), thread.get());
2126 +
2127 +        setRejectedExecutionHandler(p, savedHandler);
2128 +
2129 +        // check that pool was not perturbed by handlers
2130 +        assertEquals(savedTaskCount, p.getTaskCount());
2131 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2132 +        assertEquals(savedQueueSize, p.getQueue().size());
2133 +    }
2134   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines