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.227 by jsr166, Sun May 14 03:12:05 2017 UTC vs.
Revision 1.237 by jsr166, Wed Aug 23 05:33:00 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 538 | Line 544 | public class JSR166TestCase extends Test
544                  "DoubleAdderTest",
545                  "ForkJoinPool8Test",
546                  "ForkJoinTask8Test",
547 +                "HashMapTest",
548                  "LinkedBlockingDeque8Test",
549                  "LinkedBlockingQueue8Test",
550                  "LongAccumulatorTest",
# Line 638 | 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 1066 | Line 1100 | public class JSR166TestCase extends Test
1100       * Checks that thread eventually enters the expected blocked thread state.
1101       */
1102      void assertThreadBlocks(Thread thread, Thread.State expected) {
1103 <        // always sleep at least 1 ms, avoiding transitional states
1104 <        // with high probability
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) {
# Line 1083 | Line 1117 | public class JSR166TestCase extends Test
1117      }
1118  
1119      /**
1086     * Checks that thread does not terminate within the default
1087     * millisecond delay of {@code timeoutMillis()}.
1088     */
1089    void assertThreadStaysAlive(Thread thread) {
1090        assertThreadStaysAlive(thread, timeoutMillis());
1091    }
1092
1093    /**
1094     * Checks that thread does not terminate within the given millisecond delay.
1095     */
1096    void assertThreadStaysAlive(Thread thread, long millis) {
1097        try {
1098            // No need to optimize the failing case via Thread.join.
1099            delay(millis);
1100            assertTrue(thread.isAlive());
1101        } catch (InterruptedException fail) {
1102            threadFail("Unexpected InterruptedException");
1103        }
1104    }
1105
1106    /**
1120       * Checks that future.get times out, with the default timeout of
1121       * {@code timeoutMillis()}.
1122       */
# Line 1646 | Line 1659 | public class JSR166TestCase extends Test
1659          public String call() { throw new NullPointerException(); }
1660      }
1661  
1649    public static class CallableOne implements Callable<Integer> {
1650        public Integer call() { return one; }
1651    }
1652
1653    public class ShortRunnable extends CheckedRunnable {
1654        protected void realRun() throws Throwable {
1655            delay(SHORT_DELAY_MS);
1656        }
1657    }
1658
1659    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1660        protected void realRun() throws InterruptedException {
1661            delay(SHORT_DELAY_MS);
1662        }
1663    }
1664
1665    public class SmallRunnable extends CheckedRunnable {
1666        protected void realRun() throws Throwable {
1667            delay(SMALL_DELAY_MS);
1668        }
1669    }
1670
1662      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1663          protected void realRun() {
1664              try {
# Line 1676 | Line 1667 | public class JSR166TestCase extends Test
1667          }
1668      }
1669  
1679    public class SmallCallable extends CheckedCallable {
1680        protected Object realCall() throws InterruptedException {
1681            delay(SMALL_DELAY_MS);
1682            return Boolean.TRUE;
1683        }
1684    }
1685
1686    public class MediumRunnable extends CheckedRunnable {
1687        protected void realRun() throws Throwable {
1688            delay(MEDIUM_DELAY_MS);
1689        }
1690    }
1691
1692    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1693        protected void realRun() throws InterruptedException {
1694            delay(MEDIUM_DELAY_MS);
1695        }
1696    }
1697
1670      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1671          return new CheckedRunnable() {
1672              protected void realRun() {
# Line 1704 | Line 1676 | public class JSR166TestCase extends Test
1676              }};
1677      }
1678  
1707    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1708        protected void realRun() {
1709            try {
1710                delay(MEDIUM_DELAY_MS);
1711            } catch (InterruptedException ok) {}
1712        }
1713    }
1714
1715    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1716        protected void realRun() {
1717            try {
1718                delay(LONG_DELAY_MS);
1719            } catch (InterruptedException ok) {}
1720        }
1721    }
1722
1679      /**
1680       * For use as ThreadFactory in constructors
1681       */
# Line 1733 | Line 1689 | public class JSR166TestCase extends Test
1689          boolean isDone();
1690      }
1691  
1736    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1737        return new TrackedRunnable() {
1738                private volatile boolean done = false;
1739                public boolean isDone() { return done; }
1740                public void run() {
1741                    try {
1742                        delay(timeoutMillis);
1743                        done = true;
1744                    } catch (InterruptedException ok) {}
1745                }
1746            };
1747    }
1748
1749    public static class TrackedShortRunnable implements Runnable {
1750        public volatile boolean done = false;
1751        public void run() {
1752            try {
1753                delay(SHORT_DELAY_MS);
1754                done = true;
1755            } catch (InterruptedException ok) {}
1756        }
1757    }
1758
1759    public static class TrackedSmallRunnable implements Runnable {
1760        public volatile boolean done = false;
1761        public void run() {
1762            try {
1763                delay(SMALL_DELAY_MS);
1764                done = true;
1765            } catch (InterruptedException ok) {}
1766        }
1767    }
1768
1769    public static class TrackedMediumRunnable implements Runnable {
1770        public volatile boolean done = false;
1771        public void run() {
1772            try {
1773                delay(MEDIUM_DELAY_MS);
1774                done = true;
1775            } catch (InterruptedException ok) {}
1776        }
1777    }
1778
1779    public static class TrackedLongRunnable implements Runnable {
1780        public volatile boolean done = false;
1781        public void run() {
1782            try {
1783                delay(LONG_DELAY_MS);
1784                done = true;
1785            } catch (InterruptedException ok) {}
1786        }
1787    }
1788
1692      public static class TrackedNoOpRunnable implements Runnable {
1693          public volatile boolean done = false;
1694          public void run() {
# Line 1793 | Line 1696 | public class JSR166TestCase extends Test
1696          }
1697      }
1698  
1796    public static class TrackedCallable implements Callable {
1797        public volatile boolean done = false;
1798        public Object call() {
1799            try {
1800                delay(SMALL_DELAY_MS);
1801                done = true;
1802            } catch (InterruptedException ok) {}
1803            return Boolean.TRUE;
1804        }
1805    }
1806
1699      /**
1700       * Analog of CheckedRunnable for RecursiveAction
1701       */
# Line 1870 | 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 2021 | 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