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.232 by jsr166, Mon May 29 19:15:02 2017 UTC vs.
Revision 1.268 by jsr166, Sun Sep 22 01:59:57 2019 UTC

# Line 49 | Line 49 | import java.io.ByteArrayOutputStream;
49   import java.io.ObjectInputStream;
50   import java.io.ObjectOutputStream;
51   import java.lang.management.ManagementFactory;
52 + import java.lang.management.LockInfo;
53   import java.lang.management.ThreadInfo;
54   import java.lang.management.ThreadMXBean;
55   import java.lang.reflect.Constructor;
# Line 66 | Line 67 | import java.util.Arrays;
67   import java.util.Collection;
68   import java.util.Collections;
69   import java.util.Date;
70 + import java.util.Deque;
71   import java.util.Enumeration;
72 + import java.util.HashSet;
73   import java.util.Iterator;
74   import java.util.List;
75   import java.util.NoSuchElementException;
76   import java.util.PropertyPermission;
77 + import java.util.Set;
78   import java.util.concurrent.BlockingQueue;
79   import java.util.concurrent.Callable;
80   import java.util.concurrent.CountDownLatch;
81   import java.util.concurrent.CyclicBarrier;
82   import java.util.concurrent.ExecutionException;
83 + import java.util.concurrent.Executor;
84   import java.util.concurrent.Executors;
85   import java.util.concurrent.ExecutorService;
86   import java.util.concurrent.ForkJoinPool;
87   import java.util.concurrent.Future;
88 + import java.util.concurrent.FutureTask;
89   import java.util.concurrent.RecursiveAction;
90   import java.util.concurrent.RecursiveTask;
91 + import java.util.concurrent.RejectedExecutionException;
92   import java.util.concurrent.RejectedExecutionHandler;
93   import java.util.concurrent.Semaphore;
94 + import java.util.concurrent.ScheduledExecutorService;
95 + import java.util.concurrent.ScheduledFuture;
96   import java.util.concurrent.SynchronousQueue;
97   import java.util.concurrent.ThreadFactory;
98   import java.util.concurrent.ThreadLocalRandom;
# Line 94 | Line 103 | import java.util.concurrent.atomic.Atomi
103   import java.util.concurrent.atomic.AtomicReference;
104   import java.util.regex.Pattern;
105  
97 import junit.framework.AssertionFailedError;
106   import junit.framework.Test;
107   import junit.framework.TestCase;
108   import junit.framework.TestResult;
# Line 110 | Line 118 | import junit.framework.TestSuite;
118   *
119   * <ol>
120   *
121 < * <li>All assertions in code running in generated threads must use
122 < * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
123 < * #threadAssertEquals}, or {@link #threadAssertNull}, (not
124 < * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
125 < * particularly recommended) for other code to use these forms too.
126 < * Only the most typically used JUnit assertion methods are defined
127 < * this way, but enough to live with.
121 > * <li>All code not running in the main test thread (manually spawned threads
122 > * or the common fork join pool) must be checked for failure (and completion!).
123 > * Mechanisms that can be used to ensure this are:
124 > *   <ol>
125 > *   <li>Signalling via a synchronizer like AtomicInteger or CountDownLatch
126 > *    that the task completed normally, which is checked before returning from
127 > *    the test method in the main thread.
128 > *   <li>Using the forms {@link #threadFail}, {@link #threadAssertTrue},
129 > *    or {@link #threadAssertNull}, (not {@code fail}, {@code assertTrue}, etc.)
130 > *    Only the most typically used JUnit assertion methods are defined
131 > *    this way, but enough to live with.
132 > *   <li>Recording failure explicitly using {@link #threadUnexpectedException}
133 > *    or {@link #threadRecordFailure}.
134 > *   <li>Using a wrapper like CheckedRunnable that uses one the mechanisms above.
135 > *   </ol>
136   *
137   * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
138   * to invoke {@code super.setUp} and {@code super.tearDown} within
# Line 228 | Line 244 | public class JSR166TestCase extends Test
244          }
245      }
246  
247 +    private static final ThreadMXBean THREAD_MXBEAN
248 +        = ManagementFactory.getThreadMXBean();
249 +
250      /**
251       * The scaling factor to apply to standard delays used in tests.
252       * May be initialized from any of:
# Line 269 | Line 288 | public class JSR166TestCase extends Test
288      static volatile TestCase currentTestCase;
289      // static volatile int currentRun = 0;
290      static {
291 <        Runnable checkForWedgedTest = new Runnable() { public void run() {
291 >        Runnable wedgedTestDetector = new Runnable() { public void run() {
292              // Avoid spurious reports with enormous runsPerTest.
293              // A single test case run should never take more than 1 second.
294              // But let's cap it at the high end too ...
295 <            final int timeoutMinutes =
296 <                Math.min(15, Math.max(runsPerTest / 60, 1));
295 >            final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1)
296 >                * Math.max((int) delayFactor, 1);
297 >            final int timeoutMinutes = Math.min(15, timeoutMinutesMin);
298              for (TestCase lastTestCase = currentTestCase;;) {
299                  try { MINUTES.sleep(timeoutMinutes); }
300                  catch (InterruptedException unexpected) { break; }
# Line 294 | Line 314 | public class JSR166TestCase extends Test
314                  }
315                  lastTestCase = currentTestCase;
316              }}};
317 <        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
317 >        Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector");
318          thread.setDaemon(true);
319          thread.start();
320      }
# Line 338 | Line 358 | public class JSR166TestCase extends Test
358              // Never report first run of any test; treat it as a
359              // warmup run, notably to trigger all needed classloading,
360              if (i > 0)
361 <                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
361 >                System.out.printf("%s: %d%n", toString(), elapsedMillis);
362          }
363      }
364  
# Line 414 | Line 434 | public class JSR166TestCase extends Test
434          for (String testClassName : testClassNames) {
435              try {
436                  Class<?> testClass = Class.forName(testClassName);
437 <                Method m = testClass.getDeclaredMethod("suite",
418 <                                                       new Class<?>[0]);
437 >                Method m = testClass.getDeclaredMethod("suite");
438                  suite.addTest(newTestSuite((Test)m.invoke(null)));
439 <            } catch (Exception e) {
440 <                throw new Error("Missing test class", e);
439 >            } catch (ReflectiveOperationException e) {
440 >                throw new AssertionError("Missing test class", e);
441              }
442          }
443      }
# Line 440 | Line 459 | public class JSR166TestCase extends Test
459          }
460      }
461  
462 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
463 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
464 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
465 <    public static boolean atLeastJava9() {
466 <        return JAVA_CLASS_VERSION >= 53.0
467 <            // As of 2015-09, java9 still uses 52.0 class file version
468 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
469 <    }
470 <    public static boolean atLeastJava10() {
471 <        return JAVA_CLASS_VERSION >= 54.0
472 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
473 <    }
462 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
463 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
464 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
465 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
466 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
467 >    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
468 >    public static boolean atLeastJava12() { return JAVA_CLASS_VERSION >= 56.0; }
469 >    public static boolean atLeastJava13() { return JAVA_CLASS_VERSION >= 57.0; }
470 >    public static boolean atLeastJava14() { return JAVA_CLASS_VERSION >= 58.0; }
471 >    public static boolean atLeastJava15() { return JAVA_CLASS_VERSION >= 59.0; }
472 >    public static boolean atLeastJava16() { return JAVA_CLASS_VERSION >= 60.0; }
473 >    public static boolean atLeastJava17() { return JAVA_CLASS_VERSION >= 61.0; }
474  
475      /**
476       * Collects all JSR166 unit tests as one suite.
# Line 503 | Line 522 | public class JSR166TestCase extends Test
522              ExecutorsTest.suite(),
523              ExecutorCompletionServiceTest.suite(),
524              FutureTaskTest.suite(),
525 +            HashtableTest.suite(),
526              LinkedBlockingDequeTest.suite(),
527              LinkedBlockingQueueTest.suite(),
528              LinkedListTest.suite(),
# Line 539 | Line 559 | public class JSR166TestCase extends Test
559                  "DoubleAdderTest",
560                  "ForkJoinPool8Test",
561                  "ForkJoinTask8Test",
562 +                "HashMapTest",
563                  "LinkedBlockingDeque8Test",
564                  "LinkedBlockingQueue8Test",
565 +                "LinkedHashMapTest",
566                  "LongAccumulatorTest",
567                  "LongAdderTest",
568                  "SplittableRandomTest",
# Line 601 | Line 623 | public class JSR166TestCase extends Test
623              for (String methodName : testMethodNames(testClass))
624                  suite.addTest((Test) c.newInstance(data, methodName));
625              return suite;
626 <        } catch (Exception e) {
627 <            throw new Error(e);
626 >        } catch (ReflectiveOperationException e) {
627 >            throw new AssertionError(e);
628          }
629      }
630  
# Line 618 | Line 640 | public class JSR166TestCase extends Test
640          if (atLeastJava8()) {
641              String name = testClass.getName();
642              String name8 = name.replaceAll("Test$", "8Test");
643 <            if (name.equals(name8)) throw new Error(name);
643 >            if (name.equals(name8)) throw new AssertionError(name);
644              try {
645                  return (Test)
646                      Class.forName(name8)
647 <                    .getMethod("testSuite", new Class[] { dataClass })
647 >                    .getMethod("testSuite", dataClass)
648                      .invoke(null, data);
649 <            } catch (Exception e) {
650 <                throw new Error(e);
649 >            } catch (ReflectiveOperationException e) {
650 >                throw new AssertionError(e);
651              }
652          } else {
653              return new TestSuite();
# Line 639 | Line 661 | public class JSR166TestCase extends Test
661      public static long MEDIUM_DELAY_MS;
662      public static long LONG_DELAY_MS;
663  
664 +    /**
665 +     * A delay significantly longer than LONG_DELAY_MS.
666 +     * Use this in a thread that is waited for via awaitTermination(Thread).
667 +     */
668 +    public static long LONGER_DELAY_MS;
669 +
670      private static final long RANDOM_TIMEOUT;
671      private static final long RANDOM_EXPIRED_TIMEOUT;
672      private static final TimeUnit RANDOM_TIMEUNIT;
# Line 667 | Line 695 | public class JSR166TestCase extends Test
695      static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
696  
697      /**
698 +     * Returns a random boolean; a "coin flip".
699 +     */
700 +    static boolean randomBoolean() {
701 +        return ThreadLocalRandom.current().nextBoolean();
702 +    }
703 +
704 +    /**
705 +     * Returns a random element from given choices.
706 +     */
707 +    <T> T chooseRandomly(T... choices) {
708 +        return choices[ThreadLocalRandom.current().nextInt(choices.length)];
709 +    }
710 +
711 +    /**
712       * Returns the shortest timed delay. This can be scaled up for
713       * slow machines using the jsr166.delay.factor system property,
714       * or via jtreg's -timeoutFactor: flag.
# Line 684 | Line 726 | public class JSR166TestCase extends Test
726          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
727          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
728          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
729 +        LONGER_DELAY_MS = 2 * LONG_DELAY_MS;
730      }
731  
732      private static final long TIMEOUT_DELAY_MS
# Line 722 | Line 765 | public class JSR166TestCase extends Test
765       */
766      public void threadRecordFailure(Throwable t) {
767          System.err.println(t);
768 <        dumpTestThreads();
769 <        threadFailure.compareAndSet(null, t);
768 >        if (threadFailure.compareAndSet(null, t))
769 >            dumpTestThreads();
770      }
771  
772      public void setUp() {
# Line 734 | Line 777 | public class JSR166TestCase extends Test
777          String msg = toString() + ": " + String.format(format, args);
778          System.err.println(msg);
779          dumpTestThreads();
780 <        throw new AssertionFailedError(msg);
780 >        throw new AssertionError(msg);
781      }
782  
783      /**
# Line 755 | Line 798 | public class JSR166TestCase extends Test
798                  throw (RuntimeException) t;
799              else if (t instanceof Exception)
800                  throw (Exception) t;
801 <            else {
802 <                AssertionFailedError afe =
760 <                    new AssertionFailedError(t.toString());
761 <                afe.initCause(t);
762 <                throw afe;
763 <            }
801 >            else
802 >                throw new AssertionError(t.toString(), t);
803          }
804  
805          if (Thread.interrupted())
# Line 794 | Line 833 | public class JSR166TestCase extends Test
833  
834      /**
835       * Just like fail(reason), 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 threadFail(String reason) {
840          try {
841              fail(reason);
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 assertTrue(b), 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 threadAssertTrue(boolean b) {
854          try {
855              assertTrue(b);
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 assertFalse(b), 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 threadAssertFalse(boolean b) {
868          try {
869              assertFalse(b);
870 <        } catch (AssertionFailedError t) {
871 <            threadRecordFailure(t);
872 <            throw t;
870 >        } catch (AssertionError fail) {
871 >            threadRecordFailure(fail);
872 >            throw fail;
873          }
874      }
875  
876      /**
877       * Just like assertNull(x), but additionally recording (using
878 <     * threadRecordFailure) any AssertionFailedError thrown, so that
879 <     * the current testcase will fail.
878 >     * threadRecordFailure) any AssertionError thrown, so that the
879 >     * current testcase will fail.
880       */
881      public void threadAssertNull(Object x) {
882          try {
883              assertNull(x);
884 <        } catch (AssertionFailedError t) {
885 <            threadRecordFailure(t);
886 <            throw t;
884 >        } catch (AssertionError fail) {
885 >            threadRecordFailure(fail);
886 >            throw fail;
887          }
888      }
889  
890      /**
891       * Just like assertEquals(x, y), but additionally recording (using
892 <     * threadRecordFailure) any AssertionFailedError thrown, so that
893 <     * the current testcase will fail.
892 >     * threadRecordFailure) any AssertionError thrown, so that the
893 >     * current testcase will fail.
894       */
895      public void threadAssertEquals(long x, long y) {
896          try {
897              assertEquals(x, y);
898 <        } catch (AssertionFailedError t) {
899 <            threadRecordFailure(t);
900 <            throw t;
898 >        } catch (AssertionError fail) {
899 >            threadRecordFailure(fail);
900 >            throw fail;
901          }
902      }
903  
904      /**
905       * Just like assertEquals(x, y), but additionally recording (using
906 <     * threadRecordFailure) any AssertionFailedError thrown, so that
907 <     * the current testcase will fail.
906 >     * threadRecordFailure) any AssertionError thrown, so that the
907 >     * current testcase will fail.
908       */
909      public void threadAssertEquals(Object x, Object y) {
910          try {
911              assertEquals(x, y);
912 <        } catch (AssertionFailedError fail) {
912 >        } catch (AssertionError fail) {
913              threadRecordFailure(fail);
914              throw fail;
915          } catch (Throwable fail) {
# Line 880 | Line 919 | public class JSR166TestCase extends Test
919  
920      /**
921       * Just like assertSame(x, y), but additionally recording (using
922 <     * threadRecordFailure) any AssertionFailedError thrown, so that
923 <     * the current testcase will fail.
922 >     * threadRecordFailure) any AssertionError thrown, so that the
923 >     * current testcase will fail.
924       */
925      public void threadAssertSame(Object x, Object y) {
926          try {
927              assertSame(x, y);
928 <        } catch (AssertionFailedError fail) {
928 >        } catch (AssertionError fail) {
929              threadRecordFailure(fail);
930              throw fail;
931          }
# Line 908 | Line 947 | public class JSR166TestCase extends Test
947  
948      /**
949       * Records the given exception using {@link #threadRecordFailure},
950 <     * then rethrows the exception, wrapping it in an
951 <     * AssertionFailedError if necessary.
950 >     * then rethrows the exception, wrapping it in an AssertionError
951 >     * if necessary.
952       */
953      public void threadUnexpectedException(Throwable t) {
954          threadRecordFailure(t);
# Line 918 | Line 957 | public class JSR166TestCase extends Test
957              throw (RuntimeException) t;
958          else if (t instanceof Error)
959              throw (Error) t;
960 <        else {
961 <            AssertionFailedError afe =
923 <                new AssertionFailedError("unexpected exception: " + t);
924 <            afe.initCause(t);
925 <            throw afe;
926 <        }
960 >        else
961 >            throw new AssertionError("unexpected exception: " + t, t);
962      }
963  
964      /**
# Line 1052 | Line 1087 | public class JSR166TestCase extends Test
1087          }
1088      }
1089  
1090 +    /** Returns true if thread info might be useful in a thread dump. */
1091 +    static boolean threadOfInterest(ThreadInfo info) {
1092 +        final String name = info.getThreadName();
1093 +        String lockName;
1094 +        if (name == null)
1095 +            return true;
1096 +        if (name.equals("Signal Dispatcher")
1097 +            || name.equals("WedgedTestDetector"))
1098 +            return false;
1099 +        if (name.equals("Reference Handler")) {
1100 +            // Reference Handler stacktrace changed in JDK-8156500
1101 +            StackTraceElement[] stackTrace; String methodName;
1102 +            if ((stackTrace = info.getStackTrace()) != null
1103 +                && stackTrace.length > 0
1104 +                && (methodName = stackTrace[0].getMethodName()) != null
1105 +                && methodName.equals("waitForReferencePendingList"))
1106 +                return false;
1107 +            // jdk8 Reference Handler stacktrace
1108 +            if ((lockName = info.getLockName()) != null
1109 +                && lockName.startsWith("java.lang.ref"))
1110 +                return false;
1111 +        }
1112 +        if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
1113 +            && (lockName = info.getLockName()) != null
1114 +            && lockName.startsWith("java.lang.ref"))
1115 +            return false;
1116 +        if (name.startsWith("ForkJoinPool.commonPool-worker")
1117 +            && (lockName = info.getLockName()) != null
1118 +            && lockName.startsWith("java.util.concurrent.ForkJoinPool"))
1119 +            return false;
1120 +        return true;
1121 +    }
1122 +
1123      /**
1124       * A debugging tool to print stack traces of most threads, as jstack does.
1125       * Uninteresting threads are filtered out.
# Line 1066 | Line 1134 | public class JSR166TestCase extends Test
1134              }
1135          }
1136  
1069        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1137          System.err.println("------ stacktrace dump start ------");
1138 <        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1139 <            final String name = info.getThreadName();
1140 <            String lockName;
1074 <            if ("Signal Dispatcher".equals(name))
1075 <                continue;
1076 <            if ("Reference Handler".equals(name)
1077 <                && (lockName = info.getLockName()) != null
1078 <                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1079 <                continue;
1080 <            if ("Finalizer".equals(name)
1081 <                && (lockName = info.getLockName()) != null
1082 <                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1083 <                continue;
1084 <            if ("checkForWedgedTest".equals(name))
1085 <                continue;
1086 <            System.err.print(info);
1087 <        }
1138 >        for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true))
1139 >            if (threadOfInterest(info))
1140 >                System.err.print(info);
1141          System.err.println("------ stacktrace dump end ------");
1142  
1143          if (sm != null) System.setSecurityManager(sm);
# Line 1099 | Line 1152 | public class JSR166TestCase extends Test
1152          for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1153              try { delay(1); }
1154              catch (InterruptedException fail) {
1155 <                fail("Unexpected InterruptedException");
1155 >                throw new AssertionError("Unexpected InterruptedException", fail);
1156              }
1157              Thread.State s = thread.getState();
1158              if (s == expected)
# Line 1111 | Line 1164 | public class JSR166TestCase extends Test
1164      }
1165  
1166      /**
1167 <     * 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
1167 >     * Returns the thread's blocker's class name, if any, else null.
1168       */
1169 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1170 <        try {
1171 <            // No need to optimize the failing case via Thread.join.
1172 <            delay(millis);
1173 <            for (Thread thread : threads)
1174 <                assertTrue(thread.isAlive());
1155 <        } catch (InterruptedException fail) {
1156 <            threadFail("Unexpected InterruptedException");
1157 <        }
1169 >    String blockerClassName(Thread thread) {
1170 >        ThreadInfo threadInfo; LockInfo lockInfo;
1171 >        if ((threadInfo = THREAD_MXBEAN.getThreadInfo(thread.getId(), 0)) != null
1172 >            && (lockInfo = threadInfo.getLockInfo()) != null)
1173 >            return lockInfo.getClassName();
1174 >        return null;
1175      }
1176  
1177      /**
# Line 1332 | Line 1349 | public class JSR166TestCase extends Test
1349  
1350      /**
1351       * Sleeps until the given time has elapsed.
1352 <     * Throws AssertionFailedError if interrupted.
1352 >     * Throws AssertionError if interrupted.
1353       */
1354      static void sleep(long millis) {
1355          try {
1356              delay(millis);
1357          } catch (InterruptedException fail) {
1358 <            AssertionFailedError afe =
1342 <                new AssertionFailedError("Unexpected InterruptedException");
1343 <            afe.initCause(fail);
1344 <            throw afe;
1358 >            throw new AssertionError("Unexpected InterruptedException", fail);
1359          }
1360      }
1361  
1362      /**
1363       * Spin-waits up to the specified number of milliseconds for the given
1364       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1365 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1366       */
1367 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1368 <        long startTime = 0L;
1369 <        for (;;) {
1370 <            Thread.State s = thread.getState();
1371 <            if (s == Thread.State.BLOCKED ||
1372 <                s == Thread.State.WAITING ||
1373 <                s == Thread.State.TIMED_WAITING)
1374 <                return;
1375 <            else if (s == Thread.State.TERMINATED)
1367 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1368 >                                       Callable<Boolean> waitingForGodot) {
1369 >        for (long startTime = 0L;;) {
1370 >            switch (thread.getState()) {
1371 >            default: break;
1372 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1373 >                try {
1374 >                    if (waitingForGodot == null || waitingForGodot.call())
1375 >                        return;
1376 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1377 >                break;
1378 >            case TERMINATED:
1379                  fail("Unexpected thread termination");
1380 <            else if (startTime == 0L)
1380 >            }
1381 >
1382 >            if (startTime == 0L)
1383                  startTime = System.nanoTime();
1384              else if (millisElapsedSince(startTime) > timeoutMillis) {
1385 <                threadAssertTrue(thread.isAlive());
1386 <                fail("timed out waiting for thread to enter wait state");
1385 >                assertTrue(thread.isAlive());
1386 >                if (waitingForGodot == null
1387 >                    || thread.getState() == Thread.State.RUNNABLE)
1388 >                    fail("timed out waiting for thread to enter wait state");
1389 >                else
1390 >                    fail("timed out waiting for condition, thread state="
1391 >                         + thread.getState());
1392              }
1393              Thread.yield();
1394          }
# Line 1371 | Line 1396 | public class JSR166TestCase extends Test
1396  
1397      /**
1398       * Spin-waits up to the specified number of milliseconds for the given
1399 <     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1375 <     * and additionally satisfy the given condition.
1399 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1400       */
1401 <    void waitForThreadToEnterWaitState(
1402 <        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1379 <        long startTime = 0L;
1380 <        for (;;) {
1381 <            Thread.State s = thread.getState();
1382 <            if (s == Thread.State.BLOCKED ||
1383 <                s == Thread.State.WAITING ||
1384 <                s == Thread.State.TIMED_WAITING) {
1385 <                try {
1386 <                    if (waitingForGodot.call())
1387 <                        return;
1388 <                } catch (Throwable fail) { threadUnexpectedException(fail); }
1389 <            }
1390 <            else if (s == Thread.State.TERMINATED)
1391 <                fail("Unexpected thread termination");
1392 <            else if (startTime == 0L)
1393 <                startTime = System.nanoTime();
1394 <            else if (millisElapsedSince(startTime) > timeoutMillis) {
1395 <                threadAssertTrue(thread.isAlive());
1396 <                fail("timed out waiting for thread to enter wait state");
1397 <            }
1398 <            Thread.yield();
1399 <        }
1401 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1402 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1403      }
1404  
1405      /**
# Line 1404 | Line 1407 | public class JSR166TestCase extends Test
1407       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1408       */
1409      void waitForThreadToEnterWaitState(Thread thread) {
1410 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1410 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1411      }
1412  
1413      /**
# Line 1412 | Line 1415 | public class JSR166TestCase extends Test
1415       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1416       * and additionally satisfy the given condition.
1417       */
1418 <    void waitForThreadToEnterWaitState(
1419 <        Thread thread, Callable<Boolean> waitingForGodot) {
1418 >    void waitForThreadToEnterWaitState(Thread thread,
1419 >                                       Callable<Boolean> waitingForGodot) {
1420          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1421      }
1422  
1423      /**
1424 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1425 +     * be interrupted.  Clears the interrupt status before returning.
1426 +     */
1427 +    void awaitInterrupted() {
1428 +        for (long startTime = 0L; !Thread.interrupted(); ) {
1429 +            if (startTime == 0L)
1430 +                startTime = System.nanoTime();
1431 +            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1432 +                fail("timed out waiting for thread interrupt");
1433 +            Thread.yield();
1434 +        }
1435 +    }
1436 +
1437 +    /**
1438       * Returns the number of milliseconds since time given by
1439       * startNanoTime, which must have been previously returned from a
1440       * call to {@link System#nanoTime()}.
# Line 1426 | Line 1443 | public class JSR166TestCase extends Test
1443          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1444      }
1445  
1429 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1430 //         long startTime = System.nanoTime();
1431 //         try {
1432 //             r.run();
1433 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1434 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1435 //             throw new AssertionFailedError("did not return promptly");
1436 //     }
1437
1438 //     void assertTerminatesPromptly(Runnable r) {
1439 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1440 //     }
1441
1446      /**
1447       * Checks that timed f.get() returns the expected value, and does not
1448       * wait for the timeout to elapse before returning.
1449       */
1450      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1451          long startTime = System.nanoTime();
1452 +        T actual = null;
1453          try {
1454 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1454 >            actual = f.get(timeoutMillis, MILLISECONDS);
1455          } catch (Throwable fail) { threadUnexpectedException(fail); }
1456 +        assertEquals(expectedValue, actual);
1457          if (millisElapsedSince(startTime) > timeoutMillis/2)
1458 <            throw new AssertionFailedError("timed get did not return promptly");
1458 >            throw new AssertionError("timed get did not return promptly");
1459      }
1460  
1461      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1467 | Line 1473 | public class JSR166TestCase extends Test
1473      }
1474  
1475      /**
1476 +     * Returns a new started daemon Thread running the given action,
1477 +     * wrapped in a CheckedRunnable.
1478 +     */
1479 +    Thread newStartedThread(Action action) {
1480 +        return newStartedThread(checkedRunnable(action));
1481 +    }
1482 +
1483 +    /**
1484       * Waits for the specified time (in milliseconds) for the thread
1485       * to terminate (using {@link Thread#join(long)}), else interrupts
1486       * the thread (in the hope that it may terminate later) and fails.
1487       */
1488 <    void awaitTermination(Thread t, long timeoutMillis) {
1488 >    void awaitTermination(Thread thread, long timeoutMillis) {
1489          try {
1490 <            t.join(timeoutMillis);
1490 >            thread.join(timeoutMillis);
1491          } catch (InterruptedException fail) {
1492              threadUnexpectedException(fail);
1493 <        } finally {
1494 <            if (t.getState() != Thread.State.TERMINATED) {
1495 <                t.interrupt();
1496 <                threadFail("timed out waiting for thread to terminate");
1493 >        }
1494 >        if (thread.getState() != Thread.State.TERMINATED) {
1495 >            String detail = String.format(
1496 >                    "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1497 >                    thread, thread.getState());
1498 >            try {
1499 >                threadFail(detail);
1500 >            } finally {
1501 >                // Interrupt thread __after__ having reported its stack trace
1502 >                thread.interrupt();
1503              }
1504          }
1505      }
# Line 1507 | Line 1527 | public class JSR166TestCase extends Test
1527          }
1528      }
1529  
1530 <    public abstract class RunnableShouldThrow implements Runnable {
1531 <        protected abstract void realRun() throws Throwable;
1532 <
1533 <        final Class<?> exceptionClass;
1534 <
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 <        }
1530 >    Runnable checkedRunnable(Action action) {
1531 >        return new CheckedRunnable() {
1532 >            public void realRun() throws Throwable {
1533 >                action.run();
1534 >            }};
1535      }
1536  
1537      public abstract class ThreadShouldThrow extends Thread {
# Line 1539 | Line 1546 | public class JSR166TestCase extends Test
1546          public final void run() {
1547              try {
1548                  realRun();
1542                threadShouldThrow(exceptionClass.getSimpleName());
1549              } catch (Throwable t) {
1550                  if (! exceptionClass.isInstance(t))
1551                      threadUnexpectedException(t);
1552 +                return;
1553              }
1554 +            threadShouldThrow(exceptionClass.getSimpleName());
1555          }
1556      }
1557  
# Line 1553 | Line 1561 | public class JSR166TestCase extends Test
1561          public final void run() {
1562              try {
1563                  realRun();
1556                threadShouldThrow("InterruptedException");
1564              } catch (InterruptedException success) {
1565                  threadAssertFalse(Thread.interrupted());
1566 +                return;
1567              } catch (Throwable fail) {
1568                  threadUnexpectedException(fail);
1569              }
1570 +            threadShouldThrow("InterruptedException");
1571          }
1572      }
1573  
# Line 1570 | Line 1579 | public class JSR166TestCase extends Test
1579                  return realCall();
1580              } catch (Throwable fail) {
1581                  threadUnexpectedException(fail);
1573                return null;
1574            }
1575        }
1576    }
1577
1578    public abstract class CheckedInterruptedCallable<T>
1579        implements Callable<T> {
1580        protected abstract T realCall() throws Throwable;
1581
1582        public final T call() {
1583            try {
1584                T result = realCall();
1585                threadShouldThrow("InterruptedException");
1586                return result;
1587            } catch (InterruptedException success) {
1588                threadAssertFalse(Thread.interrupted());
1589            } catch (Throwable fail) {
1590                threadUnexpectedException(fail);
1582              }
1583 <            return null;
1583 >            throw new AssertionError("unreached");
1584          }
1585      }
1586  
# Line 1646 | Line 1637 | public class JSR166TestCase extends Test
1637      }
1638  
1639      public void await(CountDownLatch latch, long timeoutMillis) {
1640 +        boolean timedOut = false;
1641          try {
1642 <            if (!latch.await(timeoutMillis, MILLISECONDS))
1651 <                fail("timed out waiting for CountDownLatch for "
1652 <                     + (timeoutMillis/1000) + " sec");
1642 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1643          } catch (Throwable fail) {
1644              threadUnexpectedException(fail);
1645          }
1646 +        if (timedOut)
1647 +            fail("timed out waiting for CountDownLatch for "
1648 +                 + (timeoutMillis/1000) + " sec");
1649      }
1650  
1651      public void await(CountDownLatch latch) {
# Line 1660 | Line 1653 | public class JSR166TestCase extends Test
1653      }
1654  
1655      public void await(Semaphore semaphore) {
1656 +        boolean timedOut = false;
1657          try {
1658 <            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1665 <                fail("timed out waiting for Semaphore for "
1666 <                     + (LONG_DELAY_MS/1000) + " sec");
1658 >            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1659          } catch (Throwable fail) {
1660              threadUnexpectedException(fail);
1661          }
1662 +        if (timedOut)
1663 +            fail("timed out waiting for Semaphore for "
1664 +                 + (LONG_DELAY_MS/1000) + " sec");
1665      }
1666  
1667      public void await(CyclicBarrier barrier) {
# Line 1691 | Line 1686 | public class JSR166TestCase extends Test
1686   //         long startTime = System.nanoTime();
1687   //         while (!flag.get()) {
1688   //             if (millisElapsedSince(startTime) > timeoutMillis)
1689 < //                 throw new AssertionFailedError("timed out");
1689 > //                 throw new AssertionError("timed out");
1690   //             Thread.yield();
1691   //         }
1692   //     }
# Line 1700 | Line 1695 | public class JSR166TestCase extends Test
1695          public String call() { throw new NullPointerException(); }
1696      }
1697  
1703    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1704        protected void realRun() {
1705            try {
1706                delay(SMALL_DELAY_MS);
1707            } catch (InterruptedException ok) {}
1708        }
1709    }
1710
1698      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1699          return new CheckedRunnable() {
1700              protected void realRun() {
# Line 1763 | Line 1750 | public class JSR166TestCase extends Test
1750                  return realCompute();
1751              } catch (Throwable fail) {
1752                  threadUnexpectedException(fail);
1766                return null;
1753              }
1754 +            throw new AssertionError("unreached");
1755          }
1756      }
1757  
# Line 1778 | Line 1765 | public class JSR166TestCase extends Test
1765  
1766      /**
1767       * A CyclicBarrier that uses timed await and fails with
1768 <     * AssertionFailedErrors instead of throwing checked exceptions.
1768 >     * AssertionErrors instead of throwing checked exceptions.
1769       */
1770      public static class CheckedBarrier extends CyclicBarrier {
1771          public CheckedBarrier(int parties) { super(parties); }
# Line 1787 | Line 1774 | public class JSR166TestCase extends Test
1774              try {
1775                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1776              } catch (TimeoutException timedOut) {
1777 <                throw new AssertionFailedError("timed out");
1777 >                throw new AssertionError("timed out");
1778              } catch (Exception fail) {
1779 <                AssertionFailedError afe =
1793 <                    new AssertionFailedError("Unexpected exception: " + fail);
1794 <                afe.initCause(fail);
1795 <                throw afe;
1779 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1780              }
1781          }
1782      }
# Line 1844 | Line 1828 | public class JSR166TestCase extends Test
1828          }
1829      }
1830  
1831 <    void assertImmutable(final Object o) {
1831 >    void assertImmutable(Object o) {
1832          if (o instanceof Collection) {
1833              assertThrows(
1834                  UnsupportedOperationException.class,
1835 <                new Runnable() { public void run() {
1852 <                        ((Collection) o).add(null);}});
1835 >                () -> ((Collection) o).add(null));
1836          }
1837      }
1838  
1839      @SuppressWarnings("unchecked")
1840      <T> T serialClone(T o) {
1841 +        T clone = null;
1842          try {
1843              ObjectInputStream ois = new ObjectInputStream
1844                  (new ByteArrayInputStream(serialBytes(o)));
1845 <            T clone = (T) ois.readObject();
1862 <            if (o == clone) assertImmutable(o);
1863 <            assertSame(o.getClass(), clone.getClass());
1864 <            return clone;
1845 >            clone = (T) ois.readObject();
1846          } catch (Throwable fail) {
1847              threadUnexpectedException(fail);
1867            return null;
1848          }
1849 +        if (o == clone) assertImmutable(o);
1850 +        else assertSame(o.getClass(), clone.getClass());
1851 +        return clone;
1852      }
1853  
1854      /**
# Line 1884 | Line 1867 | public class JSR166TestCase extends Test
1867              (new ByteArrayInputStream(bos.toByteArray()));
1868          T clone = (T) ois.readObject();
1869          if (o == clone) assertImmutable(o);
1870 <        assertSame(o.getClass(), clone.getClass());
1870 >        else assertSame(o.getClass(), clone.getClass());
1871          return clone;
1872      }
1873  
# Line 1909 | Line 1892 | public class JSR166TestCase extends Test
1892      }
1893  
1894      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1895 <                             Runnable... throwingActions) {
1896 <        for (Runnable throwingAction : throwingActions) {
1895 >                             Action... throwingActions) {
1896 >        for (Action throwingAction : throwingActions) {
1897              boolean threw = false;
1898              try { throwingAction.run(); }
1899              catch (Throwable t) {
1900                  threw = true;
1901 <                if (!expectedExceptionClass.isInstance(t)) {
1902 <                    AssertionFailedError afe =
1903 <                        new AssertionFailedError
1904 <                        ("Expected " + expectedExceptionClass.getName() +
1905 <                         ", got " + t.getClass().getName());
1923 <                    afe.initCause(t);
1924 <                    threadUnexpectedException(afe);
1925 <                }
1901 >                if (!expectedExceptionClass.isInstance(t))
1902 >                    throw new AssertionError(
1903 >                            "Expected " + expectedExceptionClass.getName() +
1904 >                            ", got " + t.getClass().getName(),
1905 >                            t);
1906              }
1907              if (!threw)
1908                  shouldThrow(expectedExceptionClass.getName());
# Line 1954 | Line 1934 | public class JSR166TestCase extends Test
1934      static <T> void shuffle(T[] array) {
1935          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1936      }
1937 +
1938 +    /**
1939 +     * Returns the same String as would be returned by {@link
1940 +     * Object#toString}, whether or not the given object's class
1941 +     * overrides toString().
1942 +     *
1943 +     * @see System#identityHashCode
1944 +     */
1945 +    static String identityString(Object x) {
1946 +        return x.getClass().getName()
1947 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1948 +    }
1949 +
1950 +    // --- Shared assertions for Executor tests ---
1951 +
1952 +    /**
1953 +     * Returns maximum number of tasks that can be submitted to given
1954 +     * pool (with bounded queue) before saturation (when submission
1955 +     * throws RejectedExecutionException).
1956 +     */
1957 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1958 +        BlockingQueue<Runnable> q = pool.getQueue();
1959 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1960 +    }
1961 +
1962 +    @SuppressWarnings("FutureReturnValueIgnored")
1963 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1964 +        try {
1965 +            e.execute((Runnable) null);
1966 +            shouldThrow();
1967 +        } catch (NullPointerException success) {}
1968 +
1969 +        if (! (e instanceof ExecutorService)) return;
1970 +        ExecutorService es = (ExecutorService) e;
1971 +        try {
1972 +            es.submit((Runnable) null);
1973 +            shouldThrow();
1974 +        } catch (NullPointerException success) {}
1975 +        try {
1976 +            es.submit((Runnable) null, Boolean.TRUE);
1977 +            shouldThrow();
1978 +        } catch (NullPointerException success) {}
1979 +        try {
1980 +            es.submit((Callable) null);
1981 +            shouldThrow();
1982 +        } catch (NullPointerException success) {}
1983 +
1984 +        if (! (e instanceof ScheduledExecutorService)) return;
1985 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1986 +        try {
1987 +            ses.schedule((Runnable) null,
1988 +                         randomTimeout(), randomTimeUnit());
1989 +            shouldThrow();
1990 +        } catch (NullPointerException success) {}
1991 +        try {
1992 +            ses.schedule((Callable) null,
1993 +                         randomTimeout(), randomTimeUnit());
1994 +            shouldThrow();
1995 +        } catch (NullPointerException success) {}
1996 +        try {
1997 +            ses.scheduleAtFixedRate((Runnable) null,
1998 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1999 +            shouldThrow();
2000 +        } catch (NullPointerException success) {}
2001 +        try {
2002 +            ses.scheduleWithFixedDelay((Runnable) null,
2003 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2004 +            shouldThrow();
2005 +        } catch (NullPointerException success) {}
2006 +    }
2007 +
2008 +    void setRejectedExecutionHandler(
2009 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2010 +        p.setRejectedExecutionHandler(handler);
2011 +        assertSame(handler, p.getRejectedExecutionHandler());
2012 +    }
2013 +
2014 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2015 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2016 +        final long savedTaskCount = p.getTaskCount();
2017 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2018 +        final int savedQueueSize = p.getQueue().size();
2019 +        final boolean stock = (p.getClass().getClassLoader() == null);
2020 +
2021 +        Runnable r = () -> {};
2022 +        Callable<Boolean> c = () -> Boolean.TRUE;
2023 +
2024 +        class Recorder implements RejectedExecutionHandler {
2025 +            public volatile Runnable r = null;
2026 +            public volatile ThreadPoolExecutor p = null;
2027 +            public void reset() { r = null; p = null; }
2028 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2029 +                assertNull(this.r);
2030 +                assertNull(this.p);
2031 +                this.r = r;
2032 +                this.p = p;
2033 +            }
2034 +        }
2035 +
2036 +        // check custom handler is invoked exactly once per task
2037 +        Recorder recorder = new Recorder();
2038 +        setRejectedExecutionHandler(p, recorder);
2039 +        for (int i = 2; i--> 0; ) {
2040 +            recorder.reset();
2041 +            p.execute(r);
2042 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2043 +                assertSame(r, recorder.r);
2044 +            assertSame(p, recorder.p);
2045 +
2046 +            recorder.reset();
2047 +            assertFalse(p.submit(r).isDone());
2048 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2049 +            assertSame(p, recorder.p);
2050 +
2051 +            recorder.reset();
2052 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2053 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2054 +            assertSame(p, recorder.p);
2055 +
2056 +            recorder.reset();
2057 +            assertFalse(p.submit(c).isDone());
2058 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2059 +            assertSame(p, recorder.p);
2060 +
2061 +            if (p instanceof ScheduledExecutorService) {
2062 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2063 +                ScheduledFuture<?> future;
2064 +
2065 +                recorder.reset();
2066 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2067 +                assertFalse(future.isDone());
2068 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2069 +                assertSame(p, recorder.p);
2070 +
2071 +                recorder.reset();
2072 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2073 +                assertFalse(future.isDone());
2074 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2075 +                assertSame(p, recorder.p);
2076 +
2077 +                recorder.reset();
2078 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2079 +                assertFalse(future.isDone());
2080 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2081 +                assertSame(p, recorder.p);
2082 +
2083 +                recorder.reset();
2084 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2085 +                assertFalse(future.isDone());
2086 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2087 +                assertSame(p, recorder.p);
2088 +            }
2089 +        }
2090 +
2091 +        // Checking our custom handler above should be sufficient, but
2092 +        // we add some integration tests of standard handlers.
2093 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2094 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2095 +
2096 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2097 +        try {
2098 +            p.execute(setThread);
2099 +            shouldThrow();
2100 +        } catch (RejectedExecutionException success) {}
2101 +        assertNull(thread.get());
2102 +
2103 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2104 +        p.execute(setThread);
2105 +        assertNull(thread.get());
2106 +
2107 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2108 +        p.execute(setThread);
2109 +        if (p.isShutdown())
2110 +            assertNull(thread.get());
2111 +        else
2112 +            assertSame(Thread.currentThread(), thread.get());
2113 +
2114 +        setRejectedExecutionHandler(p, savedHandler);
2115 +
2116 +        // check that pool was not perturbed by handlers
2117 +        assertEquals(savedTaskCount, p.getTaskCount());
2118 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2119 +        assertEquals(savedQueueSize, p.getQueue().size());
2120 +    }
2121 +
2122 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2123 +        assertEquals(x, y);
2124 +        assertEquals(y, x);
2125 +        assertEquals(x.isEmpty(), y.isEmpty());
2126 +        assertEquals(x.size(), y.size());
2127 +        if (x instanceof List) {
2128 +            assertEquals(x.toString(), y.toString());
2129 +        }
2130 +        if (x instanceof List || x instanceof Set) {
2131 +            assertEquals(x.hashCode(), y.hashCode());
2132 +        }
2133 +        if (x instanceof List || x instanceof Deque) {
2134 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2135 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2136 +                                     y.toArray(new Object[0])));
2137 +        }
2138 +    }
2139 +
2140 +    /**
2141 +     * A weaker form of assertCollectionsEquals which does not insist
2142 +     * that the two collections satisfy Object#equals(Object), since
2143 +     * they may use identity semantics as Deques do.
2144 +     */
2145 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2146 +        if (x instanceof List || x instanceof Set)
2147 +            assertCollectionsEquals(x, y);
2148 +        else {
2149 +            assertEquals(x.isEmpty(), y.isEmpty());
2150 +            assertEquals(x.size(), y.size());
2151 +            assertEquals(new HashSet(x), new HashSet(y));
2152 +            if (x instanceof Deque) {
2153 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2154 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2155 +                                         y.toArray(new Object[0])));
2156 +            }
2157 +        }
2158 +    }
2159   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines