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.231 by jsr166, Mon May 15 17:02:46 2017 UTC vs.
Revision 1.271 by jsr166, Sat Feb 1 18:52:17 2020 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;
99   import java.util.concurrent.ThreadPoolExecutor;
100 + import java.util.concurrent.TimeUnit;
101   import java.util.concurrent.TimeoutException;
102   import java.util.concurrent.atomic.AtomicBoolean;
103   import java.util.concurrent.atomic.AtomicReference;
104   import java.util.regex.Pattern;
105  
96 import junit.framework.AssertionFailedError;
106   import junit.framework.Test;
107   import junit.framework.TestCase;
108   import junit.framework.TestResult;
# Line 109 | 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 227 | 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 268 | 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 293 | 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 337 | 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 413 | 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",
417 <                                                       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 439 | 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 502 | 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 538 | 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 600 | 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 617 | 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 662 | public class JSR166TestCase extends Test
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;
673 +    static {
674 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
675 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
676 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
677 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
678 +        TimeUnit[] timeUnits = TimeUnit.values();
679 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
680 +    }
681 +
682 +    /**
683 +     * Returns a timeout for use when any value at all will do.
684 +     */
685 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
686 +
687 +    /**
688 +     * Returns a timeout that means "no waiting", i.e. not positive.
689 +     */
690 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
691 +
692 +    /**
693 +     * Returns a random non-null TimeUnit.
694 +     */
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(List<T> choices) {
708 +        return choices.get(ThreadLocalRandom.current().nextInt(choices.size()));
709 +    }
710 +
711 +    /**
712 +     * Returns a random element from given choices.
713 +     */
714 +    <T> T chooseRandomly(T... choices) {
715 +        return choices[ThreadLocalRandom.current().nextInt(choices.length)];
716 +    }
717 +
718 +    /**
719       * Returns the shortest timed delay. This can be scaled up for
720       * slow machines using the jsr166.delay.factor system property,
721       * or via jtreg's -timeoutFactor: flag.
# Line 656 | Line 733 | public class JSR166TestCase extends Test
733          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
734          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
735          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
736 +        LONGER_DELAY_MS = 2 * LONG_DELAY_MS;
737      }
738  
739      private static final long TIMEOUT_DELAY_MS
# Line 694 | Line 772 | public class JSR166TestCase extends Test
772       */
773      public void threadRecordFailure(Throwable t) {
774          System.err.println(t);
775 <        dumpTestThreads();
776 <        threadFailure.compareAndSet(null, t);
775 >        if (threadFailure.compareAndSet(null, t))
776 >            dumpTestThreads();
777      }
778  
779      public void setUp() {
# Line 706 | Line 784 | public class JSR166TestCase extends Test
784          String msg = toString() + ": " + String.format(format, args);
785          System.err.println(msg);
786          dumpTestThreads();
787 <        throw new AssertionFailedError(msg);
787 >        throw new AssertionError(msg);
788      }
789  
790      /**
# Line 727 | Line 805 | public class JSR166TestCase extends Test
805                  throw (RuntimeException) t;
806              else if (t instanceof Exception)
807                  throw (Exception) t;
808 <            else {
809 <                AssertionFailedError afe =
732 <                    new AssertionFailedError(t.toString());
733 <                afe.initCause(t);
734 <                throw afe;
735 <            }
808 >            else
809 >                throw new AssertionError(t.toString(), t);
810          }
811  
812          if (Thread.interrupted())
# Line 766 | Line 840 | public class JSR166TestCase extends Test
840  
841      /**
842       * Just like fail(reason), but additionally recording (using
843 <     * threadRecordFailure) any AssertionFailedError thrown, so that
844 <     * the current testcase will fail.
843 >     * threadRecordFailure) any AssertionError thrown, so that the
844 >     * current testcase will fail.
845       */
846      public void threadFail(String reason) {
847          try {
848              fail(reason);
849 <        } catch (AssertionFailedError t) {
850 <            threadRecordFailure(t);
851 <            throw t;
849 >        } catch (AssertionError fail) {
850 >            threadRecordFailure(fail);
851 >            throw fail;
852          }
853      }
854  
855      /**
856       * Just like assertTrue(b), but additionally recording (using
857 <     * threadRecordFailure) any AssertionFailedError thrown, so that
858 <     * the current testcase will fail.
857 >     * threadRecordFailure) any AssertionError thrown, so that the
858 >     * current testcase will fail.
859       */
860      public void threadAssertTrue(boolean b) {
861          try {
862              assertTrue(b);
863 <        } catch (AssertionFailedError t) {
864 <            threadRecordFailure(t);
865 <            throw t;
863 >        } catch (AssertionError fail) {
864 >            threadRecordFailure(fail);
865 >            throw fail;
866          }
867      }
868  
869      /**
870       * Just like assertFalse(b), but additionally recording (using
871 <     * threadRecordFailure) any AssertionFailedError thrown, so that
872 <     * the current testcase will fail.
871 >     * threadRecordFailure) any AssertionError thrown, so that the
872 >     * current testcase will fail.
873       */
874      public void threadAssertFalse(boolean b) {
875          try {
876              assertFalse(b);
877 <        } catch (AssertionFailedError t) {
878 <            threadRecordFailure(t);
879 <            throw t;
877 >        } catch (AssertionError fail) {
878 >            threadRecordFailure(fail);
879 >            throw fail;
880          }
881      }
882  
883      /**
884       * Just like assertNull(x), but additionally recording (using
885 <     * threadRecordFailure) any AssertionFailedError thrown, so that
886 <     * the current testcase will fail.
885 >     * threadRecordFailure) any AssertionError thrown, so that the
886 >     * current testcase will fail.
887       */
888      public void threadAssertNull(Object x) {
889          try {
890              assertNull(x);
891 <        } catch (AssertionFailedError t) {
892 <            threadRecordFailure(t);
893 <            throw t;
891 >        } catch (AssertionError fail) {
892 >            threadRecordFailure(fail);
893 >            throw fail;
894          }
895      }
896  
897      /**
898       * Just like assertEquals(x, y), but additionally recording (using
899 <     * threadRecordFailure) any AssertionFailedError thrown, so that
900 <     * the current testcase will fail.
899 >     * threadRecordFailure) any AssertionError thrown, so that the
900 >     * current testcase will fail.
901       */
902      public void threadAssertEquals(long x, long y) {
903          try {
904              assertEquals(x, y);
905 <        } catch (AssertionFailedError t) {
906 <            threadRecordFailure(t);
907 <            throw t;
905 >        } catch (AssertionError fail) {
906 >            threadRecordFailure(fail);
907 >            throw fail;
908          }
909      }
910  
911      /**
912       * Just like assertEquals(x, y), but additionally recording (using
913 <     * threadRecordFailure) any AssertionFailedError thrown, so that
914 <     * the current testcase will fail.
913 >     * threadRecordFailure) any AssertionError thrown, so that the
914 >     * current testcase will fail.
915       */
916      public void threadAssertEquals(Object x, Object y) {
917          try {
918              assertEquals(x, y);
919 <        } catch (AssertionFailedError fail) {
919 >        } catch (AssertionError fail) {
920              threadRecordFailure(fail);
921              throw fail;
922          } catch (Throwable fail) {
# Line 852 | Line 926 | public class JSR166TestCase extends Test
926  
927      /**
928       * Just like assertSame(x, y), but additionally recording (using
929 <     * threadRecordFailure) any AssertionFailedError thrown, so that
930 <     * the current testcase will fail.
929 >     * threadRecordFailure) any AssertionError thrown, so that the
930 >     * current testcase will fail.
931       */
932      public void threadAssertSame(Object x, Object y) {
933          try {
934              assertSame(x, y);
935 <        } catch (AssertionFailedError fail) {
935 >        } catch (AssertionError fail) {
936              threadRecordFailure(fail);
937              throw fail;
938          }
# Line 880 | Line 954 | public class JSR166TestCase extends Test
954  
955      /**
956       * Records the given exception using {@link #threadRecordFailure},
957 <     * then rethrows the exception, wrapping it in an
958 <     * AssertionFailedError if necessary.
957 >     * then rethrows the exception, wrapping it in an AssertionError
958 >     * if necessary.
959       */
960      public void threadUnexpectedException(Throwable t) {
961          threadRecordFailure(t);
# Line 890 | Line 964 | public class JSR166TestCase extends Test
964              throw (RuntimeException) t;
965          else if (t instanceof Error)
966              throw (Error) t;
967 <        else {
968 <            AssertionFailedError afe =
895 <                new AssertionFailedError("unexpected exception: " + t);
896 <            afe.initCause(t);
897 <            throw afe;
898 <        }
967 >        else
968 >            throw new AssertionError("unexpected exception: " + t, t);
969      }
970  
971      /**
# Line 1024 | Line 1094 | public class JSR166TestCase extends Test
1094          }
1095      }
1096  
1097 +    /** Returns true if thread info might be useful in a thread dump. */
1098 +    static boolean threadOfInterest(ThreadInfo info) {
1099 +        final String name = info.getThreadName();
1100 +        String lockName;
1101 +        if (name == null)
1102 +            return true;
1103 +        if (name.equals("Signal Dispatcher")
1104 +            || name.equals("WedgedTestDetector"))
1105 +            return false;
1106 +        if (name.equals("Reference Handler")) {
1107 +            // Reference Handler stacktrace changed in JDK-8156500
1108 +            StackTraceElement[] stackTrace; String methodName;
1109 +            if ((stackTrace = info.getStackTrace()) != null
1110 +                && stackTrace.length > 0
1111 +                && (methodName = stackTrace[0].getMethodName()) != null
1112 +                && methodName.equals("waitForReferencePendingList"))
1113 +                return false;
1114 +            // jdk8 Reference Handler stacktrace
1115 +            if ((lockName = info.getLockName()) != null
1116 +                && lockName.startsWith("java.lang.ref"))
1117 +                return false;
1118 +        }
1119 +        if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
1120 +            && (lockName = info.getLockName()) != null
1121 +            && lockName.startsWith("java.lang.ref"))
1122 +            return false;
1123 +        if (name.startsWith("ForkJoinPool.commonPool-worker")
1124 +            && (lockName = info.getLockName()) != null
1125 +            && lockName.startsWith("java.util.concurrent.ForkJoinPool"))
1126 +            return false;
1127 +        return true;
1128 +    }
1129 +
1130      /**
1131       * A debugging tool to print stack traces of most threads, as jstack does.
1132       * Uninteresting threads are filtered out.
# Line 1038 | Line 1141 | public class JSR166TestCase extends Test
1141              }
1142          }
1143  
1041        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1144          System.err.println("------ stacktrace dump start ------");
1145 <        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1146 <            final String name = info.getThreadName();
1147 <            String lockName;
1046 <            if ("Signal Dispatcher".equals(name))
1047 <                continue;
1048 <            if ("Reference Handler".equals(name)
1049 <                && (lockName = info.getLockName()) != null
1050 <                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1051 <                continue;
1052 <            if ("Finalizer".equals(name)
1053 <                && (lockName = info.getLockName()) != null
1054 <                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1055 <                continue;
1056 <            if ("checkForWedgedTest".equals(name))
1057 <                continue;
1058 <            System.err.print(info);
1059 <        }
1145 >        for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true))
1146 >            if (threadOfInterest(info))
1147 >                System.err.print(info);
1148          System.err.println("------ stacktrace dump end ------");
1149  
1150          if (sm != null) System.setSecurityManager(sm);
# Line 1071 | Line 1159 | public class JSR166TestCase extends Test
1159          for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1160              try { delay(1); }
1161              catch (InterruptedException fail) {
1162 <                fail("Unexpected InterruptedException");
1162 >                throw new AssertionError("Unexpected InterruptedException", fail);
1163              }
1164              Thread.State s = thread.getState();
1165              if (s == expected)
# Line 1083 | Line 1171 | public class JSR166TestCase extends Test
1171      }
1172  
1173      /**
1174 <     * Checks that thread does not terminate within the default
1087 <     * millisecond delay of {@code timeoutMillis()}.
1088 <     * TODO: REMOVEME
1089 <     */
1090 <    void assertThreadStaysAlive(Thread thread) {
1091 <        assertThreadStaysAlive(thread, timeoutMillis());
1092 <    }
1093 <
1094 <    /**
1095 <     * Checks that thread does not terminate within the given millisecond delay.
1096 <     * TODO: REMOVEME
1174 >     * Returns the thread's blocker's class name, if any, else null.
1175       */
1176 <    void assertThreadStaysAlive(Thread thread, long millis) {
1177 <        try {
1178 <            // No need to optimize the failing case via Thread.join.
1179 <            delay(millis);
1180 <            assertTrue(thread.isAlive());
1181 <        } catch (InterruptedException fail) {
1104 <            threadFail("Unexpected InterruptedException");
1105 <        }
1106 <    }
1107 <
1108 <    /**
1109 <     * Checks that the threads do not terminate within the default
1110 <     * millisecond delay of {@code timeoutMillis()}.
1111 <     * TODO: REMOVEME
1112 <     */
1113 <    void assertThreadsStayAlive(Thread... threads) {
1114 <        assertThreadsStayAlive(timeoutMillis(), threads);
1115 <    }
1116 <
1117 <    /**
1118 <     * Checks that the threads do not terminate within the given millisecond delay.
1119 <     * TODO: REMOVEME
1120 <     */
1121 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1122 <        try {
1123 <            // No need to optimize the failing case via Thread.join.
1124 <            delay(millis);
1125 <            for (Thread thread : threads)
1126 <                assertTrue(thread.isAlive());
1127 <        } catch (InterruptedException fail) {
1128 <            threadFail("Unexpected InterruptedException");
1129 <        }
1176 >    String blockerClassName(Thread thread) {
1177 >        ThreadInfo threadInfo; LockInfo lockInfo;
1178 >        if ((threadInfo = THREAD_MXBEAN.getThreadInfo(thread.getId(), 0)) != null
1179 >            && (lockInfo = threadInfo.getLockInfo()) != null)
1180 >            return lockInfo.getClassName();
1181 >        return null;
1182      }
1183  
1184      /**
# Line 1148 | Line 1200 | public class JSR166TestCase extends Test
1200          } catch (TimeoutException success) {
1201          } catch (Exception fail) {
1202              threadUnexpectedException(fail);
1203 <        } finally { future.cancel(true); }
1203 >        }
1204          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1205 +        assertFalse(future.isDone());
1206      }
1207  
1208      /**
# Line 1304 | Line 1357 | public class JSR166TestCase extends Test
1357  
1358      /**
1359       * Sleeps until the given time has elapsed.
1360 <     * Throws AssertionFailedError if interrupted.
1360 >     * Throws AssertionError if interrupted.
1361       */
1362      static void sleep(long millis) {
1363          try {
1364              delay(millis);
1365          } catch (InterruptedException fail) {
1366 <            AssertionFailedError afe =
1314 <                new AssertionFailedError("Unexpected InterruptedException");
1315 <            afe.initCause(fail);
1316 <            throw afe;
1366 >            throw new AssertionError("Unexpected InterruptedException", fail);
1367          }
1368      }
1369  
1370      /**
1371       * Spin-waits up to the specified number of milliseconds for the given
1372       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1373 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1374       */
1375 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1376 <        long startTime = 0L;
1377 <        for (;;) {
1378 <            Thread.State s = thread.getState();
1379 <            if (s == Thread.State.BLOCKED ||
1380 <                s == Thread.State.WAITING ||
1381 <                s == Thread.State.TIMED_WAITING)
1382 <                return;
1383 <            else if (s == Thread.State.TERMINATED)
1375 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1376 >                                       Callable<Boolean> waitingForGodot) {
1377 >        for (long startTime = 0L;;) {
1378 >            switch (thread.getState()) {
1379 >            default: break;
1380 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1381 >                try {
1382 >                    if (waitingForGodot == null || waitingForGodot.call())
1383 >                        return;
1384 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1385 >                break;
1386 >            case TERMINATED:
1387                  fail("Unexpected thread termination");
1388 <            else if (startTime == 0L)
1388 >            }
1389 >
1390 >            if (startTime == 0L)
1391                  startTime = System.nanoTime();
1392              else if (millisElapsedSince(startTime) > timeoutMillis) {
1393 <                threadAssertTrue(thread.isAlive());
1394 <                fail("timed out waiting for thread to enter wait state");
1393 >                assertTrue(thread.isAlive());
1394 >                if (waitingForGodot == null
1395 >                    || thread.getState() == Thread.State.RUNNABLE)
1396 >                    fail("timed out waiting for thread to enter wait state");
1397 >                else
1398 >                    fail("timed out waiting for condition, thread state="
1399 >                         + thread.getState());
1400              }
1401              Thread.yield();
1402          }
# Line 1343 | Line 1404 | public class JSR166TestCase extends Test
1404  
1405      /**
1406       * Spin-waits up to the specified number of milliseconds for the given
1407 <     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1347 <     * and additionally satisfy the given condition.
1407 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1408       */
1409 <    void waitForThreadToEnterWaitState(
1410 <        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1351 <        long startTime = 0L;
1352 <        for (;;) {
1353 <            Thread.State s = thread.getState();
1354 <            if (s == Thread.State.BLOCKED ||
1355 <                s == Thread.State.WAITING ||
1356 <                s == Thread.State.TIMED_WAITING) {
1357 <                try {
1358 <                    if (waitingForGodot.call())
1359 <                        return;
1360 <                } catch (Throwable fail) { threadUnexpectedException(fail); }
1361 <            }
1362 <            else if (s == Thread.State.TERMINATED)
1363 <                fail("Unexpected thread termination");
1364 <            else if (startTime == 0L)
1365 <                startTime = System.nanoTime();
1366 <            else if (millisElapsedSince(startTime) > timeoutMillis) {
1367 <                threadAssertTrue(thread.isAlive());
1368 <                fail("timed out waiting for thread to enter wait state");
1369 <            }
1370 <            Thread.yield();
1371 <        }
1409 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1410 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1411      }
1412  
1413      /**
# Line 1376 | Line 1415 | public class JSR166TestCase extends Test
1415       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1416       */
1417      void waitForThreadToEnterWaitState(Thread thread) {
1418 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1418 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1419      }
1420  
1421      /**
# Line 1384 | Line 1423 | public class JSR166TestCase extends Test
1423       * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1424       * and additionally satisfy the given condition.
1425       */
1426 <    void waitForThreadToEnterWaitState(
1427 <        Thread thread, Callable<Boolean> waitingForGodot) {
1426 >    void waitForThreadToEnterWaitState(Thread thread,
1427 >                                       Callable<Boolean> waitingForGodot) {
1428          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1429      }
1430  
1431      /**
1432 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1433 +     * be interrupted.  Clears the interrupt status before returning.
1434 +     */
1435 +    void awaitInterrupted() {
1436 +        for (long startTime = 0L; !Thread.interrupted(); ) {
1437 +            if (startTime == 0L)
1438 +                startTime = System.nanoTime();
1439 +            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1440 +                fail("timed out waiting for thread interrupt");
1441 +            Thread.yield();
1442 +        }
1443 +    }
1444 +
1445 +    /**
1446       * Returns the number of milliseconds since time given by
1447       * startNanoTime, which must have been previously returned from a
1448       * call to {@link System#nanoTime()}.
# Line 1398 | Line 1451 | public class JSR166TestCase extends Test
1451          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1452      }
1453  
1401 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1402 //         long startTime = System.nanoTime();
1403 //         try {
1404 //             r.run();
1405 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1406 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1407 //             throw new AssertionFailedError("did not return promptly");
1408 //     }
1409
1410 //     void assertTerminatesPromptly(Runnable r) {
1411 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1412 //     }
1413
1454      /**
1455       * Checks that timed f.get() returns the expected value, and does not
1456       * wait for the timeout to elapse before returning.
1457       */
1458      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1459          long startTime = System.nanoTime();
1460 +        T actual = null;
1461          try {
1462 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1462 >            actual = f.get(timeoutMillis, MILLISECONDS);
1463          } catch (Throwable fail) { threadUnexpectedException(fail); }
1464 +        assertEquals(expectedValue, actual);
1465          if (millisElapsedSince(startTime) > timeoutMillis/2)
1466 <            throw new AssertionFailedError("timed get did not return promptly");
1466 >            throw new AssertionError("timed get did not return promptly");
1467      }
1468  
1469      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1439 | Line 1481 | public class JSR166TestCase extends Test
1481      }
1482  
1483      /**
1484 +     * Returns a new started daemon Thread running the given action,
1485 +     * wrapped in a CheckedRunnable.
1486 +     */
1487 +    Thread newStartedThread(Action action) {
1488 +        return newStartedThread(checkedRunnable(action));
1489 +    }
1490 +
1491 +    /**
1492       * Waits for the specified time (in milliseconds) for the thread
1493       * to terminate (using {@link Thread#join(long)}), else interrupts
1494       * the thread (in the hope that it may terminate later) and fails.
1495       */
1496 <    void awaitTermination(Thread t, long timeoutMillis) {
1496 >    void awaitTermination(Thread thread, long timeoutMillis) {
1497          try {
1498 <            t.join(timeoutMillis);
1498 >            thread.join(timeoutMillis);
1499          } catch (InterruptedException fail) {
1500              threadUnexpectedException(fail);
1501 <        } finally {
1502 <            if (t.getState() != Thread.State.TERMINATED) {
1503 <                t.interrupt();
1504 <                threadFail("timed out waiting for thread to terminate");
1501 >        }
1502 >        if (thread.getState() != Thread.State.TERMINATED) {
1503 >            String detail = String.format(
1504 >                    "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1505 >                    thread, thread.getState());
1506 >            try {
1507 >                threadFail(detail);
1508 >            } finally {
1509 >                // Interrupt thread __after__ having reported its stack trace
1510 >                thread.interrupt();
1511              }
1512          }
1513      }
# Line 1479 | Line 1535 | public class JSR166TestCase extends Test
1535          }
1536      }
1537  
1538 <    public abstract class RunnableShouldThrow implements Runnable {
1539 <        protected abstract void realRun() throws Throwable;
1540 <
1541 <        final Class<?> exceptionClass;
1542 <
1487 <        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1488 <            this.exceptionClass = exceptionClass;
1489 <        }
1490 <
1491 <        public final void run() {
1492 <            try {
1493 <                realRun();
1494 <                threadShouldThrow(exceptionClass.getSimpleName());
1495 <            } catch (Throwable t) {
1496 <                if (! exceptionClass.isInstance(t))
1497 <                    threadUnexpectedException(t);
1498 <            }
1499 <        }
1538 >    Runnable checkedRunnable(Action action) {
1539 >        return new CheckedRunnable() {
1540 >            public void realRun() throws Throwable {
1541 >                action.run();
1542 >            }};
1543      }
1544  
1545      public abstract class ThreadShouldThrow extends Thread {
# Line 1511 | Line 1554 | public class JSR166TestCase extends Test
1554          public final void run() {
1555              try {
1556                  realRun();
1514                threadShouldThrow(exceptionClass.getSimpleName());
1557              } catch (Throwable t) {
1558                  if (! exceptionClass.isInstance(t))
1559                      threadUnexpectedException(t);
1560 +                return;
1561              }
1562 +            threadShouldThrow(exceptionClass.getSimpleName());
1563          }
1564      }
1565  
# Line 1525 | Line 1569 | public class JSR166TestCase extends Test
1569          public final void run() {
1570              try {
1571                  realRun();
1528                threadShouldThrow("InterruptedException");
1572              } catch (InterruptedException success) {
1573                  threadAssertFalse(Thread.interrupted());
1574 +                return;
1575              } catch (Throwable fail) {
1576                  threadUnexpectedException(fail);
1577              }
1578 +            threadShouldThrow("InterruptedException");
1579          }
1580      }
1581  
# Line 1542 | Line 1587 | public class JSR166TestCase extends Test
1587                  return realCall();
1588              } catch (Throwable fail) {
1589                  threadUnexpectedException(fail);
1545                return null;
1590              }
1591 <        }
1548 <    }
1549 <
1550 <    public abstract class CheckedInterruptedCallable<T>
1551 <        implements Callable<T> {
1552 <        protected abstract T realCall() throws Throwable;
1553 <
1554 <        public final T call() {
1555 <            try {
1556 <                T result = realCall();
1557 <                threadShouldThrow("InterruptedException");
1558 <                return result;
1559 <            } catch (InterruptedException success) {
1560 <                threadAssertFalse(Thread.interrupted());
1561 <            } catch (Throwable fail) {
1562 <                threadUnexpectedException(fail);
1563 <            }
1564 <            return null;
1591 >            throw new AssertionError("unreached");
1592          }
1593      }
1594  
# Line 1618 | Line 1645 | public class JSR166TestCase extends Test
1645      }
1646  
1647      public void await(CountDownLatch latch, long timeoutMillis) {
1648 +        boolean timedOut = false;
1649          try {
1650 <            if (!latch.await(timeoutMillis, MILLISECONDS))
1623 <                fail("timed out waiting for CountDownLatch for "
1624 <                     + (timeoutMillis/1000) + " sec");
1650 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1651          } catch (Throwable fail) {
1652              threadUnexpectedException(fail);
1653          }
1654 +        if (timedOut)
1655 +            fail("timed out waiting for CountDownLatch for "
1656 +                 + (timeoutMillis/1000) + " sec");
1657      }
1658  
1659      public void await(CountDownLatch latch) {
# Line 1632 | Line 1661 | public class JSR166TestCase extends Test
1661      }
1662  
1663      public void await(Semaphore semaphore) {
1664 +        boolean timedOut = false;
1665          try {
1666 <            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1637 <                fail("timed out waiting for Semaphore for "
1638 <                     + (LONG_DELAY_MS/1000) + " sec");
1666 >            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1667          } catch (Throwable fail) {
1668              threadUnexpectedException(fail);
1669          }
1670 +        if (timedOut)
1671 +            fail("timed out waiting for Semaphore for "
1672 +                 + (LONG_DELAY_MS/1000) + " sec");
1673      }
1674  
1675      public void await(CyclicBarrier barrier) {
# Line 1663 | Line 1694 | public class JSR166TestCase extends Test
1694   //         long startTime = System.nanoTime();
1695   //         while (!flag.get()) {
1696   //             if (millisElapsedSince(startTime) > timeoutMillis)
1697 < //                 throw new AssertionFailedError("timed out");
1697 > //                 throw new AssertionError("timed out");
1698   //             Thread.yield();
1699   //         }
1700   //     }
# Line 1672 | Line 1703 | public class JSR166TestCase extends Test
1703          public String call() { throw new NullPointerException(); }
1704      }
1705  
1675    public static class CallableOne implements Callable<Integer> {
1676        public Integer call() { return one; }
1677    }
1678
1679    public class ShortRunnable extends CheckedRunnable {
1680        protected void realRun() throws Throwable {
1681            delay(SHORT_DELAY_MS);
1682        }
1683    }
1684
1685    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1686        protected void realRun() throws InterruptedException {
1687            delay(SHORT_DELAY_MS);
1688        }
1689    }
1690
1691    public class SmallRunnable extends CheckedRunnable {
1692        protected void realRun() throws Throwable {
1693            delay(SMALL_DELAY_MS);
1694        }
1695    }
1696
1697    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1698        protected void realRun() {
1699            try {
1700                delay(SMALL_DELAY_MS);
1701            } catch (InterruptedException ok) {}
1702        }
1703    }
1704
1705    public class SmallCallable extends CheckedCallable {
1706        protected Object realCall() throws InterruptedException {
1707            delay(SMALL_DELAY_MS);
1708            return Boolean.TRUE;
1709        }
1710    }
1711
1712    public class MediumRunnable extends CheckedRunnable {
1713        protected void realRun() throws Throwable {
1714            delay(MEDIUM_DELAY_MS);
1715        }
1716    }
1717
1718    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1719        protected void realRun() throws InterruptedException {
1720            delay(MEDIUM_DELAY_MS);
1721        }
1722    }
1723
1706      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1707          return new CheckedRunnable() {
1708              protected void realRun() {
# Line 1730 | Line 1712 | public class JSR166TestCase extends Test
1712              }};
1713      }
1714  
1733    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1734        protected void realRun() {
1735            try {
1736                delay(MEDIUM_DELAY_MS);
1737            } catch (InterruptedException ok) {}
1738        }
1739    }
1740
1741    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1742        protected void realRun() {
1743            try {
1744                delay(LONG_DELAY_MS);
1745            } catch (InterruptedException ok) {}
1746        }
1747    }
1748
1715      /**
1716       * For use as ThreadFactory in constructors
1717       */
# Line 1759 | Line 1725 | public class JSR166TestCase extends Test
1725          boolean isDone();
1726      }
1727  
1762    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1763        return new TrackedRunnable() {
1764                private volatile boolean done = false;
1765                public boolean isDone() { return done; }
1766                public void run() {
1767                    try {
1768                        delay(timeoutMillis);
1769                        done = true;
1770                    } catch (InterruptedException ok) {}
1771                }
1772            };
1773    }
1774
1775    public static class TrackedShortRunnable implements Runnable {
1776        public volatile boolean done = false;
1777        public void run() {
1778            try {
1779                delay(SHORT_DELAY_MS);
1780                done = true;
1781            } catch (InterruptedException ok) {}
1782        }
1783    }
1784
1785    public static class TrackedSmallRunnable implements Runnable {
1786        public volatile boolean done = false;
1787        public void run() {
1788            try {
1789                delay(SMALL_DELAY_MS);
1790                done = true;
1791            } catch (InterruptedException ok) {}
1792        }
1793    }
1794
1795    public static class TrackedMediumRunnable implements Runnable {
1796        public volatile boolean done = false;
1797        public void run() {
1798            try {
1799                delay(MEDIUM_DELAY_MS);
1800                done = true;
1801            } catch (InterruptedException ok) {}
1802        }
1803    }
1804
1805    public static class TrackedLongRunnable implements Runnable {
1806        public volatile boolean done = false;
1807        public void run() {
1808            try {
1809                delay(LONG_DELAY_MS);
1810                done = true;
1811            } catch (InterruptedException ok) {}
1812        }
1813    }
1814
1728      public static class TrackedNoOpRunnable implements Runnable {
1729          public volatile boolean done = false;
1730          public void run() {
# Line 1819 | Line 1732 | public class JSR166TestCase extends Test
1732          }
1733      }
1734  
1822    public static class TrackedCallable implements Callable {
1823        public volatile boolean done = false;
1824        public Object call() {
1825            try {
1826                delay(SMALL_DELAY_MS);
1827                done = true;
1828            } catch (InterruptedException ok) {}
1829            return Boolean.TRUE;
1830        }
1831    }
1832
1735      /**
1736       * Analog of CheckedRunnable for RecursiveAction
1737       */
# Line 1856 | Line 1758 | public class JSR166TestCase extends Test
1758                  return realCompute();
1759              } catch (Throwable fail) {
1760                  threadUnexpectedException(fail);
1859                return null;
1761              }
1762 +            throw new AssertionError("unreached");
1763          }
1764      }
1765  
# Line 1871 | Line 1773 | public class JSR166TestCase extends Test
1773  
1774      /**
1775       * A CyclicBarrier that uses timed await and fails with
1776 <     * AssertionFailedErrors instead of throwing checked exceptions.
1776 >     * AssertionErrors instead of throwing checked exceptions.
1777       */
1778      public static class CheckedBarrier extends CyclicBarrier {
1779          public CheckedBarrier(int parties) { super(parties); }
1780  
1781          public int await() {
1782              try {
1783 <                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1783 >                return super.await(LONGER_DELAY_MS, MILLISECONDS);
1784              } catch (TimeoutException timedOut) {
1785 <                throw new AssertionFailedError("timed out");
1785 >                throw new AssertionError("timed out");
1786              } catch (Exception fail) {
1787 <                AssertionFailedError afe =
1886 <                    new AssertionFailedError("Unexpected exception: " + fail);
1887 <                afe.initCause(fail);
1888 <                throw afe;
1787 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1788              }
1789          }
1790      }
# Line 1896 | Line 1795 | public class JSR166TestCase extends Test
1795              assertEquals(0, q.size());
1796              assertNull(q.peek());
1797              assertNull(q.poll());
1798 <            assertNull(q.poll(0, MILLISECONDS));
1798 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1799              assertEquals(q.toString(), "[]");
1800              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1801              assertFalse(q.iterator().hasNext());
# Line 1937 | Line 1836 | public class JSR166TestCase extends Test
1836          }
1837      }
1838  
1839 <    void assertImmutable(final Object o) {
1839 >    void assertImmutable(Object o) {
1840          if (o instanceof Collection) {
1841              assertThrows(
1842                  UnsupportedOperationException.class,
1843 <                new Runnable() { public void run() {
1945 <                        ((Collection) o).add(null);}});
1843 >                () -> ((Collection) o).add(null));
1844          }
1845      }
1846  
1847      @SuppressWarnings("unchecked")
1848      <T> T serialClone(T o) {
1849 +        T clone = null;
1850          try {
1851              ObjectInputStream ois = new ObjectInputStream
1852                  (new ByteArrayInputStream(serialBytes(o)));
1853 <            T clone = (T) ois.readObject();
1955 <            if (o == clone) assertImmutable(o);
1956 <            assertSame(o.getClass(), clone.getClass());
1957 <            return clone;
1853 >            clone = (T) ois.readObject();
1854          } catch (Throwable fail) {
1855              threadUnexpectedException(fail);
1960            return null;
1856          }
1857 +        if (o == clone) assertImmutable(o);
1858 +        else assertSame(o.getClass(), clone.getClass());
1859 +        return clone;
1860      }
1861  
1862      /**
# Line 1977 | Line 1875 | public class JSR166TestCase extends Test
1875              (new ByteArrayInputStream(bos.toByteArray()));
1876          T clone = (T) ois.readObject();
1877          if (o == clone) assertImmutable(o);
1878 <        assertSame(o.getClass(), clone.getClass());
1878 >        else assertSame(o.getClass(), clone.getClass());
1879          return clone;
1880      }
1881  
# Line 2002 | Line 1900 | public class JSR166TestCase extends Test
1900      }
1901  
1902      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1903 <                             Runnable... throwingActions) {
1904 <        for (Runnable throwingAction : throwingActions) {
1903 >                             Action... throwingActions) {
1904 >        for (Action throwingAction : throwingActions) {
1905              boolean threw = false;
1906              try { throwingAction.run(); }
1907              catch (Throwable t) {
1908                  threw = true;
1909 <                if (!expectedExceptionClass.isInstance(t)) {
1910 <                    AssertionFailedError afe =
1911 <                        new AssertionFailedError
1912 <                        ("Expected " + expectedExceptionClass.getName() +
1913 <                         ", got " + t.getClass().getName());
2016 <                    afe.initCause(t);
2017 <                    threadUnexpectedException(afe);
2018 <                }
1909 >                if (!expectedExceptionClass.isInstance(t))
1910 >                    throw new AssertionError(
1911 >                            "Expected " + expectedExceptionClass.getName() +
1912 >                            ", got " + t.getClass().getName(),
1913 >                            t);
1914              }
1915              if (!threw)
1916                  shouldThrow(expectedExceptionClass.getName());
# Line 2047 | Line 1942 | public class JSR166TestCase extends Test
1942      static <T> void shuffle(T[] array) {
1943          Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1944      }
1945 +
1946 +    /**
1947 +     * Returns the same String as would be returned by {@link
1948 +     * Object#toString}, whether or not the given object's class
1949 +     * overrides toString().
1950 +     *
1951 +     * @see System#identityHashCode
1952 +     */
1953 +    static String identityString(Object x) {
1954 +        return x.getClass().getName()
1955 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1956 +    }
1957 +
1958 +    // --- Shared assertions for Executor tests ---
1959 +
1960 +    /**
1961 +     * Returns maximum number of tasks that can be submitted to given
1962 +     * pool (with bounded queue) before saturation (when submission
1963 +     * throws RejectedExecutionException).
1964 +     */
1965 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1966 +        BlockingQueue<Runnable> q = pool.getQueue();
1967 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1968 +    }
1969 +
1970 +    @SuppressWarnings("FutureReturnValueIgnored")
1971 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1972 +        try {
1973 +            e.execute((Runnable) null);
1974 +            shouldThrow();
1975 +        } catch (NullPointerException success) {}
1976 +
1977 +        if (! (e instanceof ExecutorService)) return;
1978 +        ExecutorService es = (ExecutorService) e;
1979 +        try {
1980 +            es.submit((Runnable) null);
1981 +            shouldThrow();
1982 +        } catch (NullPointerException success) {}
1983 +        try {
1984 +            es.submit((Runnable) null, Boolean.TRUE);
1985 +            shouldThrow();
1986 +        } catch (NullPointerException success) {}
1987 +        try {
1988 +            es.submit((Callable) null);
1989 +            shouldThrow();
1990 +        } catch (NullPointerException success) {}
1991 +
1992 +        if (! (e instanceof ScheduledExecutorService)) return;
1993 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1994 +        try {
1995 +            ses.schedule((Runnable) null,
1996 +                         randomTimeout(), randomTimeUnit());
1997 +            shouldThrow();
1998 +        } catch (NullPointerException success) {}
1999 +        try {
2000 +            ses.schedule((Callable) null,
2001 +                         randomTimeout(), randomTimeUnit());
2002 +            shouldThrow();
2003 +        } catch (NullPointerException success) {}
2004 +        try {
2005 +            ses.scheduleAtFixedRate((Runnable) null,
2006 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2007 +            shouldThrow();
2008 +        } catch (NullPointerException success) {}
2009 +        try {
2010 +            ses.scheduleWithFixedDelay((Runnable) null,
2011 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2012 +            shouldThrow();
2013 +        } catch (NullPointerException success) {}
2014 +    }
2015 +
2016 +    void setRejectedExecutionHandler(
2017 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2018 +        p.setRejectedExecutionHandler(handler);
2019 +        assertSame(handler, p.getRejectedExecutionHandler());
2020 +    }
2021 +
2022 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2023 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2024 +        final long savedTaskCount = p.getTaskCount();
2025 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2026 +        final int savedQueueSize = p.getQueue().size();
2027 +        final boolean stock = (p.getClass().getClassLoader() == null);
2028 +
2029 +        Runnable r = () -> {};
2030 +        Callable<Boolean> c = () -> Boolean.TRUE;
2031 +
2032 +        class Recorder implements RejectedExecutionHandler {
2033 +            public volatile Runnable r = null;
2034 +            public volatile ThreadPoolExecutor p = null;
2035 +            public void reset() { r = null; p = null; }
2036 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2037 +                assertNull(this.r);
2038 +                assertNull(this.p);
2039 +                this.r = r;
2040 +                this.p = p;
2041 +            }
2042 +        }
2043 +
2044 +        // check custom handler is invoked exactly once per task
2045 +        Recorder recorder = new Recorder();
2046 +        setRejectedExecutionHandler(p, recorder);
2047 +        for (int i = 2; i--> 0; ) {
2048 +            recorder.reset();
2049 +            p.execute(r);
2050 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2051 +                assertSame(r, recorder.r);
2052 +            assertSame(p, recorder.p);
2053 +
2054 +            recorder.reset();
2055 +            assertFalse(p.submit(r).isDone());
2056 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2057 +            assertSame(p, recorder.p);
2058 +
2059 +            recorder.reset();
2060 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2061 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2062 +            assertSame(p, recorder.p);
2063 +
2064 +            recorder.reset();
2065 +            assertFalse(p.submit(c).isDone());
2066 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2067 +            assertSame(p, recorder.p);
2068 +
2069 +            if (p instanceof ScheduledExecutorService) {
2070 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2071 +                ScheduledFuture<?> future;
2072 +
2073 +                recorder.reset();
2074 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2075 +                assertFalse(future.isDone());
2076 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2077 +                assertSame(p, recorder.p);
2078 +
2079 +                recorder.reset();
2080 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2081 +                assertFalse(future.isDone());
2082 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2083 +                assertSame(p, recorder.p);
2084 +
2085 +                recorder.reset();
2086 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2087 +                assertFalse(future.isDone());
2088 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2089 +                assertSame(p, recorder.p);
2090 +
2091 +                recorder.reset();
2092 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2093 +                assertFalse(future.isDone());
2094 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2095 +                assertSame(p, recorder.p);
2096 +            }
2097 +        }
2098 +
2099 +        // Checking our custom handler above should be sufficient, but
2100 +        // we add some integration tests of standard handlers.
2101 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2102 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2103 +
2104 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2105 +        try {
2106 +            p.execute(setThread);
2107 +            shouldThrow();
2108 +        } catch (RejectedExecutionException success) {}
2109 +        assertNull(thread.get());
2110 +
2111 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2112 +        p.execute(setThread);
2113 +        assertNull(thread.get());
2114 +
2115 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2116 +        p.execute(setThread);
2117 +        if (p.isShutdown())
2118 +            assertNull(thread.get());
2119 +        else
2120 +            assertSame(Thread.currentThread(), thread.get());
2121 +
2122 +        setRejectedExecutionHandler(p, savedHandler);
2123 +
2124 +        // check that pool was not perturbed by handlers
2125 +        assertEquals(savedTaskCount, p.getTaskCount());
2126 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2127 +        assertEquals(savedQueueSize, p.getQueue().size());
2128 +    }
2129 +
2130 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2131 +        assertEquals(x, y);
2132 +        assertEquals(y, x);
2133 +        assertEquals(x.isEmpty(), y.isEmpty());
2134 +        assertEquals(x.size(), y.size());
2135 +        if (x instanceof List) {
2136 +            assertEquals(x.toString(), y.toString());
2137 +        }
2138 +        if (x instanceof List || x instanceof Set) {
2139 +            assertEquals(x.hashCode(), y.hashCode());
2140 +        }
2141 +        if (x instanceof List || x instanceof Deque) {
2142 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2143 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2144 +                                     y.toArray(new Object[0])));
2145 +        }
2146 +    }
2147 +
2148 +    /**
2149 +     * A weaker form of assertCollectionsEquals which does not insist
2150 +     * that the two collections satisfy Object#equals(Object), since
2151 +     * they may use identity semantics as Deques do.
2152 +     */
2153 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2154 +        if (x instanceof List || x instanceof Set)
2155 +            assertCollectionsEquals(x, y);
2156 +        else {
2157 +            assertEquals(x.isEmpty(), y.isEmpty());
2158 +            assertEquals(x.size(), y.size());
2159 +            assertEquals(new HashSet(x), new HashSet(y));
2160 +            if (x instanceof Deque) {
2161 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2162 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2163 +                                         y.toArray(new Object[0])));
2164 +            }
2165 +        }
2166 +    }
2167   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines