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.272 by dl, Tue Jan 26 13:33:06 2021 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.Queue;
78 + import java.util.Set;
79   import java.util.concurrent.BlockingQueue;
80   import java.util.concurrent.Callable;
81   import java.util.concurrent.CountDownLatch;
82   import java.util.concurrent.CyclicBarrier;
83   import java.util.concurrent.ExecutionException;
84 + import java.util.concurrent.Executor;
85   import java.util.concurrent.Executors;
86   import java.util.concurrent.ExecutorService;
87   import java.util.concurrent.ForkJoinPool;
88   import java.util.concurrent.Future;
89 + import java.util.concurrent.FutureTask;
90   import java.util.concurrent.RecursiveAction;
91   import java.util.concurrent.RecursiveTask;
92 + import java.util.concurrent.RejectedExecutionException;
93   import java.util.concurrent.RejectedExecutionHandler;
94   import java.util.concurrent.Semaphore;
95 + import java.util.concurrent.ScheduledExecutorService;
96 + import java.util.concurrent.ScheduledFuture;
97 + import java.util.concurrent.SynchronousQueue;
98   import java.util.concurrent.ThreadFactory;
99 + import java.util.concurrent.ThreadLocalRandom;
100   import java.util.concurrent.ThreadPoolExecutor;
101 + import java.util.concurrent.TimeUnit;
102   import java.util.concurrent.TimeoutException;
103 + import java.util.concurrent.atomic.AtomicBoolean;
104   import java.util.concurrent.atomic.AtomicReference;
105   import java.util.regex.Pattern;
106  
56 import junit.framework.AssertionFailedError;
107   import junit.framework.Test;
108   import junit.framework.TestCase;
109   import junit.framework.TestResult;
# Line 69 | Line 119 | import junit.framework.TestSuite;
119   *
120   * <ol>
121   *
122 < * <li>All assertions in code running in generated threads must use
123 < * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
124 < * #threadAssertEquals}, or {@link #threadAssertNull}, (not
125 < * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
126 < * particularly recommended) for other code to use these forms too.
127 < * Only the most typically used JUnit assertion methods are defined
128 < * this way, but enough to live with.
122 > * <li>All code not running in the main test thread (manually spawned threads
123 > * or the common fork join pool) must be checked for failure (and completion!).
124 > * Mechanisms that can be used to ensure this are:
125 > *   <ol>
126 > *   <li>Signalling via a synchronizer like AtomicInteger or CountDownLatch
127 > *    that the task completed normally, which is checked before returning from
128 > *    the test method in the main thread.
129 > *   <li>Using the forms {@link #threadFail}, {@link #threadAssertTrue},
130 > *    or {@link #threadAssertNull}, (not {@code fail}, {@code assertTrue}, etc.)
131 > *    Only the most typically used JUnit assertion methods are defined
132 > *    this way, but enough to live with.
133 > *   <li>Recording failure explicitly using {@link #threadUnexpectedException}
134 > *    or {@link #threadRecordFailure}.
135 > *   <li>Using a wrapper like CheckedRunnable that uses one the mechanisms above.
136 > *   </ol>
137   *
138   * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
139   * to invoke {@code super.setUp} and {@code super.tearDown} within
# Line 93 | Line 151 | import junit.framework.TestSuite;
151   * but even so, if there is ever any doubt, they can all be increased
152   * in one spot to rerun tests on slower platforms.
153   *
154 + * Class Item is used for elements of collections and related
155 + * purposes. Many tests rely on themir keys being equal to ints. To
156 + * check these, methods mustEqual, mustContain, etc adapt the JUnit
157 + * assert methods to intercept ints.
158 + *
159   * <li>All threads generated must be joined inside each test case
160   * method (or {@code fail} to do so) before returning from the
161   * method. The {@code joinPool} method can be used to do this when
# Line 108 | Line 171 | import junit.framework.TestSuite;
171   * methods as there are exceptions the method can throw. Sometimes
172   * there are multiple tests per JSR166 method when the different
173   * "normal" behaviors differ significantly. And sometimes testcases
174 < * cover multiple methods when they cannot be tested in
112 < * isolation.
174 > * cover multiple methods when they cannot be tested in isolation.
175   *
176   * <li>The documentation style for testcases is to provide as javadoc
177   * a simple sentence or two describing the property that the testcase
# Line 172 | Line 234 | public class JSR166TestCase extends Test
234      private static final int suiteRuns =
235          Integer.getInteger("jsr166.suiteRuns", 1);
236  
237 +    /**
238 +     * Returns the value of the system property, or NaN if not defined.
239 +     */
240 +    private static float systemPropertyValue(String name) {
241 +        String floatString = System.getProperty(name);
242 +        if (floatString == null)
243 +            return Float.NaN;
244 +        try {
245 +            return Float.parseFloat(floatString);
246 +        } catch (NumberFormatException ex) {
247 +            throw new IllegalArgumentException(
248 +                String.format("Bad float value in system property %s=%s",
249 +                              name, floatString));
250 +        }
251 +    }
252 +
253 +    private static final ThreadMXBean THREAD_MXBEAN
254 +        = ManagementFactory.getThreadMXBean();
255 +
256 +    /**
257 +     * The scaling factor to apply to standard delays used in tests.
258 +     * May be initialized from any of:
259 +     * - the "jsr166.delay.factor" system property
260 +     * - the "test.timeout.factor" system property (as used by jtreg)
261 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
262 +     * - hard-coded fuzz factor when using a known slowpoke VM
263 +     */
264 +    private static final float delayFactor = delayFactor();
265 +
266 +    private static float delayFactor() {
267 +        float x;
268 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
269 +            return x;
270 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
271 +            return x;
272 +        String prop = System.getProperty("java.vm.version");
273 +        if (prop != null && prop.matches(".*debug.*"))
274 +            return 4.0f; // How much slower is fastdebug than product?!
275 +        return 1.0f;
276 +    }
277 +
278      public JSR166TestCase() { super(); }
279      public JSR166TestCase(String name) { super(name); }
280  
# Line 187 | Line 290 | public class JSR166TestCase extends Test
290          return (regex == null) ? null : Pattern.compile(regex);
291      }
292  
293 +    // Instrumentation to debug very rare, but very annoying hung test runs.
294 +    static volatile TestCase currentTestCase;
295 +    // static volatile int currentRun = 0;
296 +    static {
297 +        Runnable wedgedTestDetector = new Runnable() { public void run() {
298 +            // Avoid spurious reports with enormous runsPerTest.
299 +            // A single test case run should never take more than 1 second.
300 +            // But let's cap it at the high end too ...
301 +            final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1)
302 +                * Math.max((int) delayFactor, 1);
303 +            final int timeoutMinutes = Math.min(15, timeoutMinutesMin);
304 +            for (TestCase lastTestCase = currentTestCase;;) {
305 +                try { MINUTES.sleep(timeoutMinutes); }
306 +                catch (InterruptedException unexpected) { break; }
307 +                if (lastTestCase == currentTestCase) {
308 +                    System.err.printf(
309 +                        "Looks like we're stuck running test: %s%n",
310 +                        lastTestCase);
311 + //                     System.err.printf(
312 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
313 + //                         lastTestCase, currentRun, runsPerTest);
314 + //                     System.err.println("availableProcessors=" +
315 + //                         Runtime.getRuntime().availableProcessors());
316 + //                     System.err.printf("cpu model = %s%n", cpuModel());
317 +                    dumpTestThreads();
318 +                    // one stack dump is probably enough; more would be spam
319 +                    break;
320 +                }
321 +                lastTestCase = currentTestCase;
322 +            }}};
323 +        Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector");
324 +        thread.setDaemon(true);
325 +        thread.start();
326 +    }
327 +
328 + //     public static String cpuModel() {
329 + //         try {
330 + //             java.util.regex.Matcher matcher
331 + //               = Pattern.compile("model name\\s*: (.*)")
332 + //                 .matcher(new String(
333 + //                     java.nio.file.Files.readAllBytes(
334 + //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
335 + //             matcher.find();
336 + //             return matcher.group(1);
337 + //         } catch (Exception ex) { return null; }
338 + //     }
339 +
340      public void runBare() throws Throwable {
341 +        currentTestCase = this;
342          if (methodFilter == null
343              || methodFilter.matcher(toString()).find())
344              super.runBare();
# Line 195 | Line 346 | public class JSR166TestCase extends Test
346  
347      protected void runTest() throws Throwable {
348          for (int i = 0; i < runsPerTest; i++) {
349 +            // currentRun = i;
350              if (profileTests)
351                  runTestProfiled();
352              else
# Line 212 | Line 364 | public class JSR166TestCase extends Test
364              // Never report first run of any test; treat it as a
365              // warmup run, notably to trigger all needed classloading,
366              if (i > 0)
367 <                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
367 >                System.out.printf("%s: %d%n", toString(), elapsedMillis);
368          }
369      }
370  
# Line 223 | Line 375 | public class JSR166TestCase extends Test
375          main(suite(), args);
376      }
377  
378 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
379 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
380 +        long runTime;
381 +        public void startTest(Test test) {}
382 +        protected void printHeader(long runTime) {
383 +            this.runTime = runTime; // defer printing for later
384 +        }
385 +        protected void printFooter(TestResult result) {
386 +            if (result.wasSuccessful()) {
387 +                getWriter().println("OK (" + result.runCount() + " tests)"
388 +                    + "  Time: " + elapsedTimeAsString(runTime));
389 +            } else {
390 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
391 +                super.printFooter(result);
392 +            }
393 +        }
394 +    }
395 +
396 +    /**
397 +     * Returns a TestRunner that doesn't bother with unnecessary
398 +     * fluff, like printing a "." for each test case.
399 +     */
400 +    static junit.textui.TestRunner newPithyTestRunner() {
401 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
402 +        runner.setPrinter(new PithyResultPrinter(System.out));
403 +        return runner;
404 +    }
405 +
406      /**
407       * Runs all unit tests in the given test suite.
408       * Actual behavior influenced by jsr166.* system properties.
# Line 234 | Line 414 | public class JSR166TestCase extends Test
414              System.setSecurityManager(new SecurityManager());
415          }
416          for (int i = 0; i < suiteRuns; i++) {
417 <            TestResult result = junit.textui.TestRunner.run(suite);
417 >            TestResult result = newPithyTestRunner().doRun(suite);
418              if (!result.wasSuccessful())
419                  System.exit(1);
420              System.gc();
# Line 260 | Line 440 | public class JSR166TestCase extends Test
440          for (String testClassName : testClassNames) {
441              try {
442                  Class<?> testClass = Class.forName(testClassName);
443 <                Method m = testClass.getDeclaredMethod("suite",
264 <                                                       new Class<?>[0]);
443 >                Method m = testClass.getDeclaredMethod("suite");
444                  suite.addTest(newTestSuite((Test)m.invoke(null)));
445 <            } catch (Exception e) {
446 <                throw new Error("Missing test class", e);
445 >            } catch (ReflectiveOperationException e) {
446 >                throw new AssertionError("Missing test class", e);
447              }
448          }
449      }
# Line 286 | Line 465 | public class JSR166TestCase extends Test
465          }
466      }
467  
468 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
469 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
470 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
471 <    public static boolean atLeastJava9() {
472 <        return JAVA_CLASS_VERSION >= 53.0
473 <            // As of 2015-09, java9 still uses 52.0 class file version
474 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
475 <    }
476 <    public static boolean atLeastJava10() {
477 <        return JAVA_CLASS_VERSION >= 54.0
478 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
479 <    }
468 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
469 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
470 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
471 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
472 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
473 >    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
474 >    public static boolean atLeastJava12() { return JAVA_CLASS_VERSION >= 56.0; }
475 >    public static boolean atLeastJava13() { return JAVA_CLASS_VERSION >= 57.0; }
476 >    public static boolean atLeastJava14() { return JAVA_CLASS_VERSION >= 58.0; }
477 >    public static boolean atLeastJava15() { return JAVA_CLASS_VERSION >= 59.0; }
478 >    public static boolean atLeastJava16() { return JAVA_CLASS_VERSION >= 60.0; }
479 >    public static boolean atLeastJava17() { return JAVA_CLASS_VERSION >= 61.0; }
480  
481      /**
482       * Collects all JSR166 unit tests as one suite.
# Line 318 | Line 497 | public class JSR166TestCase extends Test
497              AbstractQueuedLongSynchronizerTest.suite(),
498              ArrayBlockingQueueTest.suite(),
499              ArrayDequeTest.suite(),
500 +            ArrayListTest.suite(),
501              AtomicBooleanTest.suite(),
502              AtomicIntegerArrayTest.suite(),
503              AtomicIntegerFieldUpdaterTest.suite(),
# Line 340 | Line 520 | public class JSR166TestCase extends Test
520              CopyOnWriteArrayListTest.suite(),
521              CopyOnWriteArraySetTest.suite(),
522              CountDownLatchTest.suite(),
523 +            CountedCompleterTest.suite(),
524              CyclicBarrierTest.suite(),
525              DelayQueueTest.suite(),
526              EntryTest.suite(),
# Line 347 | Line 528 | public class JSR166TestCase extends Test
528              ExecutorsTest.suite(),
529              ExecutorCompletionServiceTest.suite(),
530              FutureTaskTest.suite(),
531 +            HashtableTest.suite(),
532              LinkedBlockingDequeTest.suite(),
533              LinkedBlockingQueueTest.suite(),
534              LinkedListTest.suite(),
# Line 368 | Line 550 | public class JSR166TestCase extends Test
550              TreeMapTest.suite(),
551              TreeSetTest.suite(),
552              TreeSubMapTest.suite(),
553 <            TreeSubSetTest.suite());
553 >            TreeSubSetTest.suite(),
554 >            VectorTest.suite());
555  
556          // Java8+ test classes
557          if (atLeastJava8()) {
558              String[] java8TestClassNames = {
559 +                "ArrayDeque8Test",
560                  "Atomic8Test",
561                  "CompletableFutureTest",
562                  "ConcurrentHashMap8Test",
563 <                "CountedCompleterTest",
563 >                "CountedCompleter8Test",
564                  "DoubleAccumulatorTest",
565                  "DoubleAdderTest",
566                  "ForkJoinPool8Test",
567                  "ForkJoinTask8Test",
568 +                "HashMapTest",
569 +                "LinkedBlockingDeque8Test",
570 +                "LinkedBlockingQueue8Test",
571 +                "LinkedHashMapTest",
572                  "LongAccumulatorTest",
573                  "LongAdderTest",
574                  "SplittableRandomTest",
575                  "StampedLockTest",
576                  "SubmissionPublisherTest",
577                  "ThreadLocalRandom8Test",
578 +                "TimeUnit8Test",
579              };
580              addNamedTestClasses(suite, java8TestClassNames);
581          }
# Line 394 | Line 583 | public class JSR166TestCase extends Test
583          // Java9+ test classes
584          if (atLeastJava9()) {
585              String[] java9TestClassNames = {
586 <                // Currently empty, but expecting varhandle tests
586 >                "AtomicBoolean9Test",
587 >                "AtomicInteger9Test",
588 >                "AtomicIntegerArray9Test",
589 >                "AtomicLong9Test",
590 >                "AtomicLongArray9Test",
591 >                "AtomicReference9Test",
592 >                "AtomicReferenceArray9Test",
593 >                "ExecutorCompletionService9Test",
594 >                "ForkJoinPool9Test",
595              };
596              addNamedTestClasses(suite, java9TestClassNames);
597          }
# Line 405 | Line 602 | public class JSR166TestCase extends Test
602      /** Returns list of junit-style test method names in given class. */
603      public static ArrayList<String> testMethodNames(Class<?> testClass) {
604          Method[] methods = testClass.getDeclaredMethods();
605 <        ArrayList<String> names = new ArrayList<String>(methods.length);
605 >        ArrayList<String> names = new ArrayList<>(methods.length);
606          for (Method method : methods) {
607              if (method.getName().startsWith("test")
608                  && Modifier.isPublic(method.getModifiers())
# Line 432 | Line 629 | public class JSR166TestCase extends Test
629              for (String methodName : testMethodNames(testClass))
630                  suite.addTest((Test) c.newInstance(data, methodName));
631              return suite;
632 <        } catch (Exception e) {
633 <            throw new Error(e);
632 >        } catch (ReflectiveOperationException e) {
633 >            throw new AssertionError(e);
634          }
635      }
636  
# Line 449 | Line 646 | public class JSR166TestCase extends Test
646          if (atLeastJava8()) {
647              String name = testClass.getName();
648              String name8 = name.replaceAll("Test$", "8Test");
649 <            if (name.equals(name8)) throw new Error(name);
649 >            if (name.equals(name8)) throw new AssertionError(name);
650              try {
651                  return (Test)
652                      Class.forName(name8)
653 <                    .getMethod("testSuite", new Class[] { dataClass })
653 >                    .getMethod("testSuite", dataClass)
654                      .invoke(null, data);
655 <            } catch (Exception e) {
656 <                throw new Error(e);
655 >            } catch (ReflectiveOperationException e) {
656 >                throw new AssertionError(e);
657              }
658          } else {
659              return new TestSuite();
# Line 471 | Line 668 | public class JSR166TestCase extends Test
668      public static long LONG_DELAY_MS;
669  
670      /**
671 <     * Returns the shortest timed delay. This could
672 <     * be reimplemented to use for example a Property.
671 >     * A delay significantly longer than LONG_DELAY_MS.
672 >     * Use this in a thread that is waited for via awaitTermination(Thread).
673 >     */
674 >    public static long LONGER_DELAY_MS;
675 >
676 >    private static final long RANDOM_TIMEOUT;
677 >    private static final long RANDOM_EXPIRED_TIMEOUT;
678 >    private static final TimeUnit RANDOM_TIMEUNIT;
679 >    static {
680 >        ThreadLocalRandom rnd = ThreadLocalRandom.current();
681 >        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
682 >        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
683 >        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
684 >        TimeUnit[] timeUnits = TimeUnit.values();
685 >        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
686 >    }
687 >
688 >    /**
689 >     * Returns a timeout for use when any value at all will do.
690 >     */
691 >    static long randomTimeout() { return RANDOM_TIMEOUT; }
692 >
693 >    /**
694 >     * Returns a timeout that means "no waiting", i.e. not positive.
695 >     */
696 >    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
697 >
698 >    /**
699 >     * Returns a random non-null TimeUnit.
700 >     */
701 >    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
702 >
703 >    /**
704 >     * Returns a random boolean; a "coin flip".
705 >     */
706 >    static boolean randomBoolean() {
707 >        return ThreadLocalRandom.current().nextBoolean();
708 >    }
709 >
710 >    /**
711 >     * Returns a random element from given choices.
712 >     */
713 >    <T> T chooseRandomly(List<T> choices) {
714 >        return choices.get(ThreadLocalRandom.current().nextInt(choices.size()));
715 >    }
716 >
717 >    /**
718 >     * Returns a random element from given choices.
719 >     */
720 >    @SuppressWarnings("unchecked")
721 >    <T> T chooseRandomly(T... choices) {
722 >        return choices[ThreadLocalRandom.current().nextInt(choices.length)];
723 >    }
724 >
725 >    /**
726 >     * Returns the shortest timed delay. This can be scaled up for
727 >     * slow machines using the jsr166.delay.factor system property,
728 >     * or via jtreg's -timeoutFactor: flag.
729 >     * http://openjdk.java.net/jtreg/command-help.html
730       */
731      protected long getShortDelay() {
732 <        return 50;
732 >        return (long) (50 * delayFactor);
733      }
734  
735      /**
# Line 486 | Line 740 | public class JSR166TestCase extends Test
740          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
741          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
742          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
743 +        LONGER_DELAY_MS = 2 * LONG_DELAY_MS;
744      }
745  
746 +    private static final long TIMEOUT_DELAY_MS
747 +        = (long) (12.0 * Math.cbrt(delayFactor));
748 +
749      /**
750 <     * Returns a timeout in milliseconds to be used in tests that
751 <     * verify that operations block or time out.
750 >     * Returns a timeout in milliseconds to be used in tests that verify
751 >     * that operations block or time out.  We want this to be longer
752 >     * than the OS scheduling quantum, but not too long, so don't scale
753 >     * linearly with delayFactor; we use "crazy" cube root instead.
754       */
755 <    long timeoutMillis() {
756 <        return SHORT_DELAY_MS / 4;
755 >    static long timeoutMillis() {
756 >        return TIMEOUT_DELAY_MS;
757      }
758  
759      /**
# Line 509 | Line 769 | public class JSR166TestCase extends Test
769       * The first exception encountered if any threadAssertXXX method fails.
770       */
771      private final AtomicReference<Throwable> threadFailure
772 <        = new AtomicReference<Throwable>(null);
772 >        = new AtomicReference<>(null);
773  
774      /**
775       * Records an exception so that it can be rethrown later in the test
# Line 518 | Line 778 | public class JSR166TestCase extends Test
778       * the same test have no effect.
779       */
780      public void threadRecordFailure(Throwable t) {
781 <        threadDump();
782 <        threadFailure.compareAndSet(null, t);
781 >        System.err.println(t);
782 >        if (threadFailure.compareAndSet(null, t))
783 >            dumpTestThreads();
784      }
785  
786      public void setUp() {
# Line 529 | Line 790 | public class JSR166TestCase extends Test
790      void tearDownFail(String format, Object... args) {
791          String msg = toString() + ": " + String.format(format, args);
792          System.err.println(msg);
793 <        threadDump();
794 <        throw new AssertionFailedError(msg);
793 >        dumpTestThreads();
794 >        throw new AssertionError(msg);
795      }
796  
797      /**
# Line 551 | Line 812 | public class JSR166TestCase extends Test
812                  throw (RuntimeException) t;
813              else if (t instanceof Exception)
814                  throw (Exception) t;
815 <            else {
816 <                AssertionFailedError afe =
556 <                    new AssertionFailedError(t.toString());
557 <                afe.initCause(t);
558 <                throw afe;
559 <            }
815 >            else
816 >                throw new AssertionError(t.toString(), t);
817          }
818  
819          if (Thread.interrupted())
# Line 566 | Line 823 | public class JSR166TestCase extends Test
823      }
824  
825      /**
826 <     * Finds missing try { ... } finally { joinPool(e); }
826 >     * Finds missing PoolCleaners
827       */
828      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
829          Thread[] survivors = new Thread[7];
# Line 590 | Line 847 | public class JSR166TestCase extends Test
847  
848      /**
849       * Just like fail(reason), but additionally recording (using
850 <     * threadRecordFailure) any AssertionFailedError thrown, so that
851 <     * the current testcase will fail.
850 >     * threadRecordFailure) any AssertionError thrown, so that the
851 >     * current testcase will fail.
852       */
853      public void threadFail(String reason) {
854          try {
855              fail(reason);
856 <        } catch (AssertionFailedError t) {
857 <            threadRecordFailure(t);
858 <            throw t;
856 >        } catch (AssertionError fail) {
857 >            threadRecordFailure(fail);
858 >            throw fail;
859          }
860      }
861  
862      /**
863       * Just like assertTrue(b), but additionally recording (using
864 <     * threadRecordFailure) any AssertionFailedError thrown, so that
865 <     * the current testcase will fail.
864 >     * threadRecordFailure) any AssertionError thrown, so that the
865 >     * current testcase will fail.
866       */
867      public void threadAssertTrue(boolean b) {
868          try {
869              assertTrue(b);
870 <        } catch (AssertionFailedError t) {
871 <            threadRecordFailure(t);
872 <            throw t;
870 >        } catch (AssertionError fail) {
871 >            threadRecordFailure(fail);
872 >            throw fail;
873          }
874      }
875  
876      /**
877       * Just like assertFalse(b), but additionally recording (using
878 <     * threadRecordFailure) any AssertionFailedError thrown, so that
879 <     * the current testcase will fail.
878 >     * threadRecordFailure) any AssertionError thrown, so that the
879 >     * current testcase will fail.
880       */
881      public void threadAssertFalse(boolean b) {
882          try {
883              assertFalse(b);
884 <        } catch (AssertionFailedError t) {
885 <            threadRecordFailure(t);
886 <            throw t;
884 >        } catch (AssertionError fail) {
885 >            threadRecordFailure(fail);
886 >            throw fail;
887          }
888      }
889  
890      /**
891       * Just like assertNull(x), but additionally recording (using
892 <     * threadRecordFailure) any AssertionFailedError thrown, so that
893 <     * the current testcase will fail.
892 >     * threadRecordFailure) any AssertionError thrown, so that the
893 >     * current testcase will fail.
894       */
895      public void threadAssertNull(Object x) {
896          try {
897              assertNull(x);
898 <        } catch (AssertionFailedError t) {
899 <            threadRecordFailure(t);
900 <            throw t;
898 >        } catch (AssertionError fail) {
899 >            threadRecordFailure(fail);
900 >            throw fail;
901          }
902      }
903  
904      /**
905       * Just like assertEquals(x, y), but additionally recording (using
906 <     * threadRecordFailure) any AssertionFailedError thrown, so that
907 <     * the current testcase will fail.
906 >     * threadRecordFailure) any AssertionError thrown, so that the
907 >     * current testcase will fail.
908       */
909      public void threadAssertEquals(long x, long y) {
910          try {
911              assertEquals(x, y);
912 <        } catch (AssertionFailedError t) {
913 <            threadRecordFailure(t);
914 <            throw t;
912 >        } catch (AssertionError fail) {
913 >            threadRecordFailure(fail);
914 >            throw fail;
915          }
916      }
917  
918      /**
919       * Just like assertEquals(x, y), but additionally recording (using
920 <     * threadRecordFailure) any AssertionFailedError thrown, so that
921 <     * the current testcase will fail.
920 >     * threadRecordFailure) any AssertionError thrown, so that the
921 >     * current testcase will fail.
922       */
923      public void threadAssertEquals(Object x, Object y) {
924          try {
925              assertEquals(x, y);
926 <        } catch (AssertionFailedError fail) {
926 >        } catch (AssertionError fail) {
927              threadRecordFailure(fail);
928              throw fail;
929          } catch (Throwable fail) {
# Line 676 | Line 933 | public class JSR166TestCase extends Test
933  
934      /**
935       * Just like assertSame(x, y), but additionally recording (using
936 <     * threadRecordFailure) any AssertionFailedError thrown, so that
937 <     * the current testcase will fail.
936 >     * threadRecordFailure) any AssertionError thrown, so that the
937 >     * current testcase will fail.
938       */
939      public void threadAssertSame(Object x, Object y) {
940          try {
941              assertSame(x, y);
942 <        } catch (AssertionFailedError fail) {
942 >        } catch (AssertionError fail) {
943              threadRecordFailure(fail);
944              throw fail;
945          }
# Line 704 | Line 961 | public class JSR166TestCase extends Test
961  
962      /**
963       * Records the given exception using {@link #threadRecordFailure},
964 <     * then rethrows the exception, wrapping it in an
965 <     * AssertionFailedError if necessary.
964 >     * then rethrows the exception, wrapping it in an AssertionError
965 >     * if necessary.
966       */
967      public void threadUnexpectedException(Throwable t) {
968          threadRecordFailure(t);
# Line 714 | Line 971 | public class JSR166TestCase extends Test
971              throw (RuntimeException) t;
972          else if (t instanceof Error)
973              throw (Error) t;
974 <        else {
975 <            AssertionFailedError afe =
719 <                new AssertionFailedError("unexpected exception: " + t);
720 <            afe.initCause(t);
721 <            throw afe;
722 <        }
974 >        else
975 >            throw new AssertionError("unexpected exception: " + t, t);
976      }
977  
978      /**
979       * Delays, via Thread.sleep, for the given millisecond delay, but
980       * if the sleep is shorter than specified, may re-sleep or yield
981 <     * until time elapses.
981 >     * until time elapses.  Ensures that the given time, as measured
982 >     * by System.nanoTime(), has elapsed.
983       */
984      static void delay(long millis) throws InterruptedException {
985 <        long startTime = System.nanoTime();
986 <        long ns = millis * 1000 * 1000;
987 <        for (;;) {
985 >        long nanos = millis * (1000 * 1000);
986 >        final long wakeupTime = System.nanoTime() + nanos;
987 >        do {
988              if (millis > 0L)
989                  Thread.sleep(millis);
990              else // too short to sleep
991                  Thread.yield();
992 <            long d = ns - (System.nanoTime() - startTime);
993 <            if (d > 0L)
994 <                millis = d / (1000 * 1000);
741 <            else
742 <                break;
743 <        }
992 >            nanos = wakeupTime - System.nanoTime();
993 >            millis = nanos / (1000 * 1000);
994 >        } while (nanos >= 0L);
995      }
996  
997      /**
998       * Allows use of try-with-resources with per-test thread pools.
999       */
1000 <    static class PoolCloser<T extends ExecutorService>
1001 <            implements AutoCloseable {
1002 <        public final T pool;
752 <        public PoolCloser(T pool) { this.pool = pool; }
1000 >    class PoolCleaner implements AutoCloseable {
1001 >        private final ExecutorService pool;
1002 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
1003          public void close() { joinPool(pool); }
1004      }
1005  
1006      /**
1007 +     * An extension of PoolCleaner that has an action to release the pool.
1008 +     */
1009 +    class PoolCleanerWithReleaser extends PoolCleaner {
1010 +        private final Runnable releaser;
1011 +        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
1012 +            super(pool);
1013 +            this.releaser = releaser;
1014 +        }
1015 +        public void close() {
1016 +            try {
1017 +                releaser.run();
1018 +            } finally {
1019 +                super.close();
1020 +            }
1021 +        }
1022 +    }
1023 +
1024 +    PoolCleaner cleaner(ExecutorService pool) {
1025 +        return new PoolCleaner(pool);
1026 +    }
1027 +
1028 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
1029 +        return new PoolCleanerWithReleaser(pool, releaser);
1030 +    }
1031 +
1032 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
1033 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
1034 +    }
1035 +
1036 +    Runnable releaser(final CountDownLatch latch) {
1037 +        return new Runnable() { public void run() {
1038 +            do { latch.countDown(); }
1039 +            while (latch.getCount() > 0);
1040 +        }};
1041 +    }
1042 +
1043 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1044 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
1045 +    }
1046 +
1047 +    Runnable releaser(final AtomicBoolean flag) {
1048 +        return new Runnable() { public void run() { flag.set(true); }};
1049 +    }
1050 +
1051 +    /**
1052       * Waits out termination of a thread pool or fails doing so.
1053       */
1054 <    static void joinPool(ExecutorService pool) {
1054 >    void joinPool(ExecutorService pool) {
1055          try {
1056              pool.shutdown();
1057 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
1058 <                fail("ExecutorService " + pool +
1059 <                     " did not terminate in a timely manner");
1057 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1058 >                try {
1059 >                    threadFail("ExecutorService " + pool +
1060 >                               " did not terminate in a timely manner");
1061 >                } finally {
1062 >                    // last resort, for the benefit of subsequent tests
1063 >                    pool.shutdownNow();
1064 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1065 >                }
1066 >            }
1067          } catch (SecurityException ok) {
1068              // Allowed in case test doesn't have privs
1069          } catch (InterruptedException fail) {
1070 <            fail("Unexpected InterruptedException");
1070 >            threadFail("Unexpected InterruptedException");
1071          }
1072      }
1073  
1074 <    /** Like Runnable, but with the freedom to throw anything */
1074 >    /**
1075 >     * Like Runnable, but with the freedom to throw anything.
1076 >     * junit folks had the same idea:
1077 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1078 >     */
1079      interface Action { public void run() throws Throwable; }
1080  
1081      /**
# Line 778 | Line 1084 | public class JSR166TestCase extends Test
1084       * necessarily individually slow because they must block.
1085       */
1086      void testInParallel(Action ... actions) {
1087 <        try (PoolCloser<ExecutorService> poolCloser
1088 <             = new PoolCloser<>(Executors.newCachedThreadPool())) {
783 <            ExecutorService pool = poolCloser.pool;
1087 >        ExecutorService pool = Executors.newCachedThreadPool();
1088 >        try (PoolCleaner cleaner = cleaner(pool)) {
1089              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1090              for (final Action action : actions)
1091                  futures.add(pool.submit(new CheckedRunnable() {
# Line 796 | Line 1101 | public class JSR166TestCase extends Test
1101          }
1102      }
1103  
1104 +    /** Returns true if thread info might be useful in a thread dump. */
1105 +    static boolean threadOfInterest(ThreadInfo info) {
1106 +        final String name = info.getThreadName();
1107 +        String lockName;
1108 +        if (name == null)
1109 +            return true;
1110 +        if (name.equals("Signal Dispatcher")
1111 +            || name.equals("WedgedTestDetector"))
1112 +            return false;
1113 +        if (name.equals("Reference Handler")) {
1114 +            // Reference Handler stacktrace changed in JDK-8156500
1115 +            StackTraceElement[] stackTrace; String methodName;
1116 +            if ((stackTrace = info.getStackTrace()) != null
1117 +                && stackTrace.length > 0
1118 +                && (methodName = stackTrace[0].getMethodName()) != null
1119 +                && methodName.equals("waitForReferencePendingList"))
1120 +                return false;
1121 +            // jdk8 Reference Handler stacktrace
1122 +            if ((lockName = info.getLockName()) != null
1123 +                && lockName.startsWith("java.lang.ref"))
1124 +                return false;
1125 +        }
1126 +        if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
1127 +            && (lockName = info.getLockName()) != null
1128 +            && lockName.startsWith("java.lang.ref"))
1129 +            return false;
1130 +        if (name.startsWith("ForkJoinPool.commonPool-worker")
1131 +            && (lockName = info.getLockName()) != null
1132 +            && lockName.startsWith("java.util.concurrent.ForkJoinPool"))
1133 +            return false;
1134 +        return true;
1135 +    }
1136 +
1137      /**
1138 <     * A debugging tool to print all stack traces, as jstack does.
1138 >     * A debugging tool to print stack traces of most threads, as jstack does.
1139       * Uninteresting threads are filtered out.
1140       */
1141 <    static void threadDump() {
1142 <        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1143 <        System.err.println("------ stacktrace dump start ------");
1144 <        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1145 <            String name = info.getThreadName();
1146 <            if ("Signal Dispatcher".equals(name))
1147 <                continue;
1148 <            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);
1141 >    static void dumpTestThreads() {
1142 >        SecurityManager sm = System.getSecurityManager();
1143 >        if (sm != null) {
1144 >            try {
1145 >                System.setSecurityManager(null);
1146 >            } catch (SecurityException giveUp) {
1147 >                return;
1148 >            }
1149          }
1150 +
1151 +        System.err.println("------ stacktrace dump start ------");
1152 +        for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true))
1153 +            if (threadOfInterest(info))
1154 +                System.err.print(info);
1155          System.err.println("------ stacktrace dump end ------");
819    }
1156  
1157 <    /**
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());
1157 >        if (sm != null) System.setSecurityManager(sm);
1158      }
1159  
1160      /**
1161 <     * Checks that thread does not terminate within the given millisecond delay.
1161 >     * Checks that thread eventually enters the expected blocked thread state.
1162       */
1163 <    void assertThreadStaysAlive(Thread thread, long millis) {
1164 <        try {
1165 <            // No need to optimize the failing case via Thread.join.
1166 <            delay(millis);
1167 <            assertTrue(thread.isAlive());
1168 <        } catch (InterruptedException fail) {
1169 <            fail("Unexpected InterruptedException");
1163 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1164 >        // always sleep at least 1 ms, with high probability avoiding
1165 >        // transitory states
1166 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1167 >            try { delay(1); }
1168 >            catch (InterruptedException fail) {
1169 >                throw new AssertionError("Unexpected InterruptedException", fail);
1170 >            }
1171 >            Thread.State s = thread.getState();
1172 >            if (s == expected)
1173 >                return;
1174 >            else if (s == Thread.State.TERMINATED)
1175 >                fail("Unexpected thread termination");
1176          }
1177 +        fail("timed out waiting for thread to enter thread state " + expected);
1178      }
1179  
1180      /**
1181 <     * Checks that the threads do not terminate within the default
844 <     * millisecond delay of {@code timeoutMillis()}.
1181 >     * Returns the thread's blocker's class name, if any, else null.
1182       */
1183 <    void assertThreadsStayAlive(Thread... threads) {
1184 <        assertThreadsStayAlive(timeoutMillis(), threads);
1185 <    }
1186 <
1187 <    /**
1188 <     * 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 <        }
1183 >    String blockerClassName(Thread thread) {
1184 >        ThreadInfo threadInfo; LockInfo lockInfo;
1185 >        if ((threadInfo = THREAD_MXBEAN.getThreadInfo(thread.getId(), 0)) != null
1186 >            && (lockInfo = threadInfo.getLockInfo()) != null)
1187 >            return lockInfo.getClassName();
1188 >        return null;
1189      }
1190  
1191      /**
1192       * Checks that future.get times out, with the default timeout of
1193       * {@code timeoutMillis()}.
1194       */
1195 <    void assertFutureTimesOut(Future future) {
1195 >    void assertFutureTimesOut(Future<?> future) {
1196          assertFutureTimesOut(future, timeoutMillis());
1197      }
1198  
1199      /**
1200       * Checks that future.get times out, with the given millisecond timeout.
1201       */
1202 <    void assertFutureTimesOut(Future future, long timeoutMillis) {
1202 >    void assertFutureTimesOut(Future<?> future, long timeoutMillis) {
1203          long startTime = System.nanoTime();
1204          try {
1205              future.get(timeoutMillis, MILLISECONDS);
# Line 880 | Line 1207 | public class JSR166TestCase extends Test
1207          } catch (TimeoutException success) {
1208          } catch (Exception fail) {
1209              threadUnexpectedException(fail);
1210 <        } finally { future.cancel(true); }
1210 >        }
1211          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1212 +        assertFalse(future.isDone());
1213      }
1214  
1215      /**
# Line 899 | Line 1227 | public class JSR166TestCase extends Test
1227      }
1228  
1229      /**
1230 <     * The number of elements to place in collections, arrays, etc.
1230 >     * The maximum number of consecutive spurious wakeups we should
1231 >     * tolerate (from APIs like LockSupport.park) before failing a test.
1232       */
1233 <    public static final int SIZE = 20;
1233 >    static final int MAX_SPURIOUS_WAKEUPS = 10;
1234  
1235 <    // Some convenient Integer constants
1235 >    /**
1236 >     * The number of elements to place in collections, arrays, etc.
1237 >     * Must be at least ten;
1238 >     */
1239 >    public static final int SIZE = 32;
1240  
1241 <    public static final Integer zero  = new Integer(0);
1242 <    public static final Integer one   = new Integer(1);
1243 <    public static final Integer two   = new Integer(2);
1244 <    public static final Integer three = new Integer(3);
1245 <    public static final Integer four  = new Integer(4);
1246 <    public static final Integer five  = new Integer(5);
1247 <    public static final Integer six   = new Integer(6);
1248 <    public static final Integer seven = new Integer(7);
1249 <    public static final Integer eight = new Integer(8);
1250 <    public static final Integer nine  = new Integer(9);
1251 <    public static final Integer m1  = new Integer(-1);
1252 <    public static final Integer m2  = new Integer(-2);
1253 <    public static final Integer m3  = new Integer(-3);
1254 <    public static final Integer m4  = new Integer(-4);
1255 <    public static final Integer m5  = new Integer(-5);
1256 <    public static final Integer m6  = new Integer(-6);
1257 <    public static final Integer m10 = new Integer(-10);
1241 >    static Item[] seqItems(int size) {
1242 >        Item[] s = new Item[size];
1243 >        for (int i = 0; i < size; ++i)
1244 >            s[i] = new Item(i);
1245 >        return s;
1246 >    }
1247 >    static Item[] negativeSeqItems(int size) {
1248 >        Item[] s = new Item[size];
1249 >        for (int i = 0; i < size; ++i)
1250 >            s[i] = new Item(-i);
1251 >        return s;
1252 >    }
1253 >
1254 >    // Many tests rely on defaultItems all being sequential nonnegative
1255 >    public static final Item[] defaultItems = seqItems(SIZE);
1256 >
1257 >    static Item itemFor(int i) { // check cache for defaultItems
1258 >        Item[] items = defaultItems;
1259 >        return (i >= 0 && i < items.length) ? items[i] : new Item(i);
1260 >    }
1261 >
1262 >    public static final Item zero  = defaultItems[0];
1263 >    public static final Item one   = defaultItems[1];
1264 >    public static final Item two   = defaultItems[2];
1265 >    public static final Item three = defaultItems[3];
1266 >    public static final Item four  = defaultItems[4];
1267 >    public static final Item five  = defaultItems[5];
1268 >    public static final Item six   = defaultItems[6];
1269 >    public static final Item seven = defaultItems[7];
1270 >    public static final Item eight = defaultItems[8];
1271 >    public static final Item nine  = defaultItems[9];
1272 >    public static final Item ten   = defaultItems[10];
1273 >
1274 >    public static final Item[] negativeItems = negativeSeqItems(SIZE);
1275 >
1276 >    public static final Item minusOne   = negativeItems[1];
1277 >    public static final Item minusTwo   = negativeItems[2];
1278 >    public static final Item minusThree = negativeItems[3];
1279 >    public static final Item minusFour  = negativeItems[4];
1280 >    public static final Item minusFive  = negativeItems[5];
1281 >    public static final Item minusSix   = negativeItems[6];
1282 >    public static final Item minusSeven = negativeItems[7];
1283 >    public static final Item minusEight = negativeItems[8];
1284 >    public static final Item minusNone  = negativeItems[9];
1285 >    public static final Item minusTen   = negativeItems[10];
1286 >
1287 >    // elements expected to be missing
1288 >    public static final Item fortytwo = new Item(42);
1289 >    public static final Item eightysix = new Item(86);
1290 >    public static final Item ninetynine = new Item(99);
1291 >
1292 >    // Interop across Item, int
1293 >
1294 >    static void mustEqual(Item x, Item y) {
1295 >        if (x != y)
1296 >            assertEquals(x.value, y.value);
1297 >    }
1298 >    static void mustEqual(Item x, int y) {
1299 >        assertEquals(x.value, y);
1300 >    }
1301 >    static void mustEqual(int x, Item y) {
1302 >        assertEquals(x, y.value);
1303 >    }
1304 >    static void mustEqual(int x, int y) {
1305 >        assertEquals(x, y);
1306 >    }
1307 >    static void mustEqual(Object x, Object y) {
1308 >        if (x != y)
1309 >            assertEquals(x, y);
1310 >    }
1311 >    static void mustEqual(int x, Object y) {
1312 >        if (y instanceof Item)
1313 >            assertEquals(x, ((Item)y).value);
1314 >        else fail();
1315 >    }
1316 >    static void mustEqual(Object x, int y) {
1317 >        if (x instanceof Item)
1318 >            assertEquals(((Item)x).value, y);
1319 >        else fail();
1320 >    }
1321 >    static void mustEqual(boolean x, boolean y) {
1322 >        assertEquals(x, y);
1323 >    }
1324 >    static void mustEqual(long x, long y) {
1325 >        assertEquals(x, y);
1326 >    }
1327 >    static void mustEqual(double x, double y) {
1328 >        assertEquals(x, y);
1329 >    }
1330 >    static void mustContain(Collection<Item> c, int i) {
1331 >        assertTrue(c.contains(itemFor(i)));
1332 >    }
1333 >    static void mustContain(Collection<Item> c, Item i) {
1334 >        assertTrue(c.contains(i));
1335 >    }
1336 >    static void mustNotContain(Collection<Item> c, int i) {
1337 >        assertFalse(c.contains(itemFor(i)));
1338 >    }
1339 >    static void mustNotContain(Collection<Item> c, Item i) {
1340 >        assertFalse(c.contains(i));
1341 >    }
1342 >    static void mustRemove(Collection<Item> c, int i) {
1343 >        assertTrue(c.remove(itemFor(i)));
1344 >    }
1345 >    static void mustRemove(Collection<Item> c, Item i) {
1346 >        assertTrue(c.remove(i));
1347 >    }
1348 >    static void mustNotRemove(Collection<Item> c, int i) {
1349 >        Item[] items = defaultItems;
1350 >        Item x = (i >= 0 && i < items.length) ? items[i] : new Item(i);
1351 >        assertFalse(c.remove(x));
1352 >    }
1353 >    static void mustNotRemove(Collection<Item> c, Item i) {
1354 >        assertFalse(c.remove(i));
1355 >    }
1356 >    static void mustAdd(Collection<Item> c, int i) {
1357 >        assertTrue(c.add(itemFor(i)));
1358 >    }
1359 >    static void mustAdd(Collection<Item> c, Item i) {
1360 >        assertTrue(c.add(i));
1361 >    }
1362 >    static void mustOffer(Queue<Item> c, int i) {
1363 >        assertTrue(c.offer(itemFor(i)));
1364 >    }
1365 >    static void mustOffer(Queue<Item> c, Item i) {
1366 >        assertTrue(c.offer(i));
1367 >    }
1368  
1369      /**
1370       * Runs Runnable r with a security policy that permits precisely
# Line 1002 | Line 1445 | public class JSR166TestCase extends Test
1445          }
1446          public void refresh() {}
1447          public String toString() {
1448 <            List<Permission> ps = new ArrayList<Permission>();
1448 >            List<Permission> ps = new ArrayList<>();
1449              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1450                  ps.add(e.nextElement());
1451              return "AdjustablePolicy with permissions " + ps;
# Line 1030 | Line 1473 | public class JSR166TestCase extends Test
1473  
1474      /**
1475       * Sleeps until the given time has elapsed.
1476 <     * Throws AssertionFailedError if interrupted.
1476 >     * Throws AssertionError if interrupted.
1477       */
1478 <    void sleep(long millis) {
1478 >    static void sleep(long millis) {
1479          try {
1480              delay(millis);
1481          } catch (InterruptedException fail) {
1482 <            AssertionFailedError afe =
1040 <                new AssertionFailedError("Unexpected InterruptedException");
1041 <            afe.initCause(fail);
1042 <            throw afe;
1482 >            throw new AssertionError("Unexpected InterruptedException", fail);
1483          }
1484      }
1485  
1486      /**
1487       * Spin-waits up to the specified number of milliseconds for the given
1488       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1489 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1490       */
1491 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1492 <        long startTime = System.nanoTime();
1493 <        for (;;) {
1494 <            Thread.State s = thread.getState();
1495 <            if (s == Thread.State.BLOCKED ||
1496 <                s == Thread.State.WAITING ||
1497 <                s == Thread.State.TIMED_WAITING)
1498 <                return;
1499 <            else if (s == Thread.State.TERMINATED)
1491 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1492 >                                       Callable<Boolean> waitingForGodot) {
1493 >        for (long startTime = 0L;;) {
1494 >            switch (thread.getState()) {
1495 >            default: break;
1496 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1497 >                try {
1498 >                    if (waitingForGodot == null || waitingForGodot.call())
1499 >                        return;
1500 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1501 >                break;
1502 >            case TERMINATED:
1503                  fail("Unexpected thread termination");
1504 +            }
1505 +
1506 +            if (startTime == 0L)
1507 +                startTime = System.nanoTime();
1508              else if (millisElapsedSince(startTime) > timeoutMillis) {
1509 <                threadAssertTrue(thread.isAlive());
1510 <                return;
1509 >                assertTrue(thread.isAlive());
1510 >                if (waitingForGodot == null
1511 >                    || thread.getState() == Thread.State.RUNNABLE)
1512 >                    fail("timed out waiting for thread to enter wait state");
1513 >                else
1514 >                    fail("timed out waiting for condition, thread state="
1515 >                         + thread.getState());
1516              }
1517              Thread.yield();
1518          }
1519      }
1520  
1521      /**
1522 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1523 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1522 >     * Spin-waits up to the specified number of milliseconds for the given
1523 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1524 >     */
1525 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1526 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1527 >    }
1528 >
1529 >    /**
1530 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1531 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1532       */
1533      void waitForThreadToEnterWaitState(Thread thread) {
1534 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1534 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1535 >    }
1536 >
1537 >    /**
1538 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1539 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1540 >     * and additionally satisfy the given condition.
1541 >     */
1542 >    void waitForThreadToEnterWaitState(Thread thread,
1543 >                                       Callable<Boolean> waitingForGodot) {
1544 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1545 >    }
1546 >
1547 >    /**
1548 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1549 >     * be interrupted.  Clears the interrupt status before returning.
1550 >     */
1551 >    void awaitInterrupted() {
1552 >        for (long startTime = 0L; !Thread.interrupted(); ) {
1553 >            if (startTime == 0L)
1554 >                startTime = System.nanoTime();
1555 >            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1556 >                fail("timed out waiting for thread interrupt");
1557 >            Thread.yield();
1558 >        }
1559      }
1560  
1561      /**
# Line 1082 | Line 1567 | public class JSR166TestCase extends Test
1567          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1568      }
1569  
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
1570      /**
1571       * Checks that timed f.get() returns the expected value, and does not
1572       * wait for the timeout to elapse before returning.
1573       */
1574      <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1575          long startTime = System.nanoTime();
1576 +        T actual = null;
1577          try {
1578 <            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1578 >            actual = f.get(timeoutMillis, MILLISECONDS);
1579          } catch (Throwable fail) { threadUnexpectedException(fail); }
1580 +        assertEquals(expectedValue, actual);
1581          if (millisElapsedSince(startTime) > timeoutMillis/2)
1582 <            throw new AssertionFailedError("timed get did not return promptly");
1582 >            throw new AssertionError("timed get did not return promptly");
1583      }
1584  
1585      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1123 | Line 1597 | public class JSR166TestCase extends Test
1597      }
1598  
1599      /**
1600 +     * Returns a new started daemon Thread running the given action,
1601 +     * wrapped in a CheckedRunnable.
1602 +     */
1603 +    Thread newStartedThread(Action action) {
1604 +        return newStartedThread(checkedRunnable(action));
1605 +    }
1606 +
1607 +    /**
1608       * Waits for the specified time (in milliseconds) for the thread
1609       * to terminate (using {@link Thread#join(long)}), else interrupts
1610       * the thread (in the hope that it may terminate later) and fails.
1611       */
1612 <    void awaitTermination(Thread t, long timeoutMillis) {
1612 >    void awaitTermination(Thread thread, long timeoutMillis) {
1613          try {
1614 <            t.join(timeoutMillis);
1614 >            thread.join(timeoutMillis);
1615          } catch (InterruptedException fail) {
1616              threadUnexpectedException(fail);
1617 <        } finally {
1618 <            if (t.getState() != Thread.State.TERMINATED) {
1619 <                t.interrupt();
1620 <                fail("Test timed out");
1617 >        }
1618 >        if (thread.getState() != Thread.State.TERMINATED) {
1619 >            String detail = String.format(
1620 >                    "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1621 >                    thread, thread.getState());
1622 >            try {
1623 >                threadFail(detail);
1624 >            } finally {
1625 >                // Interrupt thread __after__ having reported its stack trace
1626 >                thread.interrupt();
1627              }
1628          }
1629      }
# Line 1163 | Line 1651 | public class JSR166TestCase extends Test
1651          }
1652      }
1653  
1654 <    public abstract class RunnableShouldThrow implements Runnable {
1655 <        protected abstract void realRun() throws Throwable;
1656 <
1657 <        final Class<?> exceptionClass;
1658 <
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 <        }
1654 >    Runnable checkedRunnable(Action action) {
1655 >        return new CheckedRunnable() {
1656 >            public void realRun() throws Throwable {
1657 >                action.run();
1658 >            }};
1659      }
1660  
1661      public abstract class ThreadShouldThrow extends Thread {
# Line 1195 | Line 1670 | public class JSR166TestCase extends Test
1670          public final void run() {
1671              try {
1672                  realRun();
1198                threadShouldThrow(exceptionClass.getSimpleName());
1673              } catch (Throwable t) {
1674                  if (! exceptionClass.isInstance(t))
1675                      threadUnexpectedException(t);
1676 +                return;
1677              }
1678 +            threadShouldThrow(exceptionClass.getSimpleName());
1679          }
1680      }
1681  
# Line 1209 | Line 1685 | public class JSR166TestCase extends Test
1685          public final void run() {
1686              try {
1687                  realRun();
1212                threadShouldThrow("InterruptedException");
1688              } catch (InterruptedException success) {
1689                  threadAssertFalse(Thread.interrupted());
1690 +                return;
1691              } catch (Throwable fail) {
1692                  threadUnexpectedException(fail);
1693              }
1694 +            threadShouldThrow("InterruptedException");
1695          }
1696      }
1697  
# Line 1226 | Line 1703 | public class JSR166TestCase extends Test
1703                  return realCall();
1704              } catch (Throwable fail) {
1705                  threadUnexpectedException(fail);
1229                return null;
1706              }
1707 <        }
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;
1707 >            throw new AssertionError("unreached");
1708          }
1709      }
1710  
# Line 1253 | Line 1712 | public class JSR166TestCase extends Test
1712          public void run() {}
1713      }
1714  
1715 <    public static class NoOpCallable implements Callable {
1715 >    public static class NoOpCallable implements Callable<Object> {
1716          public Object call() { return Boolean.TRUE; }
1717      }
1718  
# Line 1283 | Line 1742 | public class JSR166TestCase extends Test
1742              }};
1743      }
1744  
1745 <    public Runnable awaiter(final CountDownLatch latch) {
1746 <        return new CheckedRunnable() {
1747 <            public void realRun() throws InterruptedException {
1748 <                await(latch);
1749 <            }};
1745 >    class LatchAwaiter extends CheckedRunnable {
1746 >        static final int NEW = 0;
1747 >        static final int RUNNING = 1;
1748 >        static final int DONE = 2;
1749 >        final CountDownLatch latch;
1750 >        int state = NEW;
1751 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1752 >        public void realRun() throws InterruptedException {
1753 >            state = 1;
1754 >            await(latch);
1755 >            state = 2;
1756 >        }
1757      }
1758  
1759 <    public void await(CountDownLatch latch) {
1759 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1760 >        return new LatchAwaiter(latch);
1761 >    }
1762 >
1763 >    public void await(CountDownLatch latch, long timeoutMillis) {
1764 >        boolean timedOut = false;
1765          try {
1766 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1766 >            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1767          } catch (Throwable fail) {
1768              threadUnexpectedException(fail);
1769          }
1770 +        if (timedOut)
1771 +            fail("timed out waiting for CountDownLatch for "
1772 +                 + (timeoutMillis/1000) + " sec");
1773 +    }
1774 +
1775 +    public void await(CountDownLatch latch) {
1776 +        await(latch, LONG_DELAY_MS);
1777      }
1778  
1779      public void await(Semaphore semaphore) {
1780 +        boolean timedOut = false;
1781 +        try {
1782 +            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1783 +        } catch (Throwable fail) {
1784 +            threadUnexpectedException(fail);
1785 +        }
1786 +        if (timedOut)
1787 +            fail("timed out waiting for Semaphore for "
1788 +                 + (LONG_DELAY_MS/1000) + " sec");
1789 +    }
1790 +
1791 +    public void await(CyclicBarrier barrier) {
1792          try {
1793 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1793 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1794          } catch (Throwable fail) {
1795              threadUnexpectedException(fail);
1796          }
# Line 1320 | Line 1810 | public class JSR166TestCase extends Test
1810   //         long startTime = System.nanoTime();
1811   //         while (!flag.get()) {
1812   //             if (millisElapsedSince(startTime) > timeoutMillis)
1813 < //                 throw new AssertionFailedError("timed out");
1813 > //                 throw new AssertionError("timed out");
1814   //             Thread.yield();
1815   //         }
1816   //     }
# Line 1329 | Line 1819 | public class JSR166TestCase extends Test
1819          public String call() { throw new NullPointerException(); }
1820      }
1821  
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
1822      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1823          return new CheckedRunnable() {
1824              protected void realRun() {
# Line 1387 | Line 1828 | public class JSR166TestCase extends Test
1828              }};
1829      }
1830  
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
1831      /**
1832       * For use as ThreadFactory in constructors
1833       */
# Line 1416 | Line 1841 | public class JSR166TestCase extends Test
1841          boolean isDone();
1842      }
1843  
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
1844      public static class TrackedNoOpRunnable implements Runnable {
1845          public volatile boolean done = false;
1846          public void run() {
# Line 1476 | Line 1848 | public class JSR166TestCase extends Test
1848          }
1849      }
1850  
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
1851      /**
1852       * Analog of CheckedRunnable for RecursiveAction
1853       */
# Line 1513 | Line 1874 | public class JSR166TestCase extends Test
1874                  return realCompute();
1875              } catch (Throwable fail) {
1876                  threadUnexpectedException(fail);
1516                return null;
1877              }
1878 +            throw new AssertionError("unreached");
1879          }
1880      }
1881  
# Line 1528 | Line 1889 | public class JSR166TestCase extends Test
1889  
1890      /**
1891       * A CyclicBarrier that uses timed await and fails with
1892 <     * AssertionFailedErrors instead of throwing checked exceptions.
1892 >     * AssertionErrors instead of throwing checked exceptions.
1893       */
1894 <    public class CheckedBarrier extends CyclicBarrier {
1894 >    public static class CheckedBarrier extends CyclicBarrier {
1895          public CheckedBarrier(int parties) { super(parties); }
1896  
1897          public int await() {
1898              try {
1899 <                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1899 >                return super.await(LONGER_DELAY_MS, MILLISECONDS);
1900              } catch (TimeoutException timedOut) {
1901 <                throw new AssertionFailedError("timed out");
1901 >                throw new AssertionError("timed out");
1902              } catch (Exception fail) {
1903 <                AssertionFailedError afe =
1543 <                    new AssertionFailedError("Unexpected exception: " + fail);
1544 <                afe.initCause(fail);
1545 <                throw afe;
1903 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1904              }
1905          }
1906      }
1907  
1908 <    void checkEmpty(BlockingQueue q) {
1908 >    void checkEmpty(BlockingQueue<?> q) {
1909          try {
1910              assertTrue(q.isEmpty());
1911              assertEquals(0, q.size());
1912              assertNull(q.peek());
1913              assertNull(q.poll());
1914 <            assertNull(q.poll(0, MILLISECONDS));
1914 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1915              assertEquals(q.toString(), "[]");
1916              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1917              assertFalse(q.iterator().hasNext());
# Line 1595 | Line 1953 | public class JSR166TestCase extends Test
1953      }
1954  
1955      @SuppressWarnings("unchecked")
1956 +    void assertImmutable(Object o) {
1957 +        if (o instanceof Collection) {
1958 +            assertThrows(
1959 +                UnsupportedOperationException.class,
1960 +                () -> ((Collection) o).add(null));
1961 +        }
1962 +    }
1963 +
1964 +    @SuppressWarnings("unchecked")
1965      <T> T serialClone(T o) {
1966 +        T clone = null;
1967          try {
1968              ObjectInputStream ois = new ObjectInputStream
1969                  (new ByteArrayInputStream(serialBytes(o)));
1970 <            T clone = (T) ois.readObject();
1603 <            assertSame(o.getClass(), clone.getClass());
1604 <            return clone;
1970 >            clone = (T) ois.readObject();
1971          } catch (Throwable fail) {
1972              threadUnexpectedException(fail);
1973 +        }
1974 +        if (o == clone) assertImmutable(o);
1975 +        else assertSame(o.getClass(), clone.getClass());
1976 +        return clone;
1977 +    }
1978 +
1979 +    /**
1980 +     * A version of serialClone that leaves error handling (for
1981 +     * e.g. NotSerializableException) up to the caller.
1982 +     */
1983 +    @SuppressWarnings("unchecked")
1984 +    <T> T serialClonePossiblyFailing(T o)
1985 +        throws ReflectiveOperationException, java.io.IOException {
1986 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1987 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1988 +        oos.writeObject(o);
1989 +        oos.flush();
1990 +        oos.close();
1991 +        ObjectInputStream ois = new ObjectInputStream
1992 +            (new ByteArrayInputStream(bos.toByteArray()));
1993 +        T clone = (T) ois.readObject();
1994 +        if (o == clone) assertImmutable(o);
1995 +        else assertSame(o.getClass(), clone.getClass());
1996 +        return clone;
1997 +    }
1998 +
1999 +    /**
2000 +     * If o implements Cloneable and has a public clone method,
2001 +     * returns a clone of o, else null.
2002 +     */
2003 +    @SuppressWarnings("unchecked")
2004 +    <T> T cloneableClone(T o) {
2005 +        if (!(o instanceof Cloneable)) return null;
2006 +        final T clone;
2007 +        try {
2008 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
2009 +        } catch (NoSuchMethodException ok) {
2010              return null;
2011 +        } catch (ReflectiveOperationException unexpected) {
2012 +            throw new Error(unexpected);
2013          }
2014 +        assertNotSame(o, clone); // not 100% guaranteed by spec
2015 +        assertSame(o.getClass(), clone.getClass());
2016 +        return clone;
2017      }
2018  
2019      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
2020 <                             Runnable... throwingActions) {
2021 <        for (Runnable throwingAction : throwingActions) {
2020 >                             Action... throwingActions) {
2021 >        for (Action throwingAction : throwingActions) {
2022              boolean threw = false;
2023              try { throwingAction.run(); }
2024              catch (Throwable t) {
2025                  threw = true;
2026 <                if (!expectedExceptionClass.isInstance(t)) {
2027 <                    AssertionFailedError afe =
2028 <                        new AssertionFailedError
2029 <                        ("Expected " + expectedExceptionClass.getName() +
2030 <                         ", got " + t.getClass().getName());
1623 <                    afe.initCause(t);
1624 <                    threadUnexpectedException(afe);
1625 <                }
2026 >                if (!expectedExceptionClass.isInstance(t))
2027 >                    throw new AssertionError(
2028 >                            "Expected " + expectedExceptionClass.getName() +
2029 >                            ", got " + t.getClass().getName(),
2030 >                            t);
2031              }
2032              if (!threw)
2033                  shouldThrow(expectedExceptionClass.getName());
# Line 1636 | Line 2041 | public class JSR166TestCase extends Test
2041          } catch (NoSuchElementException success) {}
2042          assertFalse(it.hasNext());
2043      }
2044 +
2045 +    public <T> Callable<T> callableThrowing(final Exception ex) {
2046 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
2047 +    }
2048 +
2049 +    public Runnable runnableThrowing(final RuntimeException ex) {
2050 +        return new Runnable() { public void run() { throw ex; }};
2051 +    }
2052 +
2053 +    /** A reusable thread pool to be shared by tests. */
2054 +    static final ExecutorService cachedThreadPool =
2055 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
2056 +                               1000L, MILLISECONDS,
2057 +                               new SynchronousQueue<Runnable>());
2058 +
2059 +    static <T> void shuffle(T[] array) {
2060 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
2061 +    }
2062 +
2063 +    /**
2064 +     * Returns the same String as would be returned by {@link
2065 +     * Object#toString}, whether or not the given object's class
2066 +     * overrides toString().
2067 +     *
2068 +     * @see System#identityHashCode
2069 +     */
2070 +    static String identityString(Object x) {
2071 +        return x.getClass().getName()
2072 +            + "@" + Integer.toHexString(System.identityHashCode(x));
2073 +    }
2074 +
2075 +    // --- Shared assertions for Executor tests ---
2076 +
2077 +    /**
2078 +     * Returns maximum number of tasks that can be submitted to given
2079 +     * pool (with bounded queue) before saturation (when submission
2080 +     * throws RejectedExecutionException).
2081 +     */
2082 +    static final int saturatedSize(ThreadPoolExecutor pool) {
2083 +        BlockingQueue<Runnable> q = pool.getQueue();
2084 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
2085 +    }
2086 +
2087 +    @SuppressWarnings("FutureReturnValueIgnored")
2088 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
2089 +        try {
2090 +            e.execute((Runnable) null);
2091 +            shouldThrow();
2092 +        } catch (NullPointerException success) {}
2093 +
2094 +        if (! (e instanceof ExecutorService)) return;
2095 +        ExecutorService es = (ExecutorService) e;
2096 +        try {
2097 +            es.submit((Runnable) null);
2098 +            shouldThrow();
2099 +        } catch (NullPointerException success) {}
2100 +        try {
2101 +            es.submit((Runnable) null, Boolean.TRUE);
2102 +            shouldThrow();
2103 +        } catch (NullPointerException success) {}
2104 +        try {
2105 +            es.submit((Callable<?>) null);
2106 +            shouldThrow();
2107 +        } catch (NullPointerException success) {}
2108 +
2109 +        if (! (e instanceof ScheduledExecutorService)) return;
2110 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
2111 +        try {
2112 +            ses.schedule((Runnable) null,
2113 +                         randomTimeout(), randomTimeUnit());
2114 +            shouldThrow();
2115 +        } catch (NullPointerException success) {}
2116 +        try {
2117 +            ses.schedule((Callable<?>) null,
2118 +                         randomTimeout(), randomTimeUnit());
2119 +            shouldThrow();
2120 +        } catch (NullPointerException success) {}
2121 +        try {
2122 +            ses.scheduleAtFixedRate((Runnable) null,
2123 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2124 +            shouldThrow();
2125 +        } catch (NullPointerException success) {}
2126 +        try {
2127 +            ses.scheduleWithFixedDelay((Runnable) null,
2128 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2129 +            shouldThrow();
2130 +        } catch (NullPointerException success) {}
2131 +    }
2132 +
2133 +    void setRejectedExecutionHandler(
2134 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2135 +        p.setRejectedExecutionHandler(handler);
2136 +        assertSame(handler, p.getRejectedExecutionHandler());
2137 +    }
2138 +
2139 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2140 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2141 +        final long savedTaskCount = p.getTaskCount();
2142 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2143 +        final int savedQueueSize = p.getQueue().size();
2144 +        final boolean stock = (p.getClass().getClassLoader() == null);
2145 +
2146 +        Runnable r = () -> {};
2147 +        Callable<Boolean> c = () -> Boolean.TRUE;
2148 +
2149 +        class Recorder implements RejectedExecutionHandler {
2150 +            public volatile Runnable r = null;
2151 +            public volatile ThreadPoolExecutor p = null;
2152 +            public void reset() { r = null; p = null; }
2153 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2154 +                assertNull(this.r);
2155 +                assertNull(this.p);
2156 +                this.r = r;
2157 +                this.p = p;
2158 +            }
2159 +        }
2160 +
2161 +        // check custom handler is invoked exactly once per task
2162 +        Recorder recorder = new Recorder();
2163 +        setRejectedExecutionHandler(p, recorder);
2164 +        for (int i = 2; i--> 0; ) {
2165 +            recorder.reset();
2166 +            p.execute(r);
2167 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2168 +                assertSame(r, recorder.r);
2169 +            assertSame(p, recorder.p);
2170 +
2171 +            recorder.reset();
2172 +            assertFalse(p.submit(r).isDone());
2173 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2174 +            assertSame(p, recorder.p);
2175 +
2176 +            recorder.reset();
2177 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2178 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2179 +            assertSame(p, recorder.p);
2180 +
2181 +            recorder.reset();
2182 +            assertFalse(p.submit(c).isDone());
2183 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2184 +            assertSame(p, recorder.p);
2185 +
2186 +            if (p instanceof ScheduledExecutorService) {
2187 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2188 +                ScheduledFuture<?> future;
2189 +
2190 +                recorder.reset();
2191 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2192 +                assertFalse(future.isDone());
2193 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2194 +                assertSame(p, recorder.p);
2195 +
2196 +                recorder.reset();
2197 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2198 +                assertFalse(future.isDone());
2199 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2200 +                assertSame(p, recorder.p);
2201 +
2202 +                recorder.reset();
2203 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2204 +                assertFalse(future.isDone());
2205 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2206 +                assertSame(p, recorder.p);
2207 +
2208 +                recorder.reset();
2209 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2210 +                assertFalse(future.isDone());
2211 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2212 +                assertSame(p, recorder.p);
2213 +            }
2214 +        }
2215 +
2216 +        // Checking our custom handler above should be sufficient, but
2217 +        // we add some integration tests of standard handlers.
2218 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2219 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2220 +
2221 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2222 +        try {
2223 +            p.execute(setThread);
2224 +            shouldThrow();
2225 +        } catch (RejectedExecutionException success) {}
2226 +        assertNull(thread.get());
2227 +
2228 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2229 +        p.execute(setThread);
2230 +        assertNull(thread.get());
2231 +
2232 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2233 +        p.execute(setThread);
2234 +        if (p.isShutdown())
2235 +            assertNull(thread.get());
2236 +        else
2237 +            assertSame(Thread.currentThread(), thread.get());
2238 +
2239 +        setRejectedExecutionHandler(p, savedHandler);
2240 +
2241 +        // check that pool was not perturbed by handlers
2242 +        assertEquals(savedTaskCount, p.getTaskCount());
2243 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2244 +        assertEquals(savedQueueSize, p.getQueue().size());
2245 +    }
2246 +
2247 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2248 +        assertEquals(x, y);
2249 +        assertEquals(y, x);
2250 +        assertEquals(x.isEmpty(), y.isEmpty());
2251 +        assertEquals(x.size(), y.size());
2252 +        if (x instanceof List) {
2253 +            assertEquals(x.toString(), y.toString());
2254 +        }
2255 +        if (x instanceof List || x instanceof Set) {
2256 +            assertEquals(x.hashCode(), y.hashCode());
2257 +        }
2258 +        if (x instanceof List || x instanceof Deque) {
2259 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2260 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2261 +                                     y.toArray(new Object[0])));
2262 +        }
2263 +    }
2264 +
2265 +    /**
2266 +     * A weaker form of assertCollectionsEquals which does not insist
2267 +     * that the two collections satisfy Object#equals(Object), since
2268 +     * they may use identity semantics as Deques do.
2269 +     */
2270 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2271 +        if (x instanceof List || x instanceof Set)
2272 +            assertCollectionsEquals(x, y);
2273 +        else {
2274 +            assertEquals(x.isEmpty(), y.isEmpty());
2275 +            assertEquals(x.size(), y.size());
2276 +            assertEquals(new HashSet<Object>(x), new HashSet<Object>(y));
2277 +            if (x instanceof Deque) {
2278 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2279 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2280 +                                         y.toArray(new Object[0])));
2281 +            }
2282 +        }
2283 +    }
2284   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines