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.233 by jsr166, Sat Jul 15 23:15:21 2017 UTC vs.
Revision 1.243 by jsr166, Thu Apr 5 03:36:54 2018 UTC

# Line 66 | Line 66 | import java.util.Arrays;
66   import java.util.Collection;
67   import java.util.Collections;
68   import java.util.Date;
69 + import java.util.Deque;
70   import java.util.Enumeration;
71 + import java.util.HashSet;
72   import java.util.Iterator;
73   import java.util.List;
74   import java.util.NoSuchElementException;
75   import java.util.PropertyPermission;
76 + import java.util.Set;
77   import java.util.concurrent.BlockingQueue;
78   import java.util.concurrent.Callable;
79   import java.util.concurrent.CountDownLatch;
80   import java.util.concurrent.CyclicBarrier;
81   import java.util.concurrent.ExecutionException;
82 + import java.util.concurrent.Executor;
83   import java.util.concurrent.Executors;
84   import java.util.concurrent.ExecutorService;
85   import java.util.concurrent.ForkJoinPool;
86   import java.util.concurrent.Future;
87 + import java.util.concurrent.FutureTask;
88   import java.util.concurrent.RecursiveAction;
89   import java.util.concurrent.RecursiveTask;
90 + import java.util.concurrent.RejectedExecutionException;
91   import java.util.concurrent.RejectedExecutionHandler;
92   import java.util.concurrent.Semaphore;
93 + import java.util.concurrent.ScheduledExecutorService;
94 + import java.util.concurrent.ScheduledFuture;
95   import java.util.concurrent.SynchronousQueue;
96   import java.util.concurrent.ThreadFactory;
97   import java.util.concurrent.ThreadLocalRandom;
# Line 94 | Line 102 | import java.util.concurrent.atomic.Atomi
102   import java.util.concurrent.atomic.AtomicReference;
103   import java.util.regex.Pattern;
104  
97 import junit.framework.AssertionFailedError;
105   import junit.framework.Test;
106   import junit.framework.TestCase;
107   import junit.framework.TestResult;
# Line 414 | Line 421 | public class JSR166TestCase extends Test
421          for (String testClassName : testClassNames) {
422              try {
423                  Class<?> testClass = Class.forName(testClassName);
424 <                Method m = testClass.getDeclaredMethod("suite",
418 <                                                       new Class<?>[0]);
424 >                Method m = testClass.getDeclaredMethod("suite");
425                  suite.addTest(newTestSuite((Test)m.invoke(null)));
426 <            } catch (Exception e) {
427 <                throw new Error("Missing test class", e);
426 >            } catch (ReflectiveOperationException e) {
427 >                throw new AssertionError("Missing test class", e);
428              }
429          }
430      }
# Line 440 | Line 446 | public class JSR166TestCase extends Test
446          }
447      }
448  
449 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
450 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
451 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
452 <    public static boolean atLeastJava9() {
453 <        return JAVA_CLASS_VERSION >= 53.0
448 <            // As of 2015-09, java9 still uses 52.0 class file version
449 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
450 <    }
451 <    public static boolean atLeastJava10() {
452 <        return JAVA_CLASS_VERSION >= 54.0
453 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
454 <    }
449 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
450 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
451 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
452 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
453 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
454  
455      /**
456       * Collects all JSR166 unit tests as one suite.
# Line 539 | Line 538 | public class JSR166TestCase extends Test
538                  "DoubleAdderTest",
539                  "ForkJoinPool8Test",
540                  "ForkJoinTask8Test",
541 +                "HashMapTest",
542                  "LinkedBlockingDeque8Test",
543                  "LinkedBlockingQueue8Test",
544                  "LongAccumulatorTest",
# Line 601 | Line 601 | public class JSR166TestCase extends Test
601              for (String methodName : testMethodNames(testClass))
602                  suite.addTest((Test) c.newInstance(data, methodName));
603              return suite;
604 <        } catch (Exception e) {
605 <            throw new Error(e);
604 >        } catch (ReflectiveOperationException e) {
605 >            throw new AssertionError(e);
606          }
607      }
608  
# Line 618 | Line 618 | public class JSR166TestCase extends Test
618          if (atLeastJava8()) {
619              String name = testClass.getName();
620              String name8 = name.replaceAll("Test$", "8Test");
621 <            if (name.equals(name8)) throw new Error(name);
621 >            if (name.equals(name8)) throw new AssertionError(name);
622              try {
623                  return (Test)
624                      Class.forName(name8)
625 <                    .getMethod("testSuite", new Class[] { dataClass })
625 >                    .getMethod("testSuite", dataClass)
626                      .invoke(null, data);
627 <            } catch (Exception e) {
628 <                throw new Error(e);
627 >            } catch (ReflectiveOperationException e) {
628 >                throw new AssertionError(e);
629              }
630          } else {
631              return new TestSuite();
# Line 734 | Line 734 | public class JSR166TestCase extends Test
734          String msg = toString() + ": " + String.format(format, args);
735          System.err.println(msg);
736          dumpTestThreads();
737 <        throw new AssertionFailedError(msg);
737 >        throw new AssertionError(msg);
738      }
739  
740      /**
# Line 755 | Line 755 | public class JSR166TestCase extends Test
755                  throw (RuntimeException) t;
756              else if (t instanceof Exception)
757                  throw (Exception) t;
758 <            else {
759 <                AssertionFailedError afe =
760 <                    new AssertionFailedError(t.toString());
761 <                afe.initCause(t);
762 <                throw afe;
763 <            }
758 >            else
759 >                throw new AssertionError(t.toString(), t);
760          }
761  
762          if (Thread.interrupted())
# Line 794 | Line 790 | public class JSR166TestCase extends Test
790  
791      /**
792       * Just like fail(reason), but additionally recording (using
793 <     * threadRecordFailure) any AssertionFailedError thrown, so that
794 <     * the current testcase will fail.
793 >     * threadRecordFailure) any AssertionError thrown, so that the
794 >     * current testcase will fail.
795       */
796      public void threadFail(String reason) {
797          try {
798              fail(reason);
799 <        } catch (AssertionFailedError t) {
800 <            threadRecordFailure(t);
801 <            throw t;
799 >        } catch (AssertionError fail) {
800 >            threadRecordFailure(fail);
801 >            throw fail;
802          }
803      }
804  
805      /**
806       * Just like assertTrue(b), but additionally recording (using
807 <     * threadRecordFailure) any AssertionFailedError thrown, so that
808 <     * the current testcase will fail.
807 >     * threadRecordFailure) any AssertionError thrown, so that the
808 >     * current testcase will fail.
809       */
810      public void threadAssertTrue(boolean b) {
811          try {
812              assertTrue(b);
813 <        } catch (AssertionFailedError t) {
814 <            threadRecordFailure(t);
815 <            throw t;
813 >        } catch (AssertionError fail) {
814 >            threadRecordFailure(fail);
815 >            throw fail;
816          }
817      }
818  
819      /**
820       * Just like assertFalse(b), but additionally recording (using
821 <     * threadRecordFailure) any AssertionFailedError thrown, so that
822 <     * the current testcase will fail.
821 >     * threadRecordFailure) any AssertionError thrown, so that the
822 >     * current testcase will fail.
823       */
824      public void threadAssertFalse(boolean b) {
825          try {
826              assertFalse(b);
827 <        } catch (AssertionFailedError t) {
828 <            threadRecordFailure(t);
829 <            throw t;
827 >        } catch (AssertionError fail) {
828 >            threadRecordFailure(fail);
829 >            throw fail;
830          }
831      }
832  
833      /**
834       * Just like assertNull(x), but additionally recording (using
835 <     * threadRecordFailure) any AssertionFailedError thrown, so that
836 <     * the current testcase will fail.
835 >     * threadRecordFailure) any AssertionError thrown, so that the
836 >     * current testcase will fail.
837       */
838      public void threadAssertNull(Object x) {
839          try {
840              assertNull(x);
841 <        } catch (AssertionFailedError t) {
842 <            threadRecordFailure(t);
843 <            throw t;
841 >        } catch (AssertionError fail) {
842 >            threadRecordFailure(fail);
843 >            throw fail;
844          }
845      }
846  
847      /**
848       * Just like assertEquals(x, y), but additionally recording (using
849 <     * threadRecordFailure) any AssertionFailedError thrown, so that
850 <     * the current testcase will fail.
849 >     * threadRecordFailure) any AssertionError thrown, so that the
850 >     * current testcase will fail.
851       */
852      public void threadAssertEquals(long x, long y) {
853          try {
854              assertEquals(x, y);
855 <        } catch (AssertionFailedError t) {
856 <            threadRecordFailure(t);
857 <            throw t;
855 >        } catch (AssertionError fail) {
856 >            threadRecordFailure(fail);
857 >            throw fail;
858          }
859      }
860  
861      /**
862       * Just like assertEquals(x, y), but additionally recording (using
863 <     * threadRecordFailure) any AssertionFailedError thrown, so that
864 <     * the current testcase will fail.
863 >     * threadRecordFailure) any AssertionError thrown, so that the
864 >     * current testcase will fail.
865       */
866      public void threadAssertEquals(Object x, Object y) {
867          try {
868              assertEquals(x, y);
869 <        } catch (AssertionFailedError fail) {
869 >        } catch (AssertionError fail) {
870              threadRecordFailure(fail);
871              throw fail;
872          } catch (Throwable fail) {
# Line 880 | Line 876 | public class JSR166TestCase extends Test
876  
877      /**
878       * Just like assertSame(x, y), but additionally recording (using
879 <     * threadRecordFailure) any AssertionFailedError thrown, so that
880 <     * the current testcase will fail.
879 >     * threadRecordFailure) any AssertionError thrown, so that the
880 >     * current testcase will fail.
881       */
882      public void threadAssertSame(Object x, Object y) {
883          try {
884              assertSame(x, y);
885 <        } catch (AssertionFailedError fail) {
885 >        } catch (AssertionError fail) {
886              threadRecordFailure(fail);
887              throw fail;
888          }
# Line 908 | Line 904 | public class JSR166TestCase extends Test
904  
905      /**
906       * Records the given exception using {@link #threadRecordFailure},
907 <     * then rethrows the exception, wrapping it in an
908 <     * AssertionFailedError if necessary.
907 >     * then rethrows the exception, wrapping it in an AssertionError
908 >     * if necessary.
909       */
910      public void threadUnexpectedException(Throwable t) {
911          threadRecordFailure(t);
# Line 918 | Line 914 | public class JSR166TestCase extends Test
914              throw (RuntimeException) t;
915          else if (t instanceof Error)
916              throw (Error) t;
917 <        else {
918 <            AssertionFailedError afe =
923 <                new AssertionFailedError("unexpected exception: " + t);
924 <            afe.initCause(t);
925 <            throw afe;
926 <        }
917 >        else
918 >            throw new AssertionError("unexpected exception: " + t, t);
919      }
920  
921      /**
# Line 1099 | Line 1091 | public class JSR166TestCase extends Test
1091          for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1092              try { delay(1); }
1093              catch (InterruptedException fail) {
1094 <                fail("Unexpected InterruptedException");
1094 >                throw new AssertionError("Unexpected InterruptedException", fail);
1095              }
1096              Thread.State s = thread.getState();
1097              if (s == expected)
# Line 1111 | Line 1103 | public class JSR166TestCase extends Test
1103      }
1104  
1105      /**
1114     * Checks that thread does not terminate within the default
1115     * millisecond delay of {@code timeoutMillis()}.
1116     * TODO: REMOVEME
1117     */
1118    void assertThreadStaysAlive(Thread thread) {
1119        assertThreadStaysAlive(thread, timeoutMillis());
1120    }
1121
1122    /**
1123     * Checks that thread does not terminate within the given millisecond delay.
1124     * TODO: REMOVEME
1125     */
1126    void assertThreadStaysAlive(Thread thread, long millis) {
1127        try {
1128            // No need to optimize the failing case via Thread.join.
1129            delay(millis);
1130            assertTrue(thread.isAlive());
1131        } catch (InterruptedException fail) {
1132            threadFail("Unexpected InterruptedException");
1133        }
1134    }
1135
1136    /**
1137     * Checks that the threads do not terminate within the default
1138     * millisecond delay of {@code timeoutMillis()}.
1139     * TODO: REMOVEME
1140     */
1141    void assertThreadsStayAlive(Thread... threads) {
1142        assertThreadsStayAlive(timeoutMillis(), threads);
1143    }
1144
1145    /**
1146     * Checks that the threads do not terminate within the given millisecond delay.
1147     * TODO: REMOVEME
1148     */
1149    void assertThreadsStayAlive(long millis, Thread... threads) {
1150        try {
1151            // No need to optimize the failing case via Thread.join.
1152            delay(millis);
1153            for (Thread thread : threads)
1154                assertTrue(thread.isAlive());
1155        } catch (InterruptedException fail) {
1156            threadFail("Unexpected InterruptedException");
1157        }
1158    }
1159
1160    /**
1106       * Checks that future.get times out, with the default timeout of
1107       * {@code timeoutMillis()}.
1108       */
# Line 1332 | Line 1277 | public class JSR166TestCase extends Test
1277  
1278      /**
1279       * Sleeps until the given time has elapsed.
1280 <     * Throws AssertionFailedError if interrupted.
1280 >     * Throws AssertionError if interrupted.
1281       */
1282      static void sleep(long millis) {
1283          try {
1284              delay(millis);
1285          } catch (InterruptedException fail) {
1286 <            AssertionFailedError afe =
1342 <                new AssertionFailedError("Unexpected InterruptedException");
1343 <            afe.initCause(fail);
1344 <            throw afe;
1286 >            throw new AssertionError("Unexpected InterruptedException", fail);
1287          }
1288      }
1289  
# Line 1432 | Line 1374 | public class JSR166TestCase extends Test
1374   //             r.run();
1375   //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1376   //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1377 < //             throw new AssertionFailedError("did not return promptly");
1377 > //             throw new AssertionError("did not return promptly");
1378   //     }
1379  
1380   //     void assertTerminatesPromptly(Runnable r) {
# Line 1449 | Line 1391 | public class JSR166TestCase extends Test
1391              assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1392          } catch (Throwable fail) { threadUnexpectedException(fail); }
1393          if (millisElapsedSince(startTime) > timeoutMillis/2)
1394 <            throw new AssertionFailedError("timed get did not return promptly");
1394 >            throw new AssertionError("timed get did not return promptly");
1395      }
1396  
1397      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1507 | Line 1449 | public class JSR166TestCase extends Test
1449          }
1450      }
1451  
1510    public abstract class RunnableShouldThrow implements Runnable {
1511        protected abstract void realRun() throws Throwable;
1512
1513        final Class<?> exceptionClass;
1514
1515        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1516            this.exceptionClass = exceptionClass;
1517        }
1518
1519        public final void run() {
1520            try {
1521                realRun();
1522                threadShouldThrow(exceptionClass.getSimpleName());
1523            } catch (Throwable t) {
1524                if (! exceptionClass.isInstance(t))
1525                    threadUnexpectedException(t);
1526            }
1527        }
1528    }
1529
1452      public abstract class ThreadShouldThrow extends Thread {
1453          protected abstract void realRun() throws Throwable;
1454  
# Line 1691 | Line 1613 | public class JSR166TestCase extends Test
1613   //         long startTime = System.nanoTime();
1614   //         while (!flag.get()) {
1615   //             if (millisElapsedSince(startTime) > timeoutMillis)
1616 < //                 throw new AssertionFailedError("timed out");
1616 > //                 throw new AssertionError("timed out");
1617   //             Thread.yield();
1618   //         }
1619   //     }
# Line 1778 | Line 1700 | public class JSR166TestCase extends Test
1700  
1701      /**
1702       * A CyclicBarrier that uses timed await and fails with
1703 <     * AssertionFailedErrors instead of throwing checked exceptions.
1703 >     * AssertionErrors instead of throwing checked exceptions.
1704       */
1705      public static class CheckedBarrier extends CyclicBarrier {
1706          public CheckedBarrier(int parties) { super(parties); }
# Line 1787 | Line 1709 | public class JSR166TestCase extends Test
1709              try {
1710                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1711              } catch (TimeoutException timedOut) {
1712 <                throw new AssertionFailedError("timed out");
1712 >                throw new AssertionError("timed out");
1713              } catch (Exception fail) {
1714 <                AssertionFailedError afe =
1793 <                    new AssertionFailedError("Unexpected exception: " + fail);
1794 <                afe.initCause(fail);
1795 <                throw afe;
1714 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1715              }
1716          }
1717      }
# Line 1915 | Line 1834 | public class JSR166TestCase extends Test
1834              try { throwingAction.run(); }
1835              catch (Throwable t) {
1836                  threw = true;
1837 <                if (!expectedExceptionClass.isInstance(t)) {
1838 <                    AssertionFailedError afe =
1839 <                        new AssertionFailedError
1840 <                        ("Expected " + expectedExceptionClass.getName() +
1841 <                         ", got " + t.getClass().getName());
1923 <                    afe.initCause(t);
1924 <                    threadUnexpectedException(afe);
1925 <                }
1837 >                if (!expectedExceptionClass.isInstance(t))
1838 >                    throw new AssertionError(
1839 >                            "Expected " + expectedExceptionClass.getName() +
1840 >                            ", got " + t.getClass().getName(),
1841 >                            t);
1842              }
1843              if (!threw)
1844                  shouldThrow(expectedExceptionClass.getName());
# Line 1951 | Line 1867 | public class JSR166TestCase extends Test
1867                                 1000L, MILLISECONDS,
1868                                 new SynchronousQueue<Runnable>());
1869  
1870 +    static <T> void shuffle(T[] array) {
1871 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1872 +    }
1873 +
1874 +    /**
1875 +     * Returns the same String as would be returned by {@link
1876 +     * Object#toString}, whether or not the given object's class
1877 +     * overrides toString().
1878 +     *
1879 +     * @see System#identityHashCode
1880 +     */
1881 +    static String identityString(Object x) {
1882 +        return x.getClass().getName()
1883 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1884 +    }
1885 +
1886 +    // --- Shared assertions for Executor tests ---
1887 +
1888      /**
1889       * Returns maximum number of tasks that can be submitted to given
1890       * pool (with bounded queue) before saturation (when submission
# Line 1961 | Line 1895 | public class JSR166TestCase extends Test
1895          return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1896      }
1897  
1898 <    static <T> void shuffle(T[] array) {
1899 <        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1898 >    @SuppressWarnings("FutureReturnValueIgnored")
1899 >    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1900 >        try {
1901 >            e.execute((Runnable) null);
1902 >            shouldThrow();
1903 >        } catch (NullPointerException success) {}
1904 >
1905 >        if (! (e instanceof ExecutorService)) return;
1906 >        ExecutorService es = (ExecutorService) e;
1907 >        try {
1908 >            es.submit((Runnable) null);
1909 >            shouldThrow();
1910 >        } catch (NullPointerException success) {}
1911 >        try {
1912 >            es.submit((Runnable) null, Boolean.TRUE);
1913 >            shouldThrow();
1914 >        } catch (NullPointerException success) {}
1915 >        try {
1916 >            es.submit((Callable) null);
1917 >            shouldThrow();
1918 >        } catch (NullPointerException success) {}
1919 >
1920 >        if (! (e instanceof ScheduledExecutorService)) return;
1921 >        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1922 >        try {
1923 >            ses.schedule((Runnable) null,
1924 >                         randomTimeout(), randomTimeUnit());
1925 >            shouldThrow();
1926 >        } catch (NullPointerException success) {}
1927 >        try {
1928 >            ses.schedule((Callable) null,
1929 >                         randomTimeout(), randomTimeUnit());
1930 >            shouldThrow();
1931 >        } catch (NullPointerException success) {}
1932 >        try {
1933 >            ses.scheduleAtFixedRate((Runnable) null,
1934 >                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1935 >            shouldThrow();
1936 >        } catch (NullPointerException success) {}
1937 >        try {
1938 >            ses.scheduleWithFixedDelay((Runnable) null,
1939 >                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1940 >            shouldThrow();
1941 >        } catch (NullPointerException success) {}
1942 >    }
1943 >
1944 >    void setRejectedExecutionHandler(
1945 >        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1946 >        p.setRejectedExecutionHandler(handler);
1947 >        assertSame(handler, p.getRejectedExecutionHandler());
1948 >    }
1949 >
1950 >    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1951 >        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1952 >        final long savedTaskCount = p.getTaskCount();
1953 >        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1954 >        final int savedQueueSize = p.getQueue().size();
1955 >        final boolean stock = (p.getClass().getClassLoader() == null);
1956 >
1957 >        Runnable r = () -> {};
1958 >        Callable<Boolean> c = () -> Boolean.TRUE;
1959 >
1960 >        class Recorder implements RejectedExecutionHandler {
1961 >            public volatile Runnable r = null;
1962 >            public volatile ThreadPoolExecutor p = null;
1963 >            public void reset() { r = null; p = null; }
1964 >            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1965 >                assertNull(this.r);
1966 >                assertNull(this.p);
1967 >                this.r = r;
1968 >                this.p = p;
1969 >            }
1970 >        }
1971 >
1972 >        // check custom handler is invoked exactly once per task
1973 >        Recorder recorder = new Recorder();
1974 >        setRejectedExecutionHandler(p, recorder);
1975 >        for (int i = 2; i--> 0; ) {
1976 >            recorder.reset();
1977 >            p.execute(r);
1978 >            if (stock && p.getClass() == ThreadPoolExecutor.class)
1979 >                assertSame(r, recorder.r);
1980 >            assertSame(p, recorder.p);
1981 >
1982 >            recorder.reset();
1983 >            assertFalse(p.submit(r).isDone());
1984 >            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1985 >            assertSame(p, recorder.p);
1986 >
1987 >            recorder.reset();
1988 >            assertFalse(p.submit(r, Boolean.TRUE).isDone());
1989 >            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1990 >            assertSame(p, recorder.p);
1991 >
1992 >            recorder.reset();
1993 >            assertFalse(p.submit(c).isDone());
1994 >            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1995 >            assertSame(p, recorder.p);
1996 >
1997 >            if (p instanceof ScheduledExecutorService) {
1998 >                ScheduledExecutorService s = (ScheduledExecutorService) p;
1999 >                ScheduledFuture<?> future;
2000 >
2001 >                recorder.reset();
2002 >                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2003 >                assertFalse(future.isDone());
2004 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2005 >                assertSame(p, recorder.p);
2006 >
2007 >                recorder.reset();
2008 >                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2009 >                assertFalse(future.isDone());
2010 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2011 >                assertSame(p, recorder.p);
2012 >
2013 >                recorder.reset();
2014 >                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2015 >                assertFalse(future.isDone());
2016 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2017 >                assertSame(p, recorder.p);
2018 >
2019 >                recorder.reset();
2020 >                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2021 >                assertFalse(future.isDone());
2022 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2023 >                assertSame(p, recorder.p);
2024 >            }
2025 >        }
2026 >
2027 >        // Checking our custom handler above should be sufficient, but
2028 >        // we add some integration tests of standard handlers.
2029 >        final AtomicReference<Thread> thread = new AtomicReference<>();
2030 >        final Runnable setThread = () -> thread.set(Thread.currentThread());
2031 >
2032 >        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2033 >        try {
2034 >            p.execute(setThread);
2035 >            shouldThrow();
2036 >        } catch (RejectedExecutionException success) {}
2037 >        assertNull(thread.get());
2038 >
2039 >        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2040 >        p.execute(setThread);
2041 >        assertNull(thread.get());
2042 >
2043 >        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2044 >        p.execute(setThread);
2045 >        if (p.isShutdown())
2046 >            assertNull(thread.get());
2047 >        else
2048 >            assertSame(Thread.currentThread(), thread.get());
2049 >
2050 >        setRejectedExecutionHandler(p, savedHandler);
2051 >
2052 >        // check that pool was not perturbed by handlers
2053 >        assertEquals(savedTaskCount, p.getTaskCount());
2054 >        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2055 >        assertEquals(savedQueueSize, p.getQueue().size());
2056 >    }
2057 >
2058 >    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2059 >        assertEquals(x, y);
2060 >        assertEquals(y, x);
2061 >        assertEquals(x.isEmpty(), y.isEmpty());
2062 >        assertEquals(x.size(), y.size());
2063 >        if (x instanceof List) {
2064 >            assertEquals(x.toString(), y.toString());
2065 >        }
2066 >        if (x instanceof List || x instanceof Set) {
2067 >            assertEquals(x.hashCode(), y.hashCode());
2068 >        }
2069 >        if (x instanceof List || x instanceof Deque) {
2070 >            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2071 >            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2072 >                                     y.toArray(new Object[0])));
2073 >        }
2074 >    }
2075 >
2076 >    /**
2077 >     * A weaker form of assertCollectionsEquals which does not insist
2078 >     * that the two collections satisfy Object#equals(Object), since
2079 >     * they may use identity semantics as Deques do.
2080 >     */
2081 >    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2082 >        if (x instanceof List || x instanceof Set)
2083 >            assertCollectionsEquals(x, y);
2084 >        else {
2085 >            assertEquals(x.isEmpty(), y.isEmpty());
2086 >            assertEquals(x.size(), y.size());
2087 >            assertEquals(new HashSet(x), new HashSet(y));
2088 >            if (x instanceof Deque) {
2089 >                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2090 >                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2091 >                                         y.toArray(new Object[0])));
2092 >            }
2093 >        }
2094      }
2095   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines