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.229 by jsr166, Sun May 14 03:15:37 2017 UTC vs.
Revision 1.234 by jsr166, Mon Jul 17 22:27:31 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 1083 | Line 1116 | public class JSR166TestCase extends Test
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());
1125 +    }
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 {
1133 +            // No need to optimize the failing case via Thread.join.
1134 +            delay(millis);
1135 +            assertTrue(thread.isAlive());
1136 +        } catch (InterruptedException fail) {
1137 +            threadFail("Unexpected InterruptedException");
1138 +        }
1139 +    }
1140 +
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);
1148 +    }
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 {
1156 +            // No need to optimize the failing case via Thread.join.
1157 +            delay(millis);
1158 +            for (Thread thread : threads)
1159 +                assertTrue(thread.isAlive());
1160 +        } catch (InterruptedException fail) {
1161 +            threadFail("Unexpected InterruptedException");
1162 +        }
1163 +    }
1164 +
1165 +    /**
1166       * Checks that future.get times out, with the default timeout of
1167       * {@code timeoutMillis()}.
1168       */
# Line 1625 | Line 1705 | public class JSR166TestCase extends Test
1705          public String call() { throw new NullPointerException(); }
1706      }
1707  
1628    public static class CallableOne implements Callable<Integer> {
1629        public Integer call() { return one; }
1630    }
1631
1632    public class ShortRunnable extends CheckedRunnable {
1633        protected void realRun() throws Throwable {
1634            delay(SHORT_DELAY_MS);
1635        }
1636    }
1637
1638    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1639        protected void realRun() throws InterruptedException {
1640            delay(SHORT_DELAY_MS);
1641        }
1642    }
1643
1644    public class SmallRunnable extends CheckedRunnable {
1645        protected void realRun() throws Throwable {
1646            delay(SMALL_DELAY_MS);
1647        }
1648    }
1649
1708      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1709          protected void realRun() {
1710              try {
# Line 1655 | Line 1713 | public class JSR166TestCase extends Test
1713          }
1714      }
1715  
1658    public class SmallCallable extends CheckedCallable {
1659        protected Object realCall() throws InterruptedException {
1660            delay(SMALL_DELAY_MS);
1661            return Boolean.TRUE;
1662        }
1663    }
1664
1665    public class MediumRunnable extends CheckedRunnable {
1666        protected void realRun() throws Throwable {
1667            delay(MEDIUM_DELAY_MS);
1668        }
1669    }
1670
1671    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1672        protected void realRun() throws InterruptedException {
1673            delay(MEDIUM_DELAY_MS);
1674        }
1675    }
1676
1716      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1717          return new CheckedRunnable() {
1718              protected void realRun() {
# Line 1683 | Line 1722 | public class JSR166TestCase extends Test
1722              }};
1723      }
1724  
1686    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1687        protected void realRun() {
1688            try {
1689                delay(MEDIUM_DELAY_MS);
1690            } catch (InterruptedException ok) {}
1691        }
1692    }
1693
1694    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1695        protected void realRun() {
1696            try {
1697                delay(LONG_DELAY_MS);
1698            } catch (InterruptedException ok) {}
1699        }
1700    }
1701
1725      /**
1726       * For use as ThreadFactory in constructors
1727       */
# Line 1712 | Line 1735 | public class JSR166TestCase extends Test
1735          boolean isDone();
1736      }
1737  
1715    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1716        return new TrackedRunnable() {
1717                private volatile boolean done = false;
1718                public boolean isDone() { return done; }
1719                public void run() {
1720                    try {
1721                        delay(timeoutMillis);
1722                        done = true;
1723                    } catch (InterruptedException ok) {}
1724                }
1725            };
1726    }
1727
1728    public static class TrackedShortRunnable implements Runnable {
1729        public volatile boolean done = false;
1730        public void run() {
1731            try {
1732                delay(SHORT_DELAY_MS);
1733                done = true;
1734            } catch (InterruptedException ok) {}
1735        }
1736    }
1737
1738    public static class TrackedSmallRunnable implements Runnable {
1739        public volatile boolean done = false;
1740        public void run() {
1741            try {
1742                delay(SMALL_DELAY_MS);
1743                done = true;
1744            } catch (InterruptedException ok) {}
1745        }
1746    }
1747
1748    public static class TrackedMediumRunnable implements Runnable {
1749        public volatile boolean done = false;
1750        public void run() {
1751            try {
1752                delay(MEDIUM_DELAY_MS);
1753                done = true;
1754            } catch (InterruptedException ok) {}
1755        }
1756    }
1757
1758    public static class TrackedLongRunnable implements Runnable {
1759        public volatile boolean done = false;
1760        public void run() {
1761            try {
1762                delay(LONG_DELAY_MS);
1763                done = true;
1764            } catch (InterruptedException ok) {}
1765        }
1766    }
1767
1738      public static class TrackedNoOpRunnable implements Runnable {
1739          public volatile boolean done = false;
1740          public void run() {
# Line 1772 | Line 1742 | public class JSR166TestCase extends Test
1742          }
1743      }
1744  
1775    public static class TrackedCallable implements Callable {
1776        public volatile boolean done = false;
1777        public Object call() {
1778            try {
1779                delay(SMALL_DELAY_MS);
1780                done = true;
1781            } catch (InterruptedException ok) {}
1782            return Boolean.TRUE;
1783        }
1784    }
1785
1745      /**
1746       * Analog of CheckedRunnable for RecursiveAction
1747       */
# Line 1849 | 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 2000 | 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