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.222 by jsr166, Fri May 12 18:12:51 2017 UTC vs.
Revision 1.238 by jsr166, Mon Dec 11 00:27:08 2017 UTC

# Line 76 | 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 439 | Line 445 | public class JSR166TestCase extends Test
445          }
446      }
447  
448 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
449 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
450 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
451 <    public static boolean atLeastJava9() {
452 <        return JAVA_CLASS_VERSION >= 53.0
447 <            // As of 2015-09, java9 still uses 52.0 class file version
448 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
449 <    }
450 <    public static boolean atLeastJava10() {
451 <        return JAVA_CLASS_VERSION >= 54.0
452 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
453 <    }
448 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
449 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
450 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
451 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
452 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
453  
454      /**
455       * Collects all JSR166 unit tests as one suite.
# Line 538 | Line 537 | public class JSR166TestCase extends Test
537                  "DoubleAdderTest",
538                  "ForkJoinPool8Test",
539                  "ForkJoinTask8Test",
540 +                "HashMapTest",
541                  "LinkedBlockingDeque8Test",
542                  "LinkedBlockingQueue8Test",
543                  "LongAccumulatorTest",
# Line 638 | Line 638 | public class JSR166TestCase extends Test
638      public static long MEDIUM_DELAY_MS;
639      public static long LONG_DELAY_MS;
640  
641 +    private static final long RANDOM_TIMEOUT;
642 +    private static final long RANDOM_EXPIRED_TIMEOUT;
643 +    private static final TimeUnit RANDOM_TIMEUNIT;
644 +    static {
645 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
646 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
647 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
648 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
649 +        TimeUnit[] timeUnits = TimeUnit.values();
650 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
651 +    }
652 +
653 +    /**
654 +     * Returns a timeout for use when any value at all will do.
655 +     */
656 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
657 +
658 +    /**
659 +     * Returns a timeout that means "no waiting", i.e. not positive.
660 +     */
661 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
662 +
663 +    /**
664 +     * Returns a random non-null TimeUnit.
665 +     */
666 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
667 +
668      /**
669       * Returns the shortest timed delay. This can be scaled up for
670       * slow machines using the jsr166.delay.factor system property,
# Line 658 | Line 685 | public class JSR166TestCase extends Test
685          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
686      }
687  
688 +    private static final long TIMEOUT_DELAY_MS
689 +        = (long) (12.0 * Math.cbrt(delayFactor));
690 +
691      /**
692 <     * Returns a timeout in milliseconds to be used in tests that
693 <     * verify that operations block or time out.
692 >     * Returns a timeout in milliseconds to be used in tests that verify
693 >     * that operations block or time out.  We want this to be longer
694 >     * than the OS scheduling quantum, but not too long, so don't scale
695 >     * linearly with delayFactor; we use "crazy" cube root instead.
696       */
697 <    long timeoutMillis() {
698 <        return SHORT_DELAY_MS / 4;
697 >    static long timeoutMillis() {
698 >        return TIMEOUT_DELAY_MS;
699      }
700  
701      /**
# Line 1058 | Line 1090 | public class JSR166TestCase extends Test
1090      }
1091  
1092      /**
1093 <     * Checks that thread does not terminate within the default
1062 <     * millisecond delay of {@code timeoutMillis()}.
1063 <     */
1064 <    void assertThreadStaysAlive(Thread thread) {
1065 <        assertThreadStaysAlive(thread, timeoutMillis());
1066 <    }
1067 <
1068 <    /**
1069 <     * Checks that thread does not terminate within the given millisecond delay.
1093 >     * Checks that thread eventually enters the expected blocked thread state.
1094       */
1095 <    void assertThreadStaysAlive(Thread thread, long millis) {
1096 <        try {
1097 <            // No need to optimize the failing case via Thread.join.
1098 <            delay(millis);
1099 <            assertTrue(thread.isAlive());
1100 <        } catch (InterruptedException fail) {
1101 <            threadFail("Unexpected InterruptedException");
1102 <        }
1103 <    }
1104 <
1105 <    /**
1106 <     * Checks that the threads do not terminate within the default
1107 <     * millisecond delay of {@code timeoutMillis()}.
1084 <     */
1085 <    void assertThreadsStayAlive(Thread... threads) {
1086 <        assertThreadsStayAlive(timeoutMillis(), threads);
1087 <    }
1088 <
1089 <    /**
1090 <     * Checks that the threads do not terminate within the given millisecond delay.
1091 <     */
1092 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1093 <        try {
1094 <            // No need to optimize the failing case via Thread.join.
1095 <            delay(millis);
1096 <            for (Thread thread : threads)
1097 <                assertTrue(thread.isAlive());
1098 <        } catch (InterruptedException fail) {
1099 <            threadFail("Unexpected InterruptedException");
1095 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1096 >        // always sleep at least 1 ms, with high probability avoiding
1097 >        // transitory states
1098 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1099 >            try { delay(1); }
1100 >            catch (InterruptedException fail) {
1101 >                fail("Unexpected InterruptedException");
1102 >            }
1103 >            Thread.State s = thread.getState();
1104 >            if (s == expected)
1105 >                return;
1106 >            else if (s == Thread.State.TERMINATED)
1107 >                fail("Unexpected thread termination");
1108          }
1109 +        fail("timed out waiting for thread to enter thread state " + expected);
1110      }
1111  
1112      /**
# Line 1612 | Line 1621 | public class JSR166TestCase extends Test
1621          }
1622      }
1623  
1624 +    public void await(CyclicBarrier barrier) {
1625 +        try {
1626 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1627 +        } catch (Throwable fail) {
1628 +            threadUnexpectedException(fail);
1629 +        }
1630 +    }
1631 +
1632   //     /**
1633   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1634   //      */
# Line 1635 | Line 1652 | public class JSR166TestCase extends Test
1652          public String call() { throw new NullPointerException(); }
1653      }
1654  
1638    public static class CallableOne implements Callable<Integer> {
1639        public Integer call() { return one; }
1640    }
1641
1642    public class ShortRunnable extends CheckedRunnable {
1643        protected void realRun() throws Throwable {
1644            delay(SHORT_DELAY_MS);
1645        }
1646    }
1647
1648    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1649        protected void realRun() throws InterruptedException {
1650            delay(SHORT_DELAY_MS);
1651        }
1652    }
1653
1654    public class SmallRunnable extends CheckedRunnable {
1655        protected void realRun() throws Throwable {
1656            delay(SMALL_DELAY_MS);
1657        }
1658    }
1659
1655      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1656          protected void realRun() {
1657              try {
# Line 1665 | Line 1660 | public class JSR166TestCase extends Test
1660          }
1661      }
1662  
1668    public class SmallCallable extends CheckedCallable {
1669        protected Object realCall() throws InterruptedException {
1670            delay(SMALL_DELAY_MS);
1671            return Boolean.TRUE;
1672        }
1673    }
1674
1675    public class MediumRunnable extends CheckedRunnable {
1676        protected void realRun() throws Throwable {
1677            delay(MEDIUM_DELAY_MS);
1678        }
1679    }
1680
1681    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1682        protected void realRun() throws InterruptedException {
1683            delay(MEDIUM_DELAY_MS);
1684        }
1685    }
1686
1663      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1664          return new CheckedRunnable() {
1665              protected void realRun() {
# Line 1693 | Line 1669 | public class JSR166TestCase extends Test
1669              }};
1670      }
1671  
1696    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1697        protected void realRun() {
1698            try {
1699                delay(MEDIUM_DELAY_MS);
1700            } catch (InterruptedException ok) {}
1701        }
1702    }
1703
1704    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1705        protected void realRun() {
1706            try {
1707                delay(LONG_DELAY_MS);
1708            } catch (InterruptedException ok) {}
1709        }
1710    }
1711
1672      /**
1673       * For use as ThreadFactory in constructors
1674       */
# Line 1722 | Line 1682 | public class JSR166TestCase extends Test
1682          boolean isDone();
1683      }
1684  
1725    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1726        return new TrackedRunnable() {
1727                private volatile boolean done = false;
1728                public boolean isDone() { return done; }
1729                public void run() {
1730                    try {
1731                        delay(timeoutMillis);
1732                        done = true;
1733                    } catch (InterruptedException ok) {}
1734                }
1735            };
1736    }
1737
1738    public static class TrackedShortRunnable implements Runnable {
1739        public volatile boolean done = false;
1740        public void run() {
1741            try {
1742                delay(SHORT_DELAY_MS);
1743                done = true;
1744            } catch (InterruptedException ok) {}
1745        }
1746    }
1747
1748    public static class TrackedSmallRunnable implements Runnable {
1749        public volatile boolean done = false;
1750        public void run() {
1751            try {
1752                delay(SMALL_DELAY_MS);
1753                done = true;
1754            } catch (InterruptedException ok) {}
1755        }
1756    }
1757
1758    public static class TrackedMediumRunnable implements Runnable {
1759        public volatile boolean done = false;
1760        public void run() {
1761            try {
1762                delay(MEDIUM_DELAY_MS);
1763                done = true;
1764            } catch (InterruptedException ok) {}
1765        }
1766    }
1767
1768    public static class TrackedLongRunnable implements Runnable {
1769        public volatile boolean done = false;
1770        public void run() {
1771            try {
1772                delay(LONG_DELAY_MS);
1773                done = true;
1774            } catch (InterruptedException ok) {}
1775        }
1776    }
1777
1685      public static class TrackedNoOpRunnable implements Runnable {
1686          public volatile boolean done = false;
1687          public void run() {
# Line 1782 | Line 1689 | public class JSR166TestCase extends Test
1689          }
1690      }
1691  
1785    public static class TrackedCallable implements Callable {
1786        public volatile boolean done = false;
1787        public Object call() {
1788            try {
1789                delay(SMALL_DELAY_MS);
1790                done = true;
1791            } catch (InterruptedException ok) {}
1792            return Boolean.TRUE;
1793        }
1794    }
1795
1692      /**
1693       * Analog of CheckedRunnable for RecursiveAction
1694       */
# Line 1859 | Line 1755 | public class JSR166TestCase extends Test
1755              assertEquals(0, q.size());
1756              assertNull(q.peek());
1757              assertNull(q.poll());
1758 <            assertNull(q.poll(0, MILLISECONDS));
1758 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1759              assertEquals(q.toString(), "[]");
1760              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1761              assertFalse(q.iterator().hasNext());
# Line 2010 | Line 1906 | public class JSR166TestCase extends Test
1906      static <T> void shuffle(T[] array) {
1907          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1908      }
1909 +
1910 +    /**
1911 +     * Returns the same String as would be returned by {@link
1912 +     * Object#toString}, whether or not the given object's class
1913 +     * overrides toString().
1914 +     *
1915 +     * @see System#identityHashCode
1916 +     */
1917 +    static String identityString(Object x) {
1918 +        return x.getClass().getName()
1919 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1920 +    }
1921 +
1922 +    // --- Shared assertions for Executor tests ---
1923 +
1924 +    /**
1925 +     * Returns maximum number of tasks that can be submitted to given
1926 +     * pool (with bounded queue) before saturation (when submission
1927 +     * throws RejectedExecutionException).
1928 +     */
1929 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1930 +        BlockingQueue<Runnable> q = pool.getQueue();
1931 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1932 +    }
1933 +
1934 +    @SuppressWarnings("FutureReturnValueIgnored")
1935 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1936 +        try {
1937 +            e.execute((Runnable) null);
1938 +            shouldThrow();
1939 +        } catch (NullPointerException success) {}
1940 +
1941 +        if (! (e instanceof ExecutorService)) return;
1942 +        ExecutorService es = (ExecutorService) e;
1943 +        try {
1944 +            es.submit((Runnable) null);
1945 +            shouldThrow();
1946 +        } catch (NullPointerException success) {}
1947 +        try {
1948 +            es.submit((Runnable) null, Boolean.TRUE);
1949 +            shouldThrow();
1950 +        } catch (NullPointerException success) {}
1951 +        try {
1952 +            es.submit((Callable) null);
1953 +            shouldThrow();
1954 +        } catch (NullPointerException success) {}
1955 +
1956 +        if (! (e instanceof ScheduledExecutorService)) return;
1957 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1958 +        try {
1959 +            ses.schedule((Runnable) null,
1960 +                         randomTimeout(), randomTimeUnit());
1961 +            shouldThrow();
1962 +        } catch (NullPointerException success) {}
1963 +        try {
1964 +            ses.schedule((Callable) null,
1965 +                         randomTimeout(), randomTimeUnit());
1966 +            shouldThrow();
1967 +        } catch (NullPointerException success) {}
1968 +        try {
1969 +            ses.scheduleAtFixedRate((Runnable) null,
1970 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1971 +            shouldThrow();
1972 +        } catch (NullPointerException success) {}
1973 +        try {
1974 +            ses.scheduleWithFixedDelay((Runnable) null,
1975 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1976 +            shouldThrow();
1977 +        } catch (NullPointerException success) {}
1978 +    }
1979 +
1980 +    void setRejectedExecutionHandler(
1981 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1982 +        p.setRejectedExecutionHandler(handler);
1983 +        assertSame(handler, p.getRejectedExecutionHandler());
1984 +    }
1985 +
1986 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1987 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1988 +        final long savedTaskCount = p.getTaskCount();
1989 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1990 +        final int savedQueueSize = p.getQueue().size();
1991 +        final boolean stock = (p.getClass().getClassLoader() == null);
1992 +
1993 +        Runnable r = () -> {};
1994 +        Callable<Boolean> c = () -> Boolean.TRUE;
1995 +
1996 +        class Recorder implements RejectedExecutionHandler {
1997 +            public volatile Runnable r = null;
1998 +            public volatile ThreadPoolExecutor p = null;
1999 +            public void reset() { r = null; p = null; }
2000 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2001 +                assertNull(this.r);
2002 +                assertNull(this.p);
2003 +                this.r = r;
2004 +                this.p = p;
2005 +            }
2006 +        }
2007 +
2008 +        // check custom handler is invoked exactly once per task
2009 +        Recorder recorder = new Recorder();
2010 +        setRejectedExecutionHandler(p, recorder);
2011 +        for (int i = 2; i--> 0; ) {
2012 +            recorder.reset();
2013 +            p.execute(r);
2014 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2015 +                assertSame(r, recorder.r);
2016 +            assertSame(p, recorder.p);
2017 +
2018 +            recorder.reset();
2019 +            assertFalse(p.submit(r).isDone());
2020 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2021 +            assertSame(p, recorder.p);
2022 +
2023 +            recorder.reset();
2024 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2025 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2026 +            assertSame(p, recorder.p);
2027 +
2028 +            recorder.reset();
2029 +            assertFalse(p.submit(c).isDone());
2030 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2031 +            assertSame(p, recorder.p);
2032 +
2033 +            if (p instanceof ScheduledExecutorService) {
2034 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2035 +                ScheduledFuture<?> future;
2036 +
2037 +                recorder.reset();
2038 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2039 +                assertFalse(future.isDone());
2040 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2041 +                assertSame(p, recorder.p);
2042 +
2043 +                recorder.reset();
2044 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2045 +                assertFalse(future.isDone());
2046 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2047 +                assertSame(p, recorder.p);
2048 +
2049 +                recorder.reset();
2050 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2051 +                assertFalse(future.isDone());
2052 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2053 +                assertSame(p, recorder.p);
2054 +
2055 +                recorder.reset();
2056 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2057 +                assertFalse(future.isDone());
2058 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2059 +                assertSame(p, recorder.p);
2060 +            }
2061 +        }
2062 +
2063 +        // Checking our custom handler above should be sufficient, but
2064 +        // we add some integration tests of standard handlers.
2065 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2066 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2067 +
2068 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2069 +        try {
2070 +            p.execute(setThread);
2071 +            shouldThrow();
2072 +        } catch (RejectedExecutionException success) {}
2073 +        assertNull(thread.get());
2074 +
2075 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2076 +        p.execute(setThread);
2077 +        assertNull(thread.get());
2078 +
2079 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2080 +        p.execute(setThread);
2081 +        if (p.isShutdown())
2082 +            assertNull(thread.get());
2083 +        else
2084 +            assertSame(Thread.currentThread(), thread.get());
2085 +
2086 +        setRejectedExecutionHandler(p, savedHandler);
2087 +
2088 +        // check that pool was not perturbed by handlers
2089 +        assertEquals(savedTaskCount, p.getTaskCount());
2090 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2091 +        assertEquals(savedQueueSize, p.getQueue().size());
2092 +    }
2093   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines