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.155 by jsr166, Sat Oct 3 19:59:49 2015 UTC vs.
Revision 1.270 by jsr166, Sun Sep 29 20:18:35 2019 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
8   */
9  
10 + /*
11 + * @test
12 + * @summary JSR-166 tck tests, in a number of variations.
13 + *          The first is the conformance testing variant,
14 + *          while others also test implementation details.
15 + * @build *
16 + * @modules java.management
17 + * @run junit/othervm/timeout=1000 JSR166TestCase
18 + * @run junit/othervm/timeout=1000
19 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 + *      --add-opens java.base/java.lang=ALL-UNNAMED
21 + *      -Djsr166.testImplementationDetails=true
22 + *      JSR166TestCase
23 + * @run junit/othervm/timeout=1000
24 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 + *      --add-opens java.base/java.lang=ALL-UNNAMED
26 + *      -Djsr166.testImplementationDetails=true
27 + *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28 + *      JSR166TestCase
29 + * @run junit/othervm/timeout=1000
30 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 + *      --add-opens java.base/java.lang=ALL-UNNAMED
32 + *      -Djsr166.testImplementationDetails=true
33 + *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
34 + *      -Djava.util.secureRandomSeed=true
35 + *      JSR166TestCase
36 + * @run junit/othervm/timeout=1000/policy=tck.policy
37 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 + *      --add-opens java.base/java.lang=ALL-UNNAMED
39 + *      -Djsr166.testImplementationDetails=true
40 + *      JSR166TestCase
41 + */
42 +
43   import static java.util.concurrent.TimeUnit.MILLISECONDS;
44 + import static java.util.concurrent.TimeUnit.MINUTES;
45   import static java.util.concurrent.TimeUnit.NANOSECONDS;
46  
47   import java.io.ByteArrayInputStream;
# Line 14 | 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 28 | Line 64 | import java.security.ProtectionDomain;
64   import java.security.SecurityPermission;
65   import java.util.ArrayList;
66   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  
56 import junit.framework.AssertionFailedError;
106   import junit.framework.Test;
107   import junit.framework.TestCase;
108   import junit.framework.TestResult;
# Line 69 | 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 108 | Line 165 | import junit.framework.TestSuite;
165   * methods as there are exceptions the method can throw. Sometimes
166   * there are multiple tests per JSR166 method when the different
167   * "normal" behaviors differ significantly. And sometimes testcases
168 < * cover multiple methods when they cannot be tested in
112 < * isolation.
168 > * cover multiple methods when they cannot be tested in isolation.
169   *
170   * <li>The documentation style for testcases is to provide as javadoc
171   * a simple sentence or two describing the property that the testcase
# Line 172 | Line 228 | public class JSR166TestCase extends Test
228      private static final int suiteRuns =
229          Integer.getInteger("jsr166.suiteRuns", 1);
230  
231 +    /**
232 +     * Returns the value of the system property, or NaN if not defined.
233 +     */
234 +    private static float systemPropertyValue(String name) {
235 +        String floatString = System.getProperty(name);
236 +        if (floatString == null)
237 +            return Float.NaN;
238 +        try {
239 +            return Float.parseFloat(floatString);
240 +        } catch (NumberFormatException ex) {
241 +            throw new IllegalArgumentException(
242 +                String.format("Bad float value in system property %s=%s",
243 +                              name, floatString));
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:
253 +     * - the "jsr166.delay.factor" system property
254 +     * - the "test.timeout.factor" system property (as used by jtreg)
255 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
256 +     * - hard-coded fuzz factor when using a known slowpoke VM
257 +     */
258 +    private static final float delayFactor = delayFactor();
259 +
260 +    private static float delayFactor() {
261 +        float x;
262 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
263 +            return x;
264 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
265 +            return x;
266 +        String prop = System.getProperty("java.vm.version");
267 +        if (prop != null && prop.matches(".*debug.*"))
268 +            return 4.0f; // How much slower is fastdebug than product?!
269 +        return 1.0f;
270 +    }
271 +
272      public JSR166TestCase() { super(); }
273      public JSR166TestCase(String name) { super(name); }
274  
# Line 187 | Line 284 | public class JSR166TestCase extends Test
284          return (regex == null) ? null : Pattern.compile(regex);
285      }
286  
287 +    // Instrumentation to debug very rare, but very annoying hung test runs.
288 +    static volatile TestCase currentTestCase;
289 +    // static volatile int currentRun = 0;
290 +    static {
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 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; }
301 +                if (lastTestCase == currentTestCase) {
302 +                    System.err.printf(
303 +                        "Looks like we're stuck running test: %s%n",
304 +                        lastTestCase);
305 + //                     System.err.printf(
306 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
307 + //                         lastTestCase, currentRun, runsPerTest);
308 + //                     System.err.println("availableProcessors=" +
309 + //                         Runtime.getRuntime().availableProcessors());
310 + //                     System.err.printf("cpu model = %s%n", cpuModel());
311 +                    dumpTestThreads();
312 +                    // one stack dump is probably enough; more would be spam
313 +                    break;
314 +                }
315 +                lastTestCase = currentTestCase;
316 +            }}};
317 +        Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector");
318 +        thread.setDaemon(true);
319 +        thread.start();
320 +    }
321 +
322 + //     public static String cpuModel() {
323 + //         try {
324 + //             java.util.regex.Matcher matcher
325 + //               = Pattern.compile("model name\\s*: (.*)")
326 + //                 .matcher(new String(
327 + //                     java.nio.file.Files.readAllBytes(
328 + //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
329 + //             matcher.find();
330 + //             return matcher.group(1);
331 + //         } catch (Exception ex) { return null; }
332 + //     }
333 +
334      public void runBare() throws Throwable {
335 +        currentTestCase = this;
336          if (methodFilter == null
337              || methodFilter.matcher(toString()).find())
338              super.runBare();
# Line 195 | Line 340 | public class JSR166TestCase extends Test
340  
341      protected void runTest() throws Throwable {
342          for (int i = 0; i < runsPerTest; i++) {
343 +            // currentRun = i;
344              if (profileTests)
345                  runTestProfiled();
346              else
# Line 212 | 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 223 | Line 369 | public class JSR166TestCase extends Test
369          main(suite(), args);
370      }
371  
372 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
373 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
374 +        long runTime;
375 +        public void startTest(Test test) {}
376 +        protected void printHeader(long runTime) {
377 +            this.runTime = runTime; // defer printing for later
378 +        }
379 +        protected void printFooter(TestResult result) {
380 +            if (result.wasSuccessful()) {
381 +                getWriter().println("OK (" + result.runCount() + " tests)"
382 +                    + "  Time: " + elapsedTimeAsString(runTime));
383 +            } else {
384 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
385 +                super.printFooter(result);
386 +            }
387 +        }
388 +    }
389 +
390 +    /**
391 +     * Returns a TestRunner that doesn't bother with unnecessary
392 +     * fluff, like printing a "." for each test case.
393 +     */
394 +    static junit.textui.TestRunner newPithyTestRunner() {
395 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
396 +        runner.setPrinter(new PithyResultPrinter(System.out));
397 +        return runner;
398 +    }
399 +
400      /**
401       * Runs all unit tests in the given test suite.
402       * Actual behavior influenced by jsr166.* system properties.
# Line 234 | Line 408 | public class JSR166TestCase extends Test
408              System.setSecurityManager(new SecurityManager());
409          }
410          for (int i = 0; i < suiteRuns; i++) {
411 <            TestResult result = junit.textui.TestRunner.run(suite);
411 >            TestResult result = newPithyTestRunner().doRun(suite);
412              if (!result.wasSuccessful())
413                  System.exit(1);
414              System.gc();
# Line 260 | 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",
264 <                                                       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 286 | 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 318 | Line 491 | public class JSR166TestCase extends Test
491              AbstractQueuedLongSynchronizerTest.suite(),
492              ArrayBlockingQueueTest.suite(),
493              ArrayDequeTest.suite(),
494 +            ArrayListTest.suite(),
495              AtomicBooleanTest.suite(),
496              AtomicIntegerArrayTest.suite(),
497              AtomicIntegerFieldUpdaterTest.suite(),
# Line 340 | Line 514 | public class JSR166TestCase extends Test
514              CopyOnWriteArrayListTest.suite(),
515              CopyOnWriteArraySetTest.suite(),
516              CountDownLatchTest.suite(),
517 +            CountedCompleterTest.suite(),
518              CyclicBarrierTest.suite(),
519              DelayQueueTest.suite(),
520              EntryTest.suite(),
# Line 347 | 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 368 | Line 544 | public class JSR166TestCase extends Test
544              TreeMapTest.suite(),
545              TreeSetTest.suite(),
546              TreeSubMapTest.suite(),
547 <            TreeSubSetTest.suite());
547 >            TreeSubSetTest.suite(),
548 >            VectorTest.suite());
549  
550          // Java8+ test classes
551          if (atLeastJava8()) {
552              String[] java8TestClassNames = {
553 +                "ArrayDeque8Test",
554                  "Atomic8Test",
555                  "CompletableFutureTest",
556                  "ConcurrentHashMap8Test",
557 <                "CountedCompleterTest",
557 >                "CountedCompleter8Test",
558                  "DoubleAccumulatorTest",
559                  "DoubleAdderTest",
560                  "ForkJoinPool8Test",
561                  "ForkJoinTask8Test",
562 +                "HashMapTest",
563 +                "LinkedBlockingDeque8Test",
564 +                "LinkedBlockingQueue8Test",
565 +                "LinkedHashMapTest",
566                  "LongAccumulatorTest",
567                  "LongAdderTest",
568                  "SplittableRandomTest",
569                  "StampedLockTest",
570                  "SubmissionPublisherTest",
571                  "ThreadLocalRandom8Test",
572 +                "TimeUnit8Test",
573              };
574              addNamedTestClasses(suite, java8TestClassNames);
575          }
# Line 394 | Line 577 | public class JSR166TestCase extends Test
577          // Java9+ test classes
578          if (atLeastJava9()) {
579              String[] java9TestClassNames = {
580 <                // Currently empty, but expecting varhandle tests
580 >                "AtomicBoolean9Test",
581 >                "AtomicInteger9Test",
582 >                "AtomicIntegerArray9Test",
583 >                "AtomicLong9Test",
584 >                "AtomicLongArray9Test",
585 >                "AtomicReference9Test",
586 >                "AtomicReferenceArray9Test",
587 >                "ExecutorCompletionService9Test",
588 >                "ForkJoinPool9Test",
589              };
590              addNamedTestClasses(suite, java9TestClassNames);
591          }
# Line 405 | Line 596 | public class JSR166TestCase extends Test
596      /** Returns list of junit-style test method names in given class. */
597      public static ArrayList<String> testMethodNames(Class<?> testClass) {
598          Method[] methods = testClass.getDeclaredMethods();
599 <        ArrayList<String> names = new ArrayList<String>(methods.length);
599 >        ArrayList<String> names = new ArrayList<>(methods.length);
600          for (Method method : methods) {
601              if (method.getName().startsWith("test")
602                  && Modifier.isPublic(method.getModifiers())
# Line 432 | 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 449 | 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 471 | Line 662 | public class JSR166TestCase extends Test
662      public static long LONG_DELAY_MS;
663  
664      /**
665 <     * Returns the shortest timed delay. This could
666 <     * be reimplemented to use for example a Property.
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.
722 >     * http://openjdk.java.net/jtreg/command-help.html
723       */
724      protected long getShortDelay() {
725 <        return 50;
725 >        return (long) (50 * delayFactor);
726      }
727  
728      /**
# Line 486 | 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
740 +        = (long) (12.0 * Math.cbrt(delayFactor));
741 +
742      /**
743 <     * Returns a timeout in milliseconds to be used in tests that
744 <     * verify that operations block or time out.
743 >     * Returns a timeout in milliseconds to be used in tests that verify
744 >     * that operations block or time out.  We want this to be longer
745 >     * than the OS scheduling quantum, but not too long, so don't scale
746 >     * linearly with delayFactor; we use "crazy" cube root instead.
747       */
748 <    long timeoutMillis() {
749 <        return SHORT_DELAY_MS / 4;
748 >    static long timeoutMillis() {
749 >        return TIMEOUT_DELAY_MS;
750      }
751  
752      /**
# Line 509 | Line 762 | public class JSR166TestCase extends Test
762       * The first exception encountered if any threadAssertXXX method fails.
763       */
764      private final AtomicReference<Throwable> threadFailure
765 <        = new AtomicReference<Throwable>(null);
765 >        = new AtomicReference<>(null);
766  
767      /**
768       * Records an exception so that it can be rethrown later in the test
# Line 518 | Line 771 | public class JSR166TestCase extends Test
771       * the same test have no effect.
772       */
773      public void threadRecordFailure(Throwable t) {
774 <        threadDump();
775 <        threadFailure.compareAndSet(null, t);
774 >        System.err.println(t);
775 >        if (threadFailure.compareAndSet(null, t))
776 >            dumpTestThreads();
777      }
778  
779      public void setUp() {
# Line 529 | Line 783 | public class JSR166TestCase extends Test
783      void tearDownFail(String format, Object... args) {
784          String msg = toString() + ": " + String.format(format, args);
785          System.err.println(msg);
786 <        threadDump();
787 <        throw new AssertionFailedError(msg);
786 >        dumpTestThreads();
787 >        throw new AssertionError(msg);
788      }
789  
790      /**
# Line 551 | 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 =
556 <                    new AssertionFailedError(t.toString());
557 <                afe.initCause(t);
558 <                throw afe;
559 <            }
808 >            else
809 >                throw new AssertionError(t.toString(), t);
810          }
811  
812          if (Thread.interrupted())
# Line 566 | Line 816 | public class JSR166TestCase extends Test
816      }
817  
818      /**
819 <     * Finds missing try { ... } finally { joinPool(e); }
819 >     * Finds missing PoolCleaners
820       */
821      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
822          Thread[] survivors = new Thread[7];
# Line 590 | 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 676 | 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 704 | 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 714 | 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 =
719 <                new AssertionFailedError("unexpected exception: " + t);
720 <            afe.initCause(t);
721 <            throw afe;
722 <        }
967 >        else
968 >            throw new AssertionError("unexpected exception: " + t, t);
969      }
970  
971      /**
972       * Delays, via Thread.sleep, for the given millisecond delay, but
973       * if the sleep is shorter than specified, may re-sleep or yield
974 <     * until time elapses.
974 >     * until time elapses.  Ensures that the given time, as measured
975 >     * by System.nanoTime(), has elapsed.
976       */
977      static void delay(long millis) throws InterruptedException {
978 <        long startTime = System.nanoTime();
979 <        long ns = millis * 1000 * 1000;
980 <        for (;;) {
978 >        long nanos = millis * (1000 * 1000);
979 >        final long wakeupTime = System.nanoTime() + nanos;
980 >        do {
981              if (millis > 0L)
982                  Thread.sleep(millis);
983              else // too short to sleep
984                  Thread.yield();
985 <            long d = ns - (System.nanoTime() - startTime);
986 <            if (d > 0L)
987 <                millis = d / (1000 * 1000);
741 <            else
742 <                break;
743 <        }
985 >            nanos = wakeupTime - System.nanoTime();
986 >            millis = nanos / (1000 * 1000);
987 >        } while (nanos >= 0L);
988      }
989  
990      /**
991       * Allows use of try-with-resources with per-test thread pools.
992       */
993 <    static class PoolCloser<T extends ExecutorService>
994 <            implements AutoCloseable {
995 <        public final T pool;
752 <        public PoolCloser(T pool) { this.pool = pool; }
993 >    class PoolCleaner implements AutoCloseable {
994 >        private final ExecutorService pool;
995 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
996          public void close() { joinPool(pool); }
997      }
998  
999      /**
1000 +     * An extension of PoolCleaner that has an action to release the pool.
1001 +     */
1002 +    class PoolCleanerWithReleaser extends PoolCleaner {
1003 +        private final Runnable releaser;
1004 +        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
1005 +            super(pool);
1006 +            this.releaser = releaser;
1007 +        }
1008 +        public void close() {
1009 +            try {
1010 +                releaser.run();
1011 +            } finally {
1012 +                super.close();
1013 +            }
1014 +        }
1015 +    }
1016 +
1017 +    PoolCleaner cleaner(ExecutorService pool) {
1018 +        return new PoolCleaner(pool);
1019 +    }
1020 +
1021 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
1022 +        return new PoolCleanerWithReleaser(pool, releaser);
1023 +    }
1024 +
1025 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
1026 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
1027 +    }
1028 +
1029 +    Runnable releaser(final CountDownLatch latch) {
1030 +        return new Runnable() { public void run() {
1031 +            do { latch.countDown(); }
1032 +            while (latch.getCount() > 0);
1033 +        }};
1034 +    }
1035 +
1036 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1037 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
1038 +    }
1039 +
1040 +    Runnable releaser(final AtomicBoolean flag) {
1041 +        return new Runnable() { public void run() { flag.set(true); }};
1042 +    }
1043 +
1044 +    /**
1045       * Waits out termination of a thread pool or fails doing so.
1046       */
1047 <    static void joinPool(ExecutorService pool) {
1047 >    void joinPool(ExecutorService pool) {
1048          try {
1049              pool.shutdown();
1050 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
1051 <                fail("ExecutorService " + pool +
1052 <                     " did not terminate in a timely manner");
1050 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1051 >                try {
1052 >                    threadFail("ExecutorService " + pool +
1053 >                               " did not terminate in a timely manner");
1054 >                } finally {
1055 >                    // last resort, for the benefit of subsequent tests
1056 >                    pool.shutdownNow();
1057 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1058 >                }
1059 >            }
1060          } catch (SecurityException ok) {
1061              // Allowed in case test doesn't have privs
1062          } catch (InterruptedException fail) {
1063 <            fail("Unexpected InterruptedException");
1063 >            threadFail("Unexpected InterruptedException");
1064          }
1065      }
1066  
1067 <    /** Like Runnable, but with the freedom to throw anything */
1067 >    /**
1068 >     * Like Runnable, but with the freedom to throw anything.
1069 >     * junit folks had the same idea:
1070 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1071 >     */
1072      interface Action { public void run() throws Throwable; }
1073  
1074      /**
# Line 778 | Line 1077 | public class JSR166TestCase extends Test
1077       * necessarily individually slow because they must block.
1078       */
1079      void testInParallel(Action ... actions) {
1080 <        try (PoolCloser<ExecutorService> poolCloser
1081 <             = new PoolCloser<>(Executors.newCachedThreadPool())) {
783 <            ExecutorService pool = poolCloser.pool;
1080 >        ExecutorService pool = Executors.newCachedThreadPool();
1081 >        try (PoolCleaner cleaner = cleaner(pool)) {
1082              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1083              for (final Action action : actions)
1084                  futures.add(pool.submit(new CheckedRunnable() {
# Line 796 | 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 all stack traces, as jstack does.
1131 >     * A debugging tool to print stack traces of most threads, as jstack does.
1132       * Uninteresting threads are filtered out.
1133       */
1134 <    static void threadDump() {
1135 <        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1136 <        System.err.println("------ stacktrace dump start ------");
1137 <        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1138 <            String name = info.getThreadName();
1139 <            if ("Signal Dispatcher".equals(name))
1140 <                continue;
1141 <            if ("Reference Handler".equals(name)
811 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
812 <                continue;
813 <            if ("Finalizer".equals(name)
814 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
815 <                continue;
816 <            System.err.print(info);
1134 >    static void dumpTestThreads() {
1135 >        SecurityManager sm = System.getSecurityManager();
1136 >        if (sm != null) {
1137 >            try {
1138 >                System.setSecurityManager(null);
1139 >            } catch (SecurityException giveUp) {
1140 >                return;
1141 >            }
1142          }
1143 +
1144 +        System.err.println("------ stacktrace dump start ------");
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 ------");
819    }
1149  
1150 <    /**
822 <     * Checks that thread does not terminate within the default
823 <     * millisecond delay of {@code timeoutMillis()}.
824 <     */
825 <    void assertThreadStaysAlive(Thread thread) {
826 <        assertThreadStaysAlive(thread, timeoutMillis());
1150 >        if (sm != null) System.setSecurityManager(sm);
1151      }
1152  
1153      /**
1154 <     * Checks that thread does not terminate within the given millisecond delay.
1154 >     * Checks that thread eventually enters the expected blocked thread state.
1155       */
1156 <    void assertThreadStaysAlive(Thread thread, long millis) {
1157 <        try {
1158 <            // No need to optimize the failing case via Thread.join.
1159 <            delay(millis);
1160 <            assertTrue(thread.isAlive());
1161 <        } catch (InterruptedException fail) {
1162 <            fail("Unexpected InterruptedException");
1156 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1157 >        // always sleep at least 1 ms, with high probability avoiding
1158 >        // transitory states
1159 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1160 >            try { delay(1); }
1161 >            catch (InterruptedException fail) {
1162 >                throw new AssertionError("Unexpected InterruptedException", fail);
1163 >            }
1164 >            Thread.State s = thread.getState();
1165 >            if (s == expected)
1166 >                return;
1167 >            else if (s == Thread.State.TERMINATED)
1168 >                fail("Unexpected thread termination");
1169          }
1170 +        fail("timed out waiting for thread to enter thread state " + expected);
1171      }
1172  
1173      /**
1174 <     * Checks that the threads do not terminate within the default
844 <     * millisecond delay of {@code timeoutMillis()}.
1174 >     * Returns the thread's blocker's class name, if any, else null.
1175       */
1176 <    void assertThreadsStayAlive(Thread... threads) {
1177 <        assertThreadsStayAlive(timeoutMillis(), threads);
1178 <    }
1179 <
1180 <    /**
1181 <     * Checks that the threads do not terminate within the given millisecond delay.
852 <     */
853 <    void assertThreadsStayAlive(long millis, Thread... threads) {
854 <        try {
855 <            // No need to optimize the failing case via Thread.join.
856 <            delay(millis);
857 <            for (Thread thread : threads)
858 <                assertTrue(thread.isAlive());
859 <        } catch (InterruptedException fail) {
860 <            fail("Unexpected InterruptedException");
861 <        }
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 899 | Line 1219 | public class JSR166TestCase extends Test
1219      }
1220  
1221      /**
1222 +     * The maximum number of consecutive spurious wakeups we should
1223 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1224 +     */
1225 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1226 +
1227 +    /**
1228       * The number of elements to place in collections, arrays, etc.
1229       */
1230      public static final int SIZE = 20;
# Line 1002 | Line 1328 | public class JSR166TestCase extends Test
1328          }
1329          public void refresh() {}
1330          public String toString() {
1331 <            List<Permission> ps = new ArrayList<Permission>();
1331 >            List<Permission> ps = new ArrayList<>();
1332              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1333                  ps.add(e.nextElement());
1334              return "AdjustablePolicy with permissions " + ps;
# Line 1030 | Line 1356 | public class JSR166TestCase extends Test
1356  
1357      /**
1358       * Sleeps until the given time has elapsed.
1359 <     * Throws AssertionFailedError if interrupted.
1359 >     * Throws AssertionError if interrupted.
1360       */
1361 <    void sleep(long millis) {
1361 >    static void sleep(long millis) {
1362          try {
1363              delay(millis);
1364          } catch (InterruptedException fail) {
1365 <            AssertionFailedError afe =
1040 <                new AssertionFailedError("Unexpected InterruptedException");
1041 <            afe.initCause(fail);
1042 <            throw afe;
1365 >            throw new AssertionError("Unexpected InterruptedException", fail);
1366          }
1367      }
1368  
1369      /**
1370       * Spin-waits up to the specified number of milliseconds for the given
1371       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1372 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1373       */
1374 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1375 <        long startTime = System.nanoTime();
1376 <        for (;;) {
1377 <            Thread.State s = thread.getState();
1378 <            if (s == Thread.State.BLOCKED ||
1379 <                s == Thread.State.WAITING ||
1380 <                s == Thread.State.TIMED_WAITING)
1381 <                return;
1382 <            else if (s == Thread.State.TERMINATED)
1374 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1375 >                                       Callable<Boolean> waitingForGodot) {
1376 >        for (long startTime = 0L;;) {
1377 >            switch (thread.getState()) {
1378 >            default: break;
1379 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1380 >                try {
1381 >                    if (waitingForGodot == null || waitingForGodot.call())
1382 >                        return;
1383 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1384 >                break;
1385 >            case TERMINATED:
1386                  fail("Unexpected thread termination");
1387 +            }
1388 +
1389 +            if (startTime == 0L)
1390 +                startTime = System.nanoTime();
1391              else if (millisElapsedSince(startTime) > timeoutMillis) {
1392 <                threadAssertTrue(thread.isAlive());
1393 <                return;
1392 >                assertTrue(thread.isAlive());
1393 >                if (waitingForGodot == null
1394 >                    || thread.getState() == Thread.State.RUNNABLE)
1395 >                    fail("timed out waiting for thread to enter wait state");
1396 >                else
1397 >                    fail("timed out waiting for condition, thread state="
1398 >                         + thread.getState());
1399              }
1400              Thread.yield();
1401          }
1402      }
1403  
1404      /**
1405 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1406 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1405 >     * Spin-waits up to the specified number of milliseconds for the given
1406 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1407 >     */
1408 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1409 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1410 >    }
1411 >
1412 >    /**
1413 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1414 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1415       */
1416      void waitForThreadToEnterWaitState(Thread thread) {
1417 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1417 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1418 >    }
1419 >
1420 >    /**
1421 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1422 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1423 >     * and additionally satisfy the given condition.
1424 >     */
1425 >    void waitForThreadToEnterWaitState(Thread thread,
1426 >                                       Callable<Boolean> waitingForGodot) {
1427 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1428 >    }
1429 >
1430 >    /**
1431 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1432 >     * be interrupted.  Clears the interrupt status before returning.
1433 >     */
1434 >    void awaitInterrupted() {
1435 >        for (long startTime = 0L; !Thread.interrupted(); ) {
1436 >            if (startTime == 0L)
1437 >                startTime = System.nanoTime();
1438 >            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1439 >                fail("timed out waiting for thread interrupt");
1440 >            Thread.yield();
1441 >        }
1442      }
1443  
1444      /**
# Line 1082 | Line 1450 | public class JSR166TestCase extends Test
1450          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1451      }
1452  
1085 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1086 //         long startTime = System.nanoTime();
1087 //         try {
1088 //             r.run();
1089 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1090 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1091 //             throw new AssertionFailedError("did not return promptly");
1092 //     }
1093
1094 //     void assertTerminatesPromptly(Runnable r) {
1095 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1096 //     }
1097
1453      /**
1454       * Checks that timed f.get() returns the expected value, and does not
1455       * wait for the timeout to elapse before returning.
1456       */
1457      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1458          long startTime = System.nanoTime();
1459 +        T actual = null;
1460          try {
1461 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1461 >            actual = f.get(timeoutMillis, MILLISECONDS);
1462          } catch (Throwable fail) { threadUnexpectedException(fail); }
1463 +        assertEquals(expectedValue, actual);
1464          if (millisElapsedSince(startTime) > timeoutMillis/2)
1465 <            throw new AssertionFailedError("timed get did not return promptly");
1465 >            throw new AssertionError("timed get did not return promptly");
1466      }
1467  
1468      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1123 | Line 1480 | public class JSR166TestCase extends Test
1480      }
1481  
1482      /**
1483 +     * Returns a new started daemon Thread running the given action,
1484 +     * wrapped in a CheckedRunnable.
1485 +     */
1486 +    Thread newStartedThread(Action action) {
1487 +        return newStartedThread(checkedRunnable(action));
1488 +    }
1489 +
1490 +    /**
1491       * Waits for the specified time (in milliseconds) for the thread
1492       * to terminate (using {@link Thread#join(long)}), else interrupts
1493       * the thread (in the hope that it may terminate later) and fails.
1494       */
1495 <    void awaitTermination(Thread t, long timeoutMillis) {
1495 >    void awaitTermination(Thread thread, long timeoutMillis) {
1496          try {
1497 <            t.join(timeoutMillis);
1497 >            thread.join(timeoutMillis);
1498          } catch (InterruptedException fail) {
1499              threadUnexpectedException(fail);
1500 <        } finally {
1501 <            if (t.getState() != Thread.State.TERMINATED) {
1502 <                t.interrupt();
1503 <                fail("Test timed out");
1500 >        }
1501 >        if (thread.getState() != Thread.State.TERMINATED) {
1502 >            String detail = String.format(
1503 >                    "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1504 >                    thread, thread.getState());
1505 >            try {
1506 >                threadFail(detail);
1507 >            } finally {
1508 >                // Interrupt thread __after__ having reported its stack trace
1509 >                thread.interrupt();
1510              }
1511          }
1512      }
# Line 1163 | Line 1534 | public class JSR166TestCase extends Test
1534          }
1535      }
1536  
1537 <    public abstract class RunnableShouldThrow implements Runnable {
1538 <        protected abstract void realRun() throws Throwable;
1539 <
1540 <        final Class<?> exceptionClass;
1541 <
1171 <        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1172 <            this.exceptionClass = exceptionClass;
1173 <        }
1174 <
1175 <        public final void run() {
1176 <            try {
1177 <                realRun();
1178 <                threadShouldThrow(exceptionClass.getSimpleName());
1179 <            } catch (Throwable t) {
1180 <                if (! exceptionClass.isInstance(t))
1181 <                    threadUnexpectedException(t);
1182 <            }
1183 <        }
1537 >    Runnable checkedRunnable(Action action) {
1538 >        return new CheckedRunnable() {
1539 >            public void realRun() throws Throwable {
1540 >                action.run();
1541 >            }};
1542      }
1543  
1544      public abstract class ThreadShouldThrow extends Thread {
# Line 1195 | Line 1553 | public class JSR166TestCase extends Test
1553          public final void run() {
1554              try {
1555                  realRun();
1198                threadShouldThrow(exceptionClass.getSimpleName());
1556              } catch (Throwable t) {
1557                  if (! exceptionClass.isInstance(t))
1558                      threadUnexpectedException(t);
1559 +                return;
1560              }
1561 +            threadShouldThrow(exceptionClass.getSimpleName());
1562          }
1563      }
1564  
# Line 1209 | Line 1568 | public class JSR166TestCase extends Test
1568          public final void run() {
1569              try {
1570                  realRun();
1212                threadShouldThrow("InterruptedException");
1571              } catch (InterruptedException success) {
1572                  threadAssertFalse(Thread.interrupted());
1573 +                return;
1574              } catch (Throwable fail) {
1575                  threadUnexpectedException(fail);
1576              }
1577 +            threadShouldThrow("InterruptedException");
1578          }
1579      }
1580  
# Line 1226 | Line 1586 | public class JSR166TestCase extends Test
1586                  return realCall();
1587              } catch (Throwable fail) {
1588                  threadUnexpectedException(fail);
1229                return null;
1589              }
1590 <        }
1232 <    }
1233 <
1234 <    public abstract class CheckedInterruptedCallable<T>
1235 <        implements Callable<T> {
1236 <        protected abstract T realCall() throws Throwable;
1237 <
1238 <        public final T call() {
1239 <            try {
1240 <                T result = realCall();
1241 <                threadShouldThrow("InterruptedException");
1242 <                return result;
1243 <            } catch (InterruptedException success) {
1244 <                threadAssertFalse(Thread.interrupted());
1245 <            } catch (Throwable fail) {
1246 <                threadUnexpectedException(fail);
1247 <            }
1248 <            return null;
1590 >            throw new AssertionError("unreached");
1591          }
1592      }
1593  
# Line 1283 | Line 1625 | public class JSR166TestCase extends Test
1625              }};
1626      }
1627  
1628 <    public Runnable awaiter(final CountDownLatch latch) {
1629 <        return new CheckedRunnable() {
1630 <            public void realRun() throws InterruptedException {
1631 <                await(latch);
1632 <            }};
1628 >    class LatchAwaiter extends CheckedRunnable {
1629 >        static final int NEW = 0;
1630 >        static final int RUNNING = 1;
1631 >        static final int DONE = 2;
1632 >        final CountDownLatch latch;
1633 >        int state = NEW;
1634 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1635 >        public void realRun() throws InterruptedException {
1636 >            state = 1;
1637 >            await(latch);
1638 >            state = 2;
1639 >        }
1640      }
1641  
1642 <    public void await(CountDownLatch latch) {
1642 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1643 >        return new LatchAwaiter(latch);
1644 >    }
1645 >
1646 >    public void await(CountDownLatch latch, long timeoutMillis) {
1647 >        boolean timedOut = false;
1648          try {
1649 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1649 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1650          } catch (Throwable fail) {
1651              threadUnexpectedException(fail);
1652          }
1653 +        if (timedOut)
1654 +            fail("timed out waiting for CountDownLatch for "
1655 +                 + (timeoutMillis/1000) + " sec");
1656 +    }
1657 +
1658 +    public void await(CountDownLatch latch) {
1659 +        await(latch, LONG_DELAY_MS);
1660      }
1661  
1662      public void await(Semaphore semaphore) {
1663 +        boolean timedOut = false;
1664          try {
1665 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1665 >            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1666 >        } catch (Throwable fail) {
1667 >            threadUnexpectedException(fail);
1668 >        }
1669 >        if (timedOut)
1670 >            fail("timed out waiting for Semaphore for "
1671 >                 + (LONG_DELAY_MS/1000) + " sec");
1672 >    }
1673 >
1674 >    public void await(CyclicBarrier barrier) {
1675 >        try {
1676 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1677          } catch (Throwable fail) {
1678              threadUnexpectedException(fail);
1679          }
# Line 1320 | Line 1693 | public class JSR166TestCase extends Test
1693   //         long startTime = System.nanoTime();
1694   //         while (!flag.get()) {
1695   //             if (millisElapsedSince(startTime) > timeoutMillis)
1696 < //                 throw new AssertionFailedError("timed out");
1696 > //                 throw new AssertionError("timed out");
1697   //             Thread.yield();
1698   //         }
1699   //     }
# Line 1329 | Line 1702 | public class JSR166TestCase extends Test
1702          public String call() { throw new NullPointerException(); }
1703      }
1704  
1332    public static class CallableOne implements Callable<Integer> {
1333        public Integer call() { return one; }
1334    }
1335
1336    public class ShortRunnable extends CheckedRunnable {
1337        protected void realRun() throws Throwable {
1338            delay(SHORT_DELAY_MS);
1339        }
1340    }
1341
1342    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1343        protected void realRun() throws InterruptedException {
1344            delay(SHORT_DELAY_MS);
1345        }
1346    }
1347
1348    public class SmallRunnable extends CheckedRunnable {
1349        protected void realRun() throws Throwable {
1350            delay(SMALL_DELAY_MS);
1351        }
1352    }
1353
1354    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1355        protected void realRun() {
1356            try {
1357                delay(SMALL_DELAY_MS);
1358            } catch (InterruptedException ok) {}
1359        }
1360    }
1361
1362    public class SmallCallable extends CheckedCallable {
1363        protected Object realCall() throws InterruptedException {
1364            delay(SMALL_DELAY_MS);
1365            return Boolean.TRUE;
1366        }
1367    }
1368
1369    public class MediumRunnable extends CheckedRunnable {
1370        protected void realRun() throws Throwable {
1371            delay(MEDIUM_DELAY_MS);
1372        }
1373    }
1374
1375    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1376        protected void realRun() throws InterruptedException {
1377            delay(MEDIUM_DELAY_MS);
1378        }
1379    }
1380
1705      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1706          return new CheckedRunnable() {
1707              protected void realRun() {
# Line 1387 | Line 1711 | public class JSR166TestCase extends Test
1711              }};
1712      }
1713  
1390    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1391        protected void realRun() {
1392            try {
1393                delay(MEDIUM_DELAY_MS);
1394            } catch (InterruptedException ok) {}
1395        }
1396    }
1397
1398    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1399        protected void realRun() {
1400            try {
1401                delay(LONG_DELAY_MS);
1402            } catch (InterruptedException ok) {}
1403        }
1404    }
1405
1714      /**
1715       * For use as ThreadFactory in constructors
1716       */
# Line 1416 | Line 1724 | public class JSR166TestCase extends Test
1724          boolean isDone();
1725      }
1726  
1419    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1420        return new TrackedRunnable() {
1421                private volatile boolean done = false;
1422                public boolean isDone() { return done; }
1423                public void run() {
1424                    try {
1425                        delay(timeoutMillis);
1426                        done = true;
1427                    } catch (InterruptedException ok) {}
1428                }
1429            };
1430    }
1431
1432    public static class TrackedShortRunnable implements Runnable {
1433        public volatile boolean done = false;
1434        public void run() {
1435            try {
1436                delay(SHORT_DELAY_MS);
1437                done = true;
1438            } catch (InterruptedException ok) {}
1439        }
1440    }
1441
1442    public static class TrackedSmallRunnable implements Runnable {
1443        public volatile boolean done = false;
1444        public void run() {
1445            try {
1446                delay(SMALL_DELAY_MS);
1447                done = true;
1448            } catch (InterruptedException ok) {}
1449        }
1450    }
1451
1452    public static class TrackedMediumRunnable implements Runnable {
1453        public volatile boolean done = false;
1454        public void run() {
1455            try {
1456                delay(MEDIUM_DELAY_MS);
1457                done = true;
1458            } catch (InterruptedException ok) {}
1459        }
1460    }
1461
1462    public static class TrackedLongRunnable implements Runnable {
1463        public volatile boolean done = false;
1464        public void run() {
1465            try {
1466                delay(LONG_DELAY_MS);
1467                done = true;
1468            } catch (InterruptedException ok) {}
1469        }
1470    }
1471
1727      public static class TrackedNoOpRunnable implements Runnable {
1728          public volatile boolean done = false;
1729          public void run() {
# Line 1476 | Line 1731 | public class JSR166TestCase extends Test
1731          }
1732      }
1733  
1479    public static class TrackedCallable implements Callable {
1480        public volatile boolean done = false;
1481        public Object call() {
1482            try {
1483                delay(SMALL_DELAY_MS);
1484                done = true;
1485            } catch (InterruptedException ok) {}
1486            return Boolean.TRUE;
1487        }
1488    }
1489
1734      /**
1735       * Analog of CheckedRunnable for RecursiveAction
1736       */
# Line 1513 | Line 1757 | public class JSR166TestCase extends Test
1757                  return realCompute();
1758              } catch (Throwable fail) {
1759                  threadUnexpectedException(fail);
1516                return null;
1760              }
1761 +            throw new AssertionError("unreached");
1762          }
1763      }
1764  
# Line 1528 | Line 1772 | public class JSR166TestCase extends Test
1772  
1773      /**
1774       * A CyclicBarrier that uses timed await and fails with
1775 <     * AssertionFailedErrors instead of throwing checked exceptions.
1775 >     * AssertionErrors instead of throwing checked exceptions.
1776       */
1777 <    public class CheckedBarrier extends CyclicBarrier {
1777 >    public static class CheckedBarrier extends CyclicBarrier {
1778          public CheckedBarrier(int parties) { super(parties); }
1779  
1780          public int await() {
1781              try {
1782 <                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1782 >                return super.await(LONGER_DELAY_MS, MILLISECONDS);
1783              } catch (TimeoutException timedOut) {
1784 <                throw new AssertionFailedError("timed out");
1784 >                throw new AssertionError("timed out");
1785              } catch (Exception fail) {
1786 <                AssertionFailedError afe =
1543 <                    new AssertionFailedError("Unexpected exception: " + fail);
1544 <                afe.initCause(fail);
1545 <                throw afe;
1786 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1787              }
1788          }
1789      }
# Line 1553 | Line 1794 | public class JSR166TestCase extends Test
1794              assertEquals(0, q.size());
1795              assertNull(q.peek());
1796              assertNull(q.poll());
1797 <            assertNull(q.poll(0, MILLISECONDS));
1797 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1798              assertEquals(q.toString(), "[]");
1799              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1800              assertFalse(q.iterator().hasNext());
# Line 1594 | Line 1835 | public class JSR166TestCase extends Test
1835          }
1836      }
1837  
1838 +    void assertImmutable(Object o) {
1839 +        if (o instanceof Collection) {
1840 +            assertThrows(
1841 +                UnsupportedOperationException.class,
1842 +                () -> ((Collection) o).add(null));
1843 +        }
1844 +    }
1845 +
1846      @SuppressWarnings("unchecked")
1847      <T> T serialClone(T o) {
1848 +        T clone = null;
1849          try {
1850              ObjectInputStream ois = new ObjectInputStream
1851                  (new ByteArrayInputStream(serialBytes(o)));
1852 <            T clone = (T) ois.readObject();
1603 <            assertSame(o.getClass(), clone.getClass());
1604 <            return clone;
1852 >            clone = (T) ois.readObject();
1853          } catch (Throwable fail) {
1854              threadUnexpectedException(fail);
1855 +        }
1856 +        if (o == clone) assertImmutable(o);
1857 +        else assertSame(o.getClass(), clone.getClass());
1858 +        return clone;
1859 +    }
1860 +
1861 +    /**
1862 +     * A version of serialClone that leaves error handling (for
1863 +     * e.g. NotSerializableException) up to the caller.
1864 +     */
1865 +    @SuppressWarnings("unchecked")
1866 +    <T> T serialClonePossiblyFailing(T o)
1867 +        throws ReflectiveOperationException, java.io.IOException {
1868 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1869 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1870 +        oos.writeObject(o);
1871 +        oos.flush();
1872 +        oos.close();
1873 +        ObjectInputStream ois = new ObjectInputStream
1874 +            (new ByteArrayInputStream(bos.toByteArray()));
1875 +        T clone = (T) ois.readObject();
1876 +        if (o == clone) assertImmutable(o);
1877 +        else assertSame(o.getClass(), clone.getClass());
1878 +        return clone;
1879 +    }
1880 +
1881 +    /**
1882 +     * If o implements Cloneable and has a public clone method,
1883 +     * returns a clone of o, else null.
1884 +     */
1885 +    @SuppressWarnings("unchecked")
1886 +    <T> T cloneableClone(T o) {
1887 +        if (!(o instanceof Cloneable)) return null;
1888 +        final T clone;
1889 +        try {
1890 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1891 +        } catch (NoSuchMethodException ok) {
1892              return null;
1893 +        } catch (ReflectiveOperationException unexpected) {
1894 +            throw new Error(unexpected);
1895          }
1896 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1897 +        assertSame(o.getClass(), clone.getClass());
1898 +        return clone;
1899      }
1900  
1901      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1902 <                             Runnable... throwingActions) {
1903 <        for (Runnable throwingAction : throwingActions) {
1902 >                             Action... throwingActions) {
1903 >        for (Action throwingAction : throwingActions) {
1904              boolean threw = false;
1905              try { throwingAction.run(); }
1906              catch (Throwable t) {
1907                  threw = true;
1908 <                if (!expectedExceptionClass.isInstance(t)) {
1909 <                    AssertionFailedError afe =
1910 <                        new AssertionFailedError
1911 <                        ("Expected " + expectedExceptionClass.getName() +
1912 <                         ", got " + t.getClass().getName());
1623 <                    afe.initCause(t);
1624 <                    threadUnexpectedException(afe);
1625 <                }
1908 >                if (!expectedExceptionClass.isInstance(t))
1909 >                    throw new AssertionError(
1910 >                            "Expected " + expectedExceptionClass.getName() +
1911 >                            ", got " + t.getClass().getName(),
1912 >                            t);
1913              }
1914              if (!threw)
1915                  shouldThrow(expectedExceptionClass.getName());
# Line 1636 | Line 1923 | public class JSR166TestCase extends Test
1923          } catch (NoSuchElementException success) {}
1924          assertFalse(it.hasNext());
1925      }
1926 +
1927 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1928 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1929 +    }
1930 +
1931 +    public Runnable runnableThrowing(final RuntimeException ex) {
1932 +        return new Runnable() { public void run() { throw ex; }};
1933 +    }
1934 +
1935 +    /** A reusable thread pool to be shared by tests. */
1936 +    static final ExecutorService cachedThreadPool =
1937 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1938 +                               1000L, MILLISECONDS,
1939 +                               new SynchronousQueue<Runnable>());
1940 +
1941 +    static <T> void shuffle(T[] array) {
1942 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1943 +    }
1944 +
1945 +    /**
1946 +     * Returns the same String as would be returned by {@link
1947 +     * Object#toString}, whether or not the given object's class
1948 +     * overrides toString().
1949 +     *
1950 +     * @see System#identityHashCode
1951 +     */
1952 +    static String identityString(Object x) {
1953 +        return x.getClass().getName()
1954 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1955 +    }
1956 +
1957 +    // --- Shared assertions for Executor tests ---
1958 +
1959 +    /**
1960 +     * Returns maximum number of tasks that can be submitted to given
1961 +     * pool (with bounded queue) before saturation (when submission
1962 +     * throws RejectedExecutionException).
1963 +     */
1964 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1965 +        BlockingQueue<Runnable> q = pool.getQueue();
1966 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1967 +    }
1968 +
1969 +    @SuppressWarnings("FutureReturnValueIgnored")
1970 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1971 +        try {
1972 +            e.execute((Runnable) null);
1973 +            shouldThrow();
1974 +        } catch (NullPointerException success) {}
1975 +
1976 +        if (! (e instanceof ExecutorService)) return;
1977 +        ExecutorService es = (ExecutorService) e;
1978 +        try {
1979 +            es.submit((Runnable) null);
1980 +            shouldThrow();
1981 +        } catch (NullPointerException success) {}
1982 +        try {
1983 +            es.submit((Runnable) null, Boolean.TRUE);
1984 +            shouldThrow();
1985 +        } catch (NullPointerException success) {}
1986 +        try {
1987 +            es.submit((Callable) null);
1988 +            shouldThrow();
1989 +        } catch (NullPointerException success) {}
1990 +
1991 +        if (! (e instanceof ScheduledExecutorService)) return;
1992 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1993 +        try {
1994 +            ses.schedule((Runnable) null,
1995 +                         randomTimeout(), randomTimeUnit());
1996 +            shouldThrow();
1997 +        } catch (NullPointerException success) {}
1998 +        try {
1999 +            ses.schedule((Callable) null,
2000 +                         randomTimeout(), randomTimeUnit());
2001 +            shouldThrow();
2002 +        } catch (NullPointerException success) {}
2003 +        try {
2004 +            ses.scheduleAtFixedRate((Runnable) null,
2005 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2006 +            shouldThrow();
2007 +        } catch (NullPointerException success) {}
2008 +        try {
2009 +            ses.scheduleWithFixedDelay((Runnable) null,
2010 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2011 +            shouldThrow();
2012 +        } catch (NullPointerException success) {}
2013 +    }
2014 +
2015 +    void setRejectedExecutionHandler(
2016 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2017 +        p.setRejectedExecutionHandler(handler);
2018 +        assertSame(handler, p.getRejectedExecutionHandler());
2019 +    }
2020 +
2021 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2022 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2023 +        final long savedTaskCount = p.getTaskCount();
2024 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2025 +        final int savedQueueSize = p.getQueue().size();
2026 +        final boolean stock = (p.getClass().getClassLoader() == null);
2027 +
2028 +        Runnable r = () -> {};
2029 +        Callable<Boolean> c = () -> Boolean.TRUE;
2030 +
2031 +        class Recorder implements RejectedExecutionHandler {
2032 +            public volatile Runnable r = null;
2033 +            public volatile ThreadPoolExecutor p = null;
2034 +            public void reset() { r = null; p = null; }
2035 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2036 +                assertNull(this.r);
2037 +                assertNull(this.p);
2038 +                this.r = r;
2039 +                this.p = p;
2040 +            }
2041 +        }
2042 +
2043 +        // check custom handler is invoked exactly once per task
2044 +        Recorder recorder = new Recorder();
2045 +        setRejectedExecutionHandler(p, recorder);
2046 +        for (int i = 2; i--> 0; ) {
2047 +            recorder.reset();
2048 +            p.execute(r);
2049 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2050 +                assertSame(r, recorder.r);
2051 +            assertSame(p, recorder.p);
2052 +
2053 +            recorder.reset();
2054 +            assertFalse(p.submit(r).isDone());
2055 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2056 +            assertSame(p, recorder.p);
2057 +
2058 +            recorder.reset();
2059 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2060 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2061 +            assertSame(p, recorder.p);
2062 +
2063 +            recorder.reset();
2064 +            assertFalse(p.submit(c).isDone());
2065 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2066 +            assertSame(p, recorder.p);
2067 +
2068 +            if (p instanceof ScheduledExecutorService) {
2069 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2070 +                ScheduledFuture<?> future;
2071 +
2072 +                recorder.reset();
2073 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2074 +                assertFalse(future.isDone());
2075 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2076 +                assertSame(p, recorder.p);
2077 +
2078 +                recorder.reset();
2079 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2080 +                assertFalse(future.isDone());
2081 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2082 +                assertSame(p, recorder.p);
2083 +
2084 +                recorder.reset();
2085 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2086 +                assertFalse(future.isDone());
2087 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2088 +                assertSame(p, recorder.p);
2089 +
2090 +                recorder.reset();
2091 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2092 +                assertFalse(future.isDone());
2093 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2094 +                assertSame(p, recorder.p);
2095 +            }
2096 +        }
2097 +
2098 +        // Checking our custom handler above should be sufficient, but
2099 +        // we add some integration tests of standard handlers.
2100 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2101 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2102 +
2103 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2104 +        try {
2105 +            p.execute(setThread);
2106 +            shouldThrow();
2107 +        } catch (RejectedExecutionException success) {}
2108 +        assertNull(thread.get());
2109 +
2110 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2111 +        p.execute(setThread);
2112 +        assertNull(thread.get());
2113 +
2114 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2115 +        p.execute(setThread);
2116 +        if (p.isShutdown())
2117 +            assertNull(thread.get());
2118 +        else
2119 +            assertSame(Thread.currentThread(), thread.get());
2120 +
2121 +        setRejectedExecutionHandler(p, savedHandler);
2122 +
2123 +        // check that pool was not perturbed by handlers
2124 +        assertEquals(savedTaskCount, p.getTaskCount());
2125 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2126 +        assertEquals(savedQueueSize, p.getQueue().size());
2127 +    }
2128 +
2129 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2130 +        assertEquals(x, y);
2131 +        assertEquals(y, x);
2132 +        assertEquals(x.isEmpty(), y.isEmpty());
2133 +        assertEquals(x.size(), y.size());
2134 +        if (x instanceof List) {
2135 +            assertEquals(x.toString(), y.toString());
2136 +        }
2137 +        if (x instanceof List || x instanceof Set) {
2138 +            assertEquals(x.hashCode(), y.hashCode());
2139 +        }
2140 +        if (x instanceof List || x instanceof Deque) {
2141 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2142 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2143 +                                     y.toArray(new Object[0])));
2144 +        }
2145 +    }
2146 +
2147 +    /**
2148 +     * A weaker form of assertCollectionsEquals which does not insist
2149 +     * that the two collections satisfy Object#equals(Object), since
2150 +     * they may use identity semantics as Deques do.
2151 +     */
2152 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2153 +        if (x instanceof List || x instanceof Set)
2154 +            assertCollectionsEquals(x, y);
2155 +        else {
2156 +            assertEquals(x.isEmpty(), y.isEmpty());
2157 +            assertEquals(x.size(), y.size());
2158 +            assertEquals(new HashSet(x), new HashSet(y));
2159 +            if (x instanceof Deque) {
2160 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2161 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2162 +                                         y.toArray(new Object[0])));
2163 +            }
2164 +        }
2165 +    }
2166   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines