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.206 by jsr166, Tue Oct 25 01:32:55 2016 UTC vs.
Revision 1.247 by jsr166, Sun Jul 22 21:37:31 2018 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
# Line 8 | Line 9
9  
10   /*
11   * @test
12 < * @summary JSR-166 tck tests
13 < * @modules java.management
12 > * @summary JSR-166 tck tests, in a number of variations.
13 > *          The first is the conformance testing variant,
14 > *          while others also test implementation details.
15   * @build *
16 < * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
17 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
18 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -Djava.util.secureRandomSeed=true JSR166TestCase
16 > * @modules java.management
17 > * @run junit/othervm/timeout=1000 JSR166TestCase
18 > * @run junit/othervm/timeout=1000
19 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 > *      --add-opens java.base/java.lang=ALL-UNNAMED
21 > *      -Djsr166.testImplementationDetails=true
22 > *      JSR166TestCase
23 > * @run junit/othervm/timeout=1000
24 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 > *      --add-opens java.base/java.lang=ALL-UNNAMED
26 > *      -Djsr166.testImplementationDetails=true
27 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28 > *      JSR166TestCase
29 > * @run junit/othervm/timeout=1000
30 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 > *      --add-opens java.base/java.lang=ALL-UNNAMED
32 > *      -Djsr166.testImplementationDetails=true
33 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
34 > *      -Djava.util.secureRandomSeed=true
35 > *      JSR166TestCase
36 > * @run junit/othervm/timeout=1000/policy=tck.policy
37 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 > *      --add-opens java.base/java.lang=ALL-UNNAMED
39 > *      -Djsr166.testImplementationDetails=true
40 > *      JSR166TestCase
41   */
42  
43   import static java.util.concurrent.TimeUnit.MILLISECONDS;
# Line 30 | Line 54 | import java.lang.management.ThreadMXBean
54   import java.lang.reflect.Constructor;
55   import java.lang.reflect.Method;
56   import java.lang.reflect.Modifier;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 41 | Line 63 | import java.security.ProtectionDomain;
63   import java.security.SecurityPermission;
64   import java.util.ArrayList;
65   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;
98   import java.util.concurrent.ThreadPoolExecutor;
99 + import java.util.concurrent.TimeUnit;
100   import java.util.concurrent.TimeoutException;
101   import java.util.concurrent.atomic.AtomicBoolean;
102   import java.util.concurrent.atomic.AtomicReference;
71 import java.util.regex.Matcher;
103   import java.util.regex.Pattern;
104  
74 import junit.framework.AssertionFailedError;
105   import junit.framework.Test;
106   import junit.framework.TestCase;
107   import junit.framework.TestResult;
# Line 278 | Line 308 | public class JSR166TestCase extends Test
308  
309   //     public static String cpuModel() {
310   //         try {
311 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
311 > //             java.util.regex.Matcher matcher
312 > //               = Pattern.compile("model name\\s*: (.*)")
313   //                 .matcher(new String(
314 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
314 > //                     java.nio.file.Files.readAllBytes(
315 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
316   //             matcher.find();
317   //             return matcher.group(1);
318   //         } catch (Exception ex) { return null; }
# Line 389 | 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",
393 <                                                       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 415 | 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
454 <            // As of 2015-09, java9 still uses 52.0 class file version
424 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
425 <    }
426 <    public static boolean atLeastJava10() {
427 <        return JAVA_CLASS_VERSION >= 54.0
428 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
429 <    }
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 >    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
455  
456      /**
457       * Collects all JSR166 unit tests as one suite.
# Line 499 | Line 524 | public class JSR166TestCase extends Test
524              TreeMapTest.suite(),
525              TreeSetTest.suite(),
526              TreeSubMapTest.suite(),
527 <            TreeSubSetTest.suite());
527 >            TreeSubSetTest.suite(),
528 >            VectorTest.suite());
529  
530          // Java8+ test classes
531          if (atLeastJava8()) {
# Line 513 | Line 539 | public class JSR166TestCase extends Test
539                  "DoubleAdderTest",
540                  "ForkJoinPool8Test",
541                  "ForkJoinTask8Test",
542 +                "HashMapTest",
543 +                "LinkedBlockingDeque8Test",
544 +                "LinkedBlockingQueue8Test",
545                  "LongAccumulatorTest",
546                  "LongAdderTest",
547                  "SplittableRandomTest",
# Line 535 | Line 564 | public class JSR166TestCase extends Test
564                  "AtomicReference9Test",
565                  "AtomicReferenceArray9Test",
566                  "ExecutorCompletionService9Test",
567 +                "ForkJoinPool9Test",
568              };
569              addNamedTestClasses(suite, java9TestClassNames);
570          }
# Line 545 | Line 575 | public class JSR166TestCase extends Test
575      /** Returns list of junit-style test method names in given class. */
576      public static ArrayList<String> testMethodNames(Class<?> testClass) {
577          Method[] methods = testClass.getDeclaredMethods();
578 <        ArrayList<String> names = new ArrayList<String>(methods.length);
578 >        ArrayList<String> names = new ArrayList<>(methods.length);
579          for (Method method : methods) {
580              if (method.getName().startsWith("test")
581                  && Modifier.isPublic(method.getModifiers())
# Line 572 | Line 602 | public class JSR166TestCase extends Test
602              for (String methodName : testMethodNames(testClass))
603                  suite.addTest((Test) c.newInstance(data, methodName));
604              return suite;
605 <        } catch (Exception e) {
606 <            throw new Error(e);
605 >        } catch (ReflectiveOperationException e) {
606 >            throw new AssertionError(e);
607          }
608      }
609  
# Line 589 | Line 619 | public class JSR166TestCase extends Test
619          if (atLeastJava8()) {
620              String name = testClass.getName();
621              String name8 = name.replaceAll("Test$", "8Test");
622 <            if (name.equals(name8)) throw new Error(name);
622 >            if (name.equals(name8)) throw new AssertionError(name);
623              try {
624                  return (Test)
625                      Class.forName(name8)
626 <                    .getMethod("testSuite", new Class[] { dataClass })
626 >                    .getMethod("testSuite", dataClass)
627                      .invoke(null, data);
628 <            } catch (Exception e) {
629 <                throw new Error(e);
628 >            } catch (ReflectiveOperationException e) {
629 >                throw new AssertionError(e);
630              }
631          } else {
632              return new TestSuite();
# Line 610 | Line 640 | public class JSR166TestCase extends Test
640      public static long MEDIUM_DELAY_MS;
641      public static long LONG_DELAY_MS;
642  
643 +    private static final long RANDOM_TIMEOUT;
644 +    private static final long RANDOM_EXPIRED_TIMEOUT;
645 +    private static final TimeUnit RANDOM_TIMEUNIT;
646 +    static {
647 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
648 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
649 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
650 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
651 +        TimeUnit[] timeUnits = TimeUnit.values();
652 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
653 +    }
654 +
655 +    /**
656 +     * Returns a timeout for use when any value at all will do.
657 +     */
658 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
659 +
660 +    /**
661 +     * Returns a timeout that means "no waiting", i.e. not positive.
662 +     */
663 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
664 +
665 +    /**
666 +     * Returns a random non-null TimeUnit.
667 +     */
668 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
669 +
670      /**
671       * Returns the shortest timed delay. This can be scaled up for
672       * slow machines using the jsr166.delay.factor system property,
# Line 630 | Line 687 | public class JSR166TestCase extends Test
687          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
688      }
689  
690 +    private static final long TIMEOUT_DELAY_MS
691 +        = (long) (12.0 * Math.cbrt(delayFactor));
692 +
693      /**
694 <     * Returns a timeout in milliseconds to be used in tests that
695 <     * verify that operations block or time out.
694 >     * Returns a timeout in milliseconds to be used in tests that verify
695 >     * that operations block or time out.  We want this to be longer
696 >     * than the OS scheduling quantum, but not too long, so don't scale
697 >     * linearly with delayFactor; we use "crazy" cube root instead.
698       */
699 <    long timeoutMillis() {
700 <        return SHORT_DELAY_MS / 4;
699 >    static long timeoutMillis() {
700 >        return TIMEOUT_DELAY_MS;
701      }
702  
703      /**
# Line 651 | Line 713 | public class JSR166TestCase extends Test
713       * The first exception encountered if any threadAssertXXX method fails.
714       */
715      private final AtomicReference<Throwable> threadFailure
716 <        = new AtomicReference<Throwable>(null);
716 >        = new AtomicReference<>(null);
717  
718      /**
719       * Records an exception so that it can be rethrown later in the test
# Line 673 | Line 735 | public class JSR166TestCase extends Test
735          String msg = toString() + ": " + String.format(format, args);
736          System.err.println(msg);
737          dumpTestThreads();
738 <        throw new AssertionFailedError(msg);
738 >        throw new AssertionError(msg);
739      }
740  
741      /**
# Line 694 | Line 756 | public class JSR166TestCase extends Test
756                  throw (RuntimeException) t;
757              else if (t instanceof Exception)
758                  throw (Exception) t;
759 <            else {
760 <                AssertionFailedError afe =
699 <                    new AssertionFailedError(t.toString());
700 <                afe.initCause(t);
701 <                throw afe;
702 <            }
759 >            else
760 >                throw new AssertionError(t.toString(), t);
761          }
762  
763          if (Thread.interrupted())
# Line 733 | Line 791 | public class JSR166TestCase extends Test
791  
792      /**
793       * Just like fail(reason), but additionally recording (using
794 <     * threadRecordFailure) any AssertionFailedError thrown, so that
795 <     * the current testcase will fail.
794 >     * threadRecordFailure) any AssertionError thrown, so that the
795 >     * current testcase will fail.
796       */
797      public void threadFail(String reason) {
798          try {
799              fail(reason);
800 <        } catch (AssertionFailedError t) {
801 <            threadRecordFailure(t);
802 <            throw t;
800 >        } catch (AssertionError fail) {
801 >            threadRecordFailure(fail);
802 >            throw fail;
803          }
804      }
805  
806      /**
807       * Just like assertTrue(b), but additionally recording (using
808 <     * threadRecordFailure) any AssertionFailedError thrown, so that
809 <     * the current testcase will fail.
808 >     * threadRecordFailure) any AssertionError thrown, so that the
809 >     * current testcase will fail.
810       */
811      public void threadAssertTrue(boolean b) {
812          try {
813              assertTrue(b);
814 <        } catch (AssertionFailedError t) {
815 <            threadRecordFailure(t);
816 <            throw t;
814 >        } catch (AssertionError fail) {
815 >            threadRecordFailure(fail);
816 >            throw fail;
817          }
818      }
819  
820      /**
821       * Just like assertFalse(b), but additionally recording (using
822 <     * threadRecordFailure) any AssertionFailedError thrown, so that
823 <     * the current testcase will fail.
822 >     * threadRecordFailure) any AssertionError thrown, so that the
823 >     * current testcase will fail.
824       */
825      public void threadAssertFalse(boolean b) {
826          try {
827              assertFalse(b);
828 <        } catch (AssertionFailedError t) {
829 <            threadRecordFailure(t);
830 <            throw t;
828 >        } catch (AssertionError fail) {
829 >            threadRecordFailure(fail);
830 >            throw fail;
831          }
832      }
833  
834      /**
835       * Just like assertNull(x), but additionally recording (using
836 <     * threadRecordFailure) any AssertionFailedError thrown, so that
837 <     * the current testcase will fail.
836 >     * threadRecordFailure) any AssertionError thrown, so that the
837 >     * current testcase will fail.
838       */
839      public void threadAssertNull(Object x) {
840          try {
841              assertNull(x);
842 <        } catch (AssertionFailedError t) {
843 <            threadRecordFailure(t);
844 <            throw t;
842 >        } catch (AssertionError fail) {
843 >            threadRecordFailure(fail);
844 >            throw fail;
845          }
846      }
847  
848      /**
849       * Just like assertEquals(x, y), but additionally recording (using
850 <     * threadRecordFailure) any AssertionFailedError thrown, so that
851 <     * the current testcase will fail.
850 >     * threadRecordFailure) any AssertionError thrown, so that the
851 >     * current testcase will fail.
852       */
853      public void threadAssertEquals(long x, long y) {
854          try {
855              assertEquals(x, y);
856 <        } catch (AssertionFailedError t) {
857 <            threadRecordFailure(t);
858 <            throw t;
856 >        } catch (AssertionError fail) {
857 >            threadRecordFailure(fail);
858 >            throw fail;
859          }
860      }
861  
862      /**
863       * Just like assertEquals(x, y), but additionally recording (using
864 <     * threadRecordFailure) any AssertionFailedError thrown, so that
865 <     * the current testcase will fail.
864 >     * threadRecordFailure) any AssertionError thrown, so that the
865 >     * current testcase will fail.
866       */
867      public void threadAssertEquals(Object x, Object y) {
868          try {
869              assertEquals(x, y);
870 <        } catch (AssertionFailedError fail) {
870 >        } catch (AssertionError fail) {
871              threadRecordFailure(fail);
872              throw fail;
873          } catch (Throwable fail) {
# Line 819 | Line 877 | public class JSR166TestCase extends Test
877  
878      /**
879       * Just like assertSame(x, y), but additionally recording (using
880 <     * threadRecordFailure) any AssertionFailedError thrown, so that
881 <     * the current testcase will fail.
880 >     * threadRecordFailure) any AssertionError thrown, so that the
881 >     * current testcase will fail.
882       */
883      public void threadAssertSame(Object x, Object y) {
884          try {
885              assertSame(x, y);
886 <        } catch (AssertionFailedError fail) {
886 >        } catch (AssertionError fail) {
887              threadRecordFailure(fail);
888              throw fail;
889          }
# Line 847 | Line 905 | public class JSR166TestCase extends Test
905  
906      /**
907       * Records the given exception using {@link #threadRecordFailure},
908 <     * then rethrows the exception, wrapping it in an
909 <     * AssertionFailedError if necessary.
908 >     * then rethrows the exception, wrapping it in an AssertionError
909 >     * if necessary.
910       */
911      public void threadUnexpectedException(Throwable t) {
912          threadRecordFailure(t);
# Line 857 | Line 915 | public class JSR166TestCase extends Test
915              throw (RuntimeException) t;
916          else if (t instanceof Error)
917              throw (Error) t;
918 <        else {
919 <            AssertionFailedError afe =
862 <                new AssertionFailedError("unexpected exception: " + t);
863 <            afe.initCause(t);
864 <            throw afe;
865 <        }
918 >        else
919 >            throw new AssertionError("unexpected exception: " + t, t);
920      }
921  
922      /**
# Line 1030 | Line 1084 | public class JSR166TestCase extends Test
1084      }
1085  
1086      /**
1087 <     * Checks that thread does not terminate within the default
1034 <     * millisecond delay of {@code timeoutMillis()}.
1035 <     */
1036 <    void assertThreadStaysAlive(Thread thread) {
1037 <        assertThreadStaysAlive(thread, timeoutMillis());
1038 <    }
1039 <
1040 <    /**
1041 <     * Checks that thread does not terminate within the given millisecond delay.
1042 <     */
1043 <    void assertThreadStaysAlive(Thread thread, long millis) {
1044 <        try {
1045 <            // No need to optimize the failing case via Thread.join.
1046 <            delay(millis);
1047 <            assertTrue(thread.isAlive());
1048 <        } catch (InterruptedException fail) {
1049 <            threadFail("Unexpected InterruptedException");
1050 <        }
1051 <    }
1052 <
1053 <    /**
1054 <     * Checks that the threads do not terminate within the default
1055 <     * millisecond delay of {@code timeoutMillis()}.
1056 <     */
1057 <    void assertThreadsStayAlive(Thread... threads) {
1058 <        assertThreadsStayAlive(timeoutMillis(), threads);
1059 <    }
1060 <
1061 <    /**
1062 <     * Checks that the threads do not terminate within the given millisecond delay.
1087 >     * Checks that thread eventually enters the expected blocked thread state.
1088       */
1089 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1090 <        try {
1091 <            // No need to optimize the failing case via Thread.join.
1092 <            delay(millis);
1093 <            for (Thread thread : threads)
1094 <                assertTrue(thread.isAlive());
1095 <        } catch (InterruptedException fail) {
1096 <            threadFail("Unexpected InterruptedException");
1089 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1090 >        // always sleep at least 1 ms, with high probability avoiding
1091 >        // transitory states
1092 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1093 >            try { delay(1); }
1094 >            catch (InterruptedException fail) {
1095 >                throw new AssertionError("Unexpected InterruptedException", fail);
1096 >            }
1097 >            Thread.State s = thread.getState();
1098 >            if (s == expected)
1099 >                return;
1100 >            else if (s == Thread.State.TERMINATED)
1101 >                fail("Unexpected thread termination");
1102          }
1103 +        fail("timed out waiting for thread to enter thread state " + expected);
1104      }
1105  
1106      /**
# Line 1110 | Line 1141 | public class JSR166TestCase extends Test
1141      }
1142  
1143      /**
1144 +     * The maximum number of consecutive spurious wakeups we should
1145 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1146 +     */
1147 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1148 +
1149 +    /**
1150       * The number of elements to place in collections, arrays, etc.
1151       */
1152      public static final int SIZE = 20;
# Line 1213 | Line 1250 | public class JSR166TestCase extends Test
1250          }
1251          public void refresh() {}
1252          public String toString() {
1253 <            List<Permission> ps = new ArrayList<Permission>();
1253 >            List<Permission> ps = new ArrayList<>();
1254              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1255                  ps.add(e.nextElement());
1256              return "AdjustablePolicy with permissions " + ps;
# Line 1241 | Line 1278 | public class JSR166TestCase extends Test
1278  
1279      /**
1280       * Sleeps until the given time has elapsed.
1281 <     * Throws AssertionFailedError if interrupted.
1281 >     * Throws AssertionError if interrupted.
1282       */
1283      static void sleep(long millis) {
1284          try {
1285              delay(millis);
1286          } catch (InterruptedException fail) {
1287 <            AssertionFailedError afe =
1251 <                new AssertionFailedError("Unexpected InterruptedException");
1252 <            afe.initCause(fail);
1253 <            throw afe;
1287 >            throw new AssertionError("Unexpected InterruptedException", fail);
1288          }
1289      }
1290  
# Line 1272 | Line 1306 | public class JSR166TestCase extends Test
1306                  startTime = System.nanoTime();
1307              else if (millisElapsedSince(startTime) > timeoutMillis) {
1308                  threadAssertTrue(thread.isAlive());
1309 <                return;
1309 >                fail("timed out waiting for thread to enter wait state");
1310 >            }
1311 >            Thread.yield();
1312 >        }
1313 >    }
1314 >
1315 >    /**
1316 >     * Spin-waits up to the specified number of milliseconds for the given
1317 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1318 >     * and additionally satisfy the given condition.
1319 >     */
1320 >    void waitForThreadToEnterWaitState(
1321 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1322 >        long startTime = 0L;
1323 >        for (;;) {
1324 >            Thread.State s = thread.getState();
1325 >            if (s == Thread.State.BLOCKED ||
1326 >                s == Thread.State.WAITING ||
1327 >                s == Thread.State.TIMED_WAITING) {
1328 >                try {
1329 >                    if (waitingForGodot.call())
1330 >                        return;
1331 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1332 >            }
1333 >            else if (s == Thread.State.TERMINATED)
1334 >                fail("Unexpected thread termination");
1335 >            else if (startTime == 0L)
1336 >                startTime = System.nanoTime();
1337 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1338 >                threadAssertTrue(thread.isAlive());
1339 >                fail("timed out waiting for thread to enter wait state");
1340              }
1341              Thread.yield();
1342          }
1343      }
1344  
1345      /**
1346 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1347 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1346 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1347 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1348       */
1349      void waitForThreadToEnterWaitState(Thread thread) {
1350          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1351      }
1352  
1353      /**
1354 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1355 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1356 +     * and additionally satisfy the given condition.
1357 +     */
1358 +    void waitForThreadToEnterWaitState(
1359 +        Thread thread, Callable<Boolean> waitingForGodot) {
1360 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1361 +    }
1362 +
1363 +    /**
1364       * Returns the number of milliseconds since time given by
1365       * startNanoTime, which must have been previously returned from a
1366       * call to {@link System#nanoTime()}.
# Line 1301 | Line 1375 | public class JSR166TestCase extends Test
1375   //             r.run();
1376   //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1377   //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1378 < //             throw new AssertionFailedError("did not return promptly");
1378 > //             throw new AssertionError("did not return promptly");
1379   //     }
1380  
1381   //     void assertTerminatesPromptly(Runnable r) {
# Line 1314 | Line 1388 | public class JSR166TestCase extends Test
1388       */
1389      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1390          long startTime = System.nanoTime();
1391 +        T actual = null;
1392          try {
1393 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1393 >            actual = f.get(timeoutMillis, MILLISECONDS);
1394          } catch (Throwable fail) { threadUnexpectedException(fail); }
1395 +        assertEquals(expectedValue, actual);
1396          if (millisElapsedSince(startTime) > timeoutMillis/2)
1397 <            throw new AssertionFailedError("timed get did not return promptly");
1397 >            throw new AssertionError("timed get did not return promptly");
1398      }
1399  
1400      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1376 | Line 1452 | public class JSR166TestCase extends Test
1452          }
1453      }
1454  
1379    public abstract class RunnableShouldThrow implements Runnable {
1380        protected abstract void realRun() throws Throwable;
1381
1382        final Class<?> exceptionClass;
1383
1384        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1385            this.exceptionClass = exceptionClass;
1386        }
1387
1388        public final void run() {
1389            try {
1390                realRun();
1391                threadShouldThrow(exceptionClass.getSimpleName());
1392            } catch (Throwable t) {
1393                if (! exceptionClass.isInstance(t))
1394                    threadUnexpectedException(t);
1395            }
1396        }
1397    }
1398
1455      public abstract class ThreadShouldThrow extends Thread {
1456          protected abstract void realRun() throws Throwable;
1457  
# Line 1515 | Line 1571 | public class JSR166TestCase extends Test
1571      }
1572  
1573      public void await(CountDownLatch latch, long timeoutMillis) {
1574 +        boolean timedOut = false;
1575          try {
1576 <            if (!latch.await(timeoutMillis, MILLISECONDS))
1520 <                fail("timed out waiting for CountDownLatch for "
1521 <                     + (timeoutMillis/1000) + " sec");
1576 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1577          } catch (Throwable fail) {
1578              threadUnexpectedException(fail);
1579          }
1580 +        if (timedOut)
1581 +            fail("timed out waiting for CountDownLatch for "
1582 +                 + (timeoutMillis/1000) + " sec");
1583      }
1584  
1585      public void await(CountDownLatch latch) {
# Line 1529 | Line 1587 | public class JSR166TestCase extends Test
1587      }
1588  
1589      public void await(Semaphore semaphore) {
1590 +        boolean timedOut = false;
1591 +        try {
1592 +            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1593 +        } catch (Throwable fail) {
1594 +            threadUnexpectedException(fail);
1595 +        }
1596 +        if (timedOut)
1597 +            fail("timed out waiting for Semaphore for "
1598 +                 + (LONG_DELAY_MS/1000) + " sec");
1599 +    }
1600 +
1601 +    public void await(CyclicBarrier barrier) {
1602          try {
1603 <            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1534 <                fail("timed out waiting for Semaphore for "
1535 <                     + (LONG_DELAY_MS/1000) + " sec");
1603 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1604          } catch (Throwable fail) {
1605              threadUnexpectedException(fail);
1606          }
# Line 1552 | Line 1620 | public class JSR166TestCase extends Test
1620   //         long startTime = System.nanoTime();
1621   //         while (!flag.get()) {
1622   //             if (millisElapsedSince(startTime) > timeoutMillis)
1623 < //                 throw new AssertionFailedError("timed out");
1623 > //                 throw new AssertionError("timed out");
1624   //             Thread.yield();
1625   //         }
1626   //     }
# Line 1561 | Line 1629 | public class JSR166TestCase extends Test
1629          public String call() { throw new NullPointerException(); }
1630      }
1631  
1564    public static class CallableOne implements Callable<Integer> {
1565        public Integer call() { return one; }
1566    }
1567
1568    public class ShortRunnable extends CheckedRunnable {
1569        protected void realRun() throws Throwable {
1570            delay(SHORT_DELAY_MS);
1571        }
1572    }
1573
1574    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1575        protected void realRun() throws InterruptedException {
1576            delay(SHORT_DELAY_MS);
1577        }
1578    }
1579
1580    public class SmallRunnable extends CheckedRunnable {
1581        protected void realRun() throws Throwable {
1582            delay(SMALL_DELAY_MS);
1583        }
1584    }
1585
1632      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1633          protected void realRun() {
1634              try {
# Line 1591 | Line 1637 | public class JSR166TestCase extends Test
1637          }
1638      }
1639  
1594    public class SmallCallable extends CheckedCallable {
1595        protected Object realCall() throws InterruptedException {
1596            delay(SMALL_DELAY_MS);
1597            return Boolean.TRUE;
1598        }
1599    }
1600
1601    public class MediumRunnable extends CheckedRunnable {
1602        protected void realRun() throws Throwable {
1603            delay(MEDIUM_DELAY_MS);
1604        }
1605    }
1606
1607    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1608        protected void realRun() throws InterruptedException {
1609            delay(MEDIUM_DELAY_MS);
1610        }
1611    }
1612
1640      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1641          return new CheckedRunnable() {
1642              protected void realRun() {
# Line 1619 | Line 1646 | public class JSR166TestCase extends Test
1646              }};
1647      }
1648  
1622    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1623        protected void realRun() {
1624            try {
1625                delay(MEDIUM_DELAY_MS);
1626            } catch (InterruptedException ok) {}
1627        }
1628    }
1629
1630    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1631        protected void realRun() {
1632            try {
1633                delay(LONG_DELAY_MS);
1634            } catch (InterruptedException ok) {}
1635        }
1636    }
1637
1649      /**
1650       * For use as ThreadFactory in constructors
1651       */
# Line 1648 | Line 1659 | public class JSR166TestCase extends Test
1659          boolean isDone();
1660      }
1661  
1651    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1652        return new TrackedRunnable() {
1653                private volatile boolean done = false;
1654                public boolean isDone() { return done; }
1655                public void run() {
1656                    try {
1657                        delay(timeoutMillis);
1658                        done = true;
1659                    } catch (InterruptedException ok) {}
1660                }
1661            };
1662    }
1663
1664    public static class TrackedShortRunnable implements Runnable {
1665        public volatile boolean done = false;
1666        public void run() {
1667            try {
1668                delay(SHORT_DELAY_MS);
1669                done = true;
1670            } catch (InterruptedException ok) {}
1671        }
1672    }
1673
1674    public static class TrackedSmallRunnable implements Runnable {
1675        public volatile boolean done = false;
1676        public void run() {
1677            try {
1678                delay(SMALL_DELAY_MS);
1679                done = true;
1680            } catch (InterruptedException ok) {}
1681        }
1682    }
1683
1684    public static class TrackedMediumRunnable implements Runnable {
1685        public volatile boolean done = false;
1686        public void run() {
1687            try {
1688                delay(MEDIUM_DELAY_MS);
1689                done = true;
1690            } catch (InterruptedException ok) {}
1691        }
1692    }
1693
1694    public static class TrackedLongRunnable implements Runnable {
1695        public volatile boolean done = false;
1696        public void run() {
1697            try {
1698                delay(LONG_DELAY_MS);
1699                done = true;
1700            } catch (InterruptedException ok) {}
1701        }
1702    }
1703
1662      public static class TrackedNoOpRunnable implements Runnable {
1663          public volatile boolean done = false;
1664          public void run() {
# Line 1708 | Line 1666 | public class JSR166TestCase extends Test
1666          }
1667      }
1668  
1711    public static class TrackedCallable implements Callable {
1712        public volatile boolean done = false;
1713        public Object call() {
1714            try {
1715                delay(SMALL_DELAY_MS);
1716                done = true;
1717            } catch (InterruptedException ok) {}
1718            return Boolean.TRUE;
1719        }
1720    }
1721
1669      /**
1670       * Analog of CheckedRunnable for RecursiveAction
1671       */
# Line 1760 | Line 1707 | public class JSR166TestCase extends Test
1707  
1708      /**
1709       * A CyclicBarrier that uses timed await and fails with
1710 <     * AssertionFailedErrors instead of throwing checked exceptions.
1710 >     * AssertionErrors instead of throwing checked exceptions.
1711       */
1712      public static class CheckedBarrier extends CyclicBarrier {
1713          public CheckedBarrier(int parties) { super(parties); }
# Line 1769 | Line 1716 | public class JSR166TestCase extends Test
1716              try {
1717                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1718              } catch (TimeoutException timedOut) {
1719 <                throw new AssertionFailedError("timed out");
1719 >                throw new AssertionError("timed out");
1720              } catch (Exception fail) {
1721 <                AssertionFailedError afe =
1775 <                    new AssertionFailedError("Unexpected exception: " + fail);
1776 <                afe.initCause(fail);
1777 <                throw afe;
1721 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1722              }
1723          }
1724      }
# Line 1785 | Line 1729 | public class JSR166TestCase extends Test
1729              assertEquals(0, q.size());
1730              assertNull(q.peek());
1731              assertNull(q.poll());
1732 <            assertNull(q.poll(0, MILLISECONDS));
1732 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1733              assertEquals(q.toString(), "[]");
1734              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1735              assertFalse(q.iterator().hasNext());
# Line 1826 | Line 1770 | public class JSR166TestCase extends Test
1770          }
1771      }
1772  
1773 +    void assertImmutable(final Object o) {
1774 +        if (o instanceof Collection) {
1775 +            assertThrows(
1776 +                UnsupportedOperationException.class,
1777 +                new Runnable() { public void run() {
1778 +                        ((Collection) o).add(null);}});
1779 +        }
1780 +    }
1781 +
1782      @SuppressWarnings("unchecked")
1783      <T> T serialClone(T o) {
1784 +        T clone = null;
1785          try {
1786              ObjectInputStream ois = new ObjectInputStream
1787                  (new ByteArrayInputStream(serialBytes(o)));
1788 <            T clone = (T) ois.readObject();
1835 <            assertSame(o.getClass(), clone.getClass());
1836 <            return clone;
1788 >            clone = (T) ois.readObject();
1789          } catch (Throwable fail) {
1790              threadUnexpectedException(fail);
1791 +        }
1792 +        if (o == clone) assertImmutable(o);
1793 +        else assertSame(o.getClass(), clone.getClass());
1794 +        return clone;
1795 +    }
1796 +
1797 +    /**
1798 +     * A version of serialClone that leaves error handling (for
1799 +     * e.g. NotSerializableException) up to the caller.
1800 +     */
1801 +    @SuppressWarnings("unchecked")
1802 +    <T> T serialClonePossiblyFailing(T o)
1803 +        throws ReflectiveOperationException, java.io.IOException {
1804 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1805 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1806 +        oos.writeObject(o);
1807 +        oos.flush();
1808 +        oos.close();
1809 +        ObjectInputStream ois = new ObjectInputStream
1810 +            (new ByteArrayInputStream(bos.toByteArray()));
1811 +        T clone = (T) ois.readObject();
1812 +        if (o == clone) assertImmutable(o);
1813 +        else assertSame(o.getClass(), clone.getClass());
1814 +        return clone;
1815 +    }
1816 +
1817 +    /**
1818 +     * If o implements Cloneable and has a public clone method,
1819 +     * returns a clone of o, else null.
1820 +     */
1821 +    @SuppressWarnings("unchecked")
1822 +    <T> T cloneableClone(T o) {
1823 +        if (!(o instanceof Cloneable)) return null;
1824 +        final T clone;
1825 +        try {
1826 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1827 +        } catch (NoSuchMethodException ok) {
1828              return null;
1829 +        } catch (ReflectiveOperationException unexpected) {
1830 +            throw new Error(unexpected);
1831          }
1832 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1833 +        assertSame(o.getClass(), clone.getClass());
1834 +        return clone;
1835      }
1836  
1837      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
# Line 1847 | Line 1841 | public class JSR166TestCase extends Test
1841              try { throwingAction.run(); }
1842              catch (Throwable t) {
1843                  threw = true;
1844 <                if (!expectedExceptionClass.isInstance(t)) {
1845 <                    AssertionFailedError afe =
1846 <                        new AssertionFailedError
1847 <                        ("Expected " + expectedExceptionClass.getName() +
1848 <                         ", got " + t.getClass().getName());
1855 <                    afe.initCause(t);
1856 <                    threadUnexpectedException(afe);
1857 <                }
1844 >                if (!expectedExceptionClass.isInstance(t))
1845 >                    throw new AssertionError(
1846 >                            "Expected " + expectedExceptionClass.getName() +
1847 >                            ", got " + t.getClass().getName(),
1848 >                            t);
1849              }
1850              if (!threw)
1851                  shouldThrow(expectedExceptionClass.getName());
# Line 1886 | Line 1877 | public class JSR166TestCase extends Test
1877      static <T> void shuffle(T[] array) {
1878          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1879      }
1880 +
1881 +    /**
1882 +     * Returns the same String as would be returned by {@link
1883 +     * Object#toString}, whether or not the given object's class
1884 +     * overrides toString().
1885 +     *
1886 +     * @see System#identityHashCode
1887 +     */
1888 +    static String identityString(Object x) {
1889 +        return x.getClass().getName()
1890 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1891 +    }
1892 +
1893 +    // --- Shared assertions for Executor tests ---
1894 +
1895 +    /**
1896 +     * Returns maximum number of tasks that can be submitted to given
1897 +     * pool (with bounded queue) before saturation (when submission
1898 +     * throws RejectedExecutionException).
1899 +     */
1900 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1901 +        BlockingQueue<Runnable> q = pool.getQueue();
1902 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1903 +    }
1904 +
1905 +    @SuppressWarnings("FutureReturnValueIgnored")
1906 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1907 +        try {
1908 +            e.execute((Runnable) null);
1909 +            shouldThrow();
1910 +        } catch (NullPointerException success) {}
1911 +
1912 +        if (! (e instanceof ExecutorService)) return;
1913 +        ExecutorService es = (ExecutorService) e;
1914 +        try {
1915 +            es.submit((Runnable) null);
1916 +            shouldThrow();
1917 +        } catch (NullPointerException success) {}
1918 +        try {
1919 +            es.submit((Runnable) null, Boolean.TRUE);
1920 +            shouldThrow();
1921 +        } catch (NullPointerException success) {}
1922 +        try {
1923 +            es.submit((Callable) null);
1924 +            shouldThrow();
1925 +        } catch (NullPointerException success) {}
1926 +
1927 +        if (! (e instanceof ScheduledExecutorService)) return;
1928 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1929 +        try {
1930 +            ses.schedule((Runnable) null,
1931 +                         randomTimeout(), randomTimeUnit());
1932 +            shouldThrow();
1933 +        } catch (NullPointerException success) {}
1934 +        try {
1935 +            ses.schedule((Callable) null,
1936 +                         randomTimeout(), randomTimeUnit());
1937 +            shouldThrow();
1938 +        } catch (NullPointerException success) {}
1939 +        try {
1940 +            ses.scheduleAtFixedRate((Runnable) null,
1941 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1942 +            shouldThrow();
1943 +        } catch (NullPointerException success) {}
1944 +        try {
1945 +            ses.scheduleWithFixedDelay((Runnable) null,
1946 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1947 +            shouldThrow();
1948 +        } catch (NullPointerException success) {}
1949 +    }
1950 +
1951 +    void setRejectedExecutionHandler(
1952 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1953 +        p.setRejectedExecutionHandler(handler);
1954 +        assertSame(handler, p.getRejectedExecutionHandler());
1955 +    }
1956 +
1957 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1958 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1959 +        final long savedTaskCount = p.getTaskCount();
1960 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1961 +        final int savedQueueSize = p.getQueue().size();
1962 +        final boolean stock = (p.getClass().getClassLoader() == null);
1963 +
1964 +        Runnable r = () -> {};
1965 +        Callable<Boolean> c = () -> Boolean.TRUE;
1966 +
1967 +        class Recorder implements RejectedExecutionHandler {
1968 +            public volatile Runnable r = null;
1969 +            public volatile ThreadPoolExecutor p = null;
1970 +            public void reset() { r = null; p = null; }
1971 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1972 +                assertNull(this.r);
1973 +                assertNull(this.p);
1974 +                this.r = r;
1975 +                this.p = p;
1976 +            }
1977 +        }
1978 +
1979 +        // check custom handler is invoked exactly once per task
1980 +        Recorder recorder = new Recorder();
1981 +        setRejectedExecutionHandler(p, recorder);
1982 +        for (int i = 2; i--> 0; ) {
1983 +            recorder.reset();
1984 +            p.execute(r);
1985 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
1986 +                assertSame(r, recorder.r);
1987 +            assertSame(p, recorder.p);
1988 +
1989 +            recorder.reset();
1990 +            assertFalse(p.submit(r).isDone());
1991 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1992 +            assertSame(p, recorder.p);
1993 +
1994 +            recorder.reset();
1995 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
1996 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1997 +            assertSame(p, recorder.p);
1998 +
1999 +            recorder.reset();
2000 +            assertFalse(p.submit(c).isDone());
2001 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2002 +            assertSame(p, recorder.p);
2003 +
2004 +            if (p instanceof ScheduledExecutorService) {
2005 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2006 +                ScheduledFuture<?> future;
2007 +
2008 +                recorder.reset();
2009 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2010 +                assertFalse(future.isDone());
2011 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2012 +                assertSame(p, recorder.p);
2013 +
2014 +                recorder.reset();
2015 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2016 +                assertFalse(future.isDone());
2017 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2018 +                assertSame(p, recorder.p);
2019 +
2020 +                recorder.reset();
2021 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2022 +                assertFalse(future.isDone());
2023 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2024 +                assertSame(p, recorder.p);
2025 +
2026 +                recorder.reset();
2027 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2028 +                assertFalse(future.isDone());
2029 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2030 +                assertSame(p, recorder.p);
2031 +            }
2032 +        }
2033 +
2034 +        // Checking our custom handler above should be sufficient, but
2035 +        // we add some integration tests of standard handlers.
2036 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2037 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2038 +
2039 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2040 +        try {
2041 +            p.execute(setThread);
2042 +            shouldThrow();
2043 +        } catch (RejectedExecutionException success) {}
2044 +        assertNull(thread.get());
2045 +
2046 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2047 +        p.execute(setThread);
2048 +        assertNull(thread.get());
2049 +
2050 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2051 +        p.execute(setThread);
2052 +        if (p.isShutdown())
2053 +            assertNull(thread.get());
2054 +        else
2055 +            assertSame(Thread.currentThread(), thread.get());
2056 +
2057 +        setRejectedExecutionHandler(p, savedHandler);
2058 +
2059 +        // check that pool was not perturbed by handlers
2060 +        assertEquals(savedTaskCount, p.getTaskCount());
2061 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2062 +        assertEquals(savedQueueSize, p.getQueue().size());
2063 +    }
2064 +
2065 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2066 +        assertEquals(x, y);
2067 +        assertEquals(y, x);
2068 +        assertEquals(x.isEmpty(), y.isEmpty());
2069 +        assertEquals(x.size(), y.size());
2070 +        if (x instanceof List) {
2071 +            assertEquals(x.toString(), y.toString());
2072 +        }
2073 +        if (x instanceof List || x instanceof Set) {
2074 +            assertEquals(x.hashCode(), y.hashCode());
2075 +        }
2076 +        if (x instanceof List || x instanceof Deque) {
2077 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2078 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2079 +                                     y.toArray(new Object[0])));
2080 +        }
2081 +    }
2082 +
2083 +    /**
2084 +     * A weaker form of assertCollectionsEquals which does not insist
2085 +     * that the two collections satisfy Object#equals(Object), since
2086 +     * they may use identity semantics as Deques do.
2087 +     */
2088 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2089 +        if (x instanceof List || x instanceof Set)
2090 +            assertCollectionsEquals(x, y);
2091 +        else {
2092 +            assertEquals(x.isEmpty(), y.isEmpty());
2093 +            assertEquals(x.size(), y.size());
2094 +            assertEquals(new HashSet(x), new HashSet(y));
2095 +            if (x instanceof Deque) {
2096 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2097 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2098 +                                         y.toArray(new Object[0])));
2099 +            }
2100 +        }
2101 +    }
2102   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines