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.226 by jsr166, Sun May 14 00:37:42 2017 UTC vs.
Revision 1.235 by jsr166, Sat Jul 22 18:23:59 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 638 | 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 1066 | Line 1099 | public class JSR166TestCase extends Test
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, avoiding transitional states
1103 <        // with high probability
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) {
# Line 1083 | Line 1116 | public class JSR166TestCase extends Test
1116      }
1117  
1118      /**
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    /**
1107     * Checks that the threads do not terminate within the default
1108     * millisecond delay of {@code timeoutMillis()}.
1109     */
1110    void assertThreadsStayAlive(Thread... threads) {
1111        assertThreadsStayAlive(timeoutMillis(), threads);
1112    }
1113
1114    /**
1115     * Checks that the threads do not terminate within the given millisecond delay.
1116     */
1117    void assertThreadsStayAlive(long millis, Thread... threads) {
1118        try {
1119            // No need to optimize the failing case via Thread.join.
1120            delay(millis);
1121            for (Thread thread : threads)
1122                assertTrue(thread.isAlive());
1123        } catch (InterruptedException fail) {
1124            threadFail("Unexpected InterruptedException");
1125        }
1126    }
1127
1128    /**
1119       * Checks that future.get times out, with the default timeout of
1120       * {@code timeoutMillis()}.
1121       */
# Line 1668 | Line 1658 | public class JSR166TestCase extends Test
1658          public String call() { throw new NullPointerException(); }
1659      }
1660  
1671    public static class CallableOne implements Callable<Integer> {
1672        public Integer call() { return one; }
1673    }
1674
1675    public class ShortRunnable extends CheckedRunnable {
1676        protected void realRun() throws Throwable {
1677            delay(SHORT_DELAY_MS);
1678        }
1679    }
1680
1681    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1682        protected void realRun() throws InterruptedException {
1683            delay(SHORT_DELAY_MS);
1684        }
1685    }
1686
1687    public class SmallRunnable extends CheckedRunnable {
1688        protected void realRun() throws Throwable {
1689            delay(SMALL_DELAY_MS);
1690        }
1691    }
1692
1661      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1662          protected void realRun() {
1663              try {
# Line 1698 | Line 1666 | public class JSR166TestCase extends Test
1666          }
1667      }
1668  
1701    public class SmallCallable extends CheckedCallable {
1702        protected Object realCall() throws InterruptedException {
1703            delay(SMALL_DELAY_MS);
1704            return Boolean.TRUE;
1705        }
1706    }
1707
1708    public class MediumRunnable extends CheckedRunnable {
1709        protected void realRun() throws Throwable {
1710            delay(MEDIUM_DELAY_MS);
1711        }
1712    }
1713
1714    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1715        protected void realRun() throws InterruptedException {
1716            delay(MEDIUM_DELAY_MS);
1717        }
1718    }
1719
1669      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1670          return new CheckedRunnable() {
1671              protected void realRun() {
# Line 1726 | Line 1675 | public class JSR166TestCase extends Test
1675              }};
1676      }
1677  
1729    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1730        protected void realRun() {
1731            try {
1732                delay(MEDIUM_DELAY_MS);
1733            } catch (InterruptedException ok) {}
1734        }
1735    }
1736
1737    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1738        protected void realRun() {
1739            try {
1740                delay(LONG_DELAY_MS);
1741            } catch (InterruptedException ok) {}
1742        }
1743    }
1744
1678      /**
1679       * For use as ThreadFactory in constructors
1680       */
# Line 1755 | Line 1688 | public class JSR166TestCase extends Test
1688          boolean isDone();
1689      }
1690  
1758    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1759        return new TrackedRunnable() {
1760                private volatile boolean done = false;
1761                public boolean isDone() { return done; }
1762                public void run() {
1763                    try {
1764                        delay(timeoutMillis);
1765                        done = true;
1766                    } catch (InterruptedException ok) {}
1767                }
1768            };
1769    }
1770
1771    public static class TrackedShortRunnable implements Runnable {
1772        public volatile boolean done = false;
1773        public void run() {
1774            try {
1775                delay(SHORT_DELAY_MS);
1776                done = true;
1777            } catch (InterruptedException ok) {}
1778        }
1779    }
1780
1781    public static class TrackedSmallRunnable implements Runnable {
1782        public volatile boolean done = false;
1783        public void run() {
1784            try {
1785                delay(SMALL_DELAY_MS);
1786                done = true;
1787            } catch (InterruptedException ok) {}
1788        }
1789    }
1790
1791    public static class TrackedMediumRunnable implements Runnable {
1792        public volatile boolean done = false;
1793        public void run() {
1794            try {
1795                delay(MEDIUM_DELAY_MS);
1796                done = true;
1797            } catch (InterruptedException ok) {}
1798        }
1799    }
1800
1801    public static class TrackedLongRunnable implements Runnable {
1802        public volatile boolean done = false;
1803        public void run() {
1804            try {
1805                delay(LONG_DELAY_MS);
1806                done = true;
1807            } catch (InterruptedException ok) {}
1808        }
1809    }
1810
1691      public static class TrackedNoOpRunnable implements Runnable {
1692          public volatile boolean done = false;
1693          public void run() {
# Line 1815 | Line 1695 | public class JSR166TestCase extends Test
1695          }
1696      }
1697  
1818    public static class TrackedCallable implements Callable {
1819        public volatile boolean done = false;
1820        public Object call() {
1821            try {
1822                delay(SMALL_DELAY_MS);
1823                done = true;
1824            } catch (InterruptedException ok) {}
1825            return Boolean.TRUE;
1826        }
1827    }
1828
1698      /**
1699       * Analog of CheckedRunnable for RecursiveAction
1700       */
# Line 1892 | Line 1761 | public class JSR166TestCase extends Test
1761              assertEquals(0, q.size());
1762              assertNull(q.peek());
1763              assertNull(q.poll());
1764 <            assertNull(q.poll(0, MILLISECONDS));
1764 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1765              assertEquals(q.toString(), "[]");
1766              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1767              assertFalse(q.iterator().hasNext());
# Line 2043 | Line 1912 | public class JSR166TestCase extends Test
1912      static <T> void shuffle(T[] array) {
1913          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1914      }
1915 +
1916 +    // --- Shared assertions for Executor tests ---
1917 +
1918 +    /**
1919 +     * Returns maximum number of tasks that can be submitted to given
1920 +     * pool (with bounded queue) before saturation (when submission
1921 +     * throws RejectedExecutionException).
1922 +     */
1923 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1924 +        BlockingQueue<Runnable> q = pool.getQueue();
1925 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1926 +    }
1927 +
1928 +    @SuppressWarnings("FutureReturnValueIgnored")
1929 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1930 +        try {
1931 +            e.execute((Runnable) null);
1932 +            shouldThrow();
1933 +        } catch (NullPointerException success) {}
1934 +
1935 +        if (! (e instanceof ExecutorService)) return;
1936 +        ExecutorService es = (ExecutorService) e;
1937 +        try {
1938 +            es.submit((Runnable) null);
1939 +            shouldThrow();
1940 +        } catch (NullPointerException success) {}
1941 +        try {
1942 +            es.submit((Runnable) null, Boolean.TRUE);
1943 +            shouldThrow();
1944 +        } catch (NullPointerException success) {}
1945 +        try {
1946 +            es.submit((Callable) null);
1947 +            shouldThrow();
1948 +        } catch (NullPointerException success) {}
1949 +
1950 +        if (! (e instanceof ScheduledExecutorService)) return;
1951 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1952 +        try {
1953 +            ses.schedule((Runnable) null,
1954 +                         randomTimeout(), randomTimeUnit());
1955 +            shouldThrow();
1956 +        } catch (NullPointerException success) {}
1957 +        try {
1958 +            ses.schedule((Callable) null,
1959 +                         randomTimeout(), randomTimeUnit());
1960 +            shouldThrow();
1961 +        } catch (NullPointerException success) {}
1962 +        try {
1963 +            ses.scheduleAtFixedRate((Runnable) null,
1964 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1965 +            shouldThrow();
1966 +        } catch (NullPointerException success) {}
1967 +        try {
1968 +            ses.scheduleWithFixedDelay((Runnable) null,
1969 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1970 +            shouldThrow();
1971 +        } catch (NullPointerException success) {}
1972 +    }
1973 +
1974 +    void setRejectedExecutionHandler(
1975 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1976 +        p.setRejectedExecutionHandler(handler);
1977 +        assertSame(handler, p.getRejectedExecutionHandler());
1978 +    }
1979 +
1980 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1981 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1982 +        final long savedTaskCount = p.getTaskCount();
1983 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1984 +        final int savedQueueSize = p.getQueue().size();
1985 +        final boolean stock = (p.getClass().getClassLoader() == null);
1986 +
1987 +        Runnable r = () -> {};
1988 +        Callable<Boolean> c = () -> Boolean.TRUE;
1989 +
1990 +        class Recorder implements RejectedExecutionHandler {
1991 +            public volatile Runnable r = null;
1992 +            public volatile ThreadPoolExecutor p = null;
1993 +            public void reset() { r = null; p = null; }
1994 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1995 +                assertNull(this.r);
1996 +                assertNull(this.p);
1997 +                this.r = r;
1998 +                this.p = p;
1999 +            }
2000 +        }
2001 +
2002 +        // check custom handler is invoked exactly once per task
2003 +        Recorder recorder = new Recorder();
2004 +        setRejectedExecutionHandler(p, recorder);
2005 +        for (int i = 2; i--> 0; ) {
2006 +            recorder.reset();
2007 +            p.execute(r);
2008 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2009 +                assertSame(r, recorder.r);
2010 +            assertSame(p, recorder.p);
2011 +
2012 +            recorder.reset();
2013 +            assertFalse(p.submit(r).isDone());
2014 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2015 +            assertSame(p, recorder.p);
2016 +
2017 +            recorder.reset();
2018 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2019 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2020 +            assertSame(p, recorder.p);
2021 +
2022 +            recorder.reset();
2023 +            assertFalse(p.submit(c).isDone());
2024 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2025 +            assertSame(p, recorder.p);
2026 +
2027 +            if (p instanceof ScheduledExecutorService) {
2028 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2029 +                ScheduledFuture<?> future;
2030 +
2031 +                recorder.reset();
2032 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2033 +                assertFalse(future.isDone());
2034 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2035 +                assertSame(p, recorder.p);
2036 +
2037 +                recorder.reset();
2038 +                future = s.schedule(c, 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.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2045 +                assertFalse(future.isDone());
2046 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2047 +                assertSame(p, recorder.p);
2048 +
2049 +                recorder.reset();
2050 +                future = s.scheduleWithFixedDelay(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 +        }
2056 +
2057 +        // Checking our custom handler above should be sufficient, but
2058 +        // we add some integration tests of standard handlers.
2059 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2060 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2061 +
2062 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2063 +        try {
2064 +            p.execute(setThread);
2065 +            shouldThrow();
2066 +        } catch (RejectedExecutionException success) {}
2067 +        assertNull(thread.get());
2068 +
2069 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2070 +        p.execute(setThread);
2071 +        assertNull(thread.get());
2072 +
2073 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2074 +        p.execute(setThread);
2075 +        if (p.isShutdown())
2076 +            assertNull(thread.get());
2077 +        else
2078 +            assertSame(Thread.currentThread(), thread.get());
2079 +
2080 +        setRejectedExecutionHandler(p, savedHandler);
2081 +
2082 +        // check that pool was not perturbed by handlers
2083 +        assertEquals(savedTaskCount, p.getTaskCount());
2084 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2085 +        assertEquals(savedQueueSize, p.getQueue().size());
2086 +    }
2087   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines