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.104 by dl, Thu Mar 21 00:26:43 2013 UTC vs.
Revision 1.269 by jsr166, Thu Sep 26 20:48:52 2019 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
8   */
9  
10 < import junit.framework.*;
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;
48   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;
56   import java.lang.reflect.Method;
57 + import java.lang.reflect.Modifier;
58 + import java.security.CodeSource;
59 + import java.security.Permission;
60 + import java.security.PermissionCollection;
61 + import java.security.Permissions;
62 + import java.security.Policy;
63 + 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.concurrent.*;
77 > import java.util.Set;
78 > import java.util.concurrent.BlockingQueue;
79 > import java.util.concurrent.Callable;
80 > import java.util.concurrent.CountDownLatch;
81 > import java.util.concurrent.CyclicBarrier;
82 > import java.util.concurrent.ExecutionException;
83 > import java.util.concurrent.Executor;
84 > import java.util.concurrent.Executors;
85 > import java.util.concurrent.ExecutorService;
86 > import java.util.concurrent.ForkJoinPool;
87 > import java.util.concurrent.Future;
88 > import java.util.concurrent.FutureTask;
89 > import java.util.concurrent.RecursiveAction;
90 > import java.util.concurrent.RecursiveTask;
91 > import java.util.concurrent.RejectedExecutionException;
92 > import java.util.concurrent.RejectedExecutionHandler;
93 > import java.util.concurrent.Semaphore;
94 > import java.util.concurrent.ScheduledExecutorService;
95 > import java.util.concurrent.ScheduledFuture;
96 > import java.util.concurrent.SynchronousQueue;
97 > import java.util.concurrent.ThreadFactory;
98 > import java.util.concurrent.ThreadLocalRandom;
99 > import java.util.concurrent.ThreadPoolExecutor;
100 > import java.util.concurrent.TimeUnit;
101 > import java.util.concurrent.TimeoutException;
102   import java.util.concurrent.atomic.AtomicBoolean;
103   import java.util.concurrent.atomic.AtomicReference;
104 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
105 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
106 < import java.security.CodeSource;
107 < import java.security.Permission;
108 < import java.security.PermissionCollection;
109 < import java.security.Permissions;
33 < import java.security.Policy;
34 < import java.security.ProtectionDomain;
35 < import java.security.SecurityPermission;
104 > import java.util.regex.Pattern;
105 >
106 > import junit.framework.Test;
107 > import junit.framework.TestCase;
108 > import junit.framework.TestResult;
109 > import junit.framework.TestSuite;
110  
111   /**
112   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 44 | Line 118 | import java.security.SecurityPermission;
118   *
119   * <ol>
120   *
121 < * <li> All assertions in code running in generated threads must use
122 < * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
123 < * #threadAssertEquals}, or {@link #threadAssertNull}, (not
124 < * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
125 < * particularly recommended) for other code to use these forms too.
126 < * Only the most typically used JUnit assertion methods are defined
127 < * this way, but enough to live with.</li>
121 > * <li>All code not running in the main test thread (manually spawned threads
122 > * or the common fork join pool) must be checked for failure (and completion!).
123 > * Mechanisms that can be used to ensure this are:
124 > *   <ol>
125 > *   <li>Signalling via a synchronizer like AtomicInteger or CountDownLatch
126 > *    that the task completed normally, which is checked before returning from
127 > *    the test method in the main thread.
128 > *   <li>Using the forms {@link #threadFail}, {@link #threadAssertTrue},
129 > *    or {@link #threadAssertNull}, (not {@code fail}, {@code assertTrue}, etc.)
130 > *    Only the most typically used JUnit assertion methods are defined
131 > *    this way, but enough to live with.
132 > *   <li>Recording failure explicitly using {@link #threadUnexpectedException}
133 > *    or {@link #threadRecordFailure}.
134 > *   <li>Using a wrapper like CheckedRunnable that uses one the mechanisms above.
135 > *   </ol>
136   *
137 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
137 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
138   * to invoke {@code super.setUp} and {@code super.tearDown} within
139   * them. These methods are used to clear and check for thread
140 < * assertion failures.</li>
140 > * assertion failures.
141   *
142   * <li>All delays and timeouts must use one of the constants {@code
143   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 66 | Line 148 | import java.security.SecurityPermission;
148   * is always discriminable as larger than SHORT and smaller than
149   * MEDIUM.  And so on. These constants are set to conservative values,
150   * but even so, if there is ever any doubt, they can all be increased
151 < * in one spot to rerun tests on slower platforms.</li>
151 > * in one spot to rerun tests on slower platforms.
152   *
153 < * <li> All threads generated must be joined inside each test case
153 > * <li>All threads generated must be joined inside each test case
154   * method (or {@code fail} to do so) before returning from the
155   * method. The {@code joinPool} method can be used to do this when
156 < * using Executors.</li>
156 > * using Executors.
157   *
158   * </ol>
159   *
160   * <p><b>Other notes</b>
161   * <ul>
162   *
163 < * <li> Usually, there is one testcase method per JSR166 method
163 > * <li>Usually, there is one testcase method per JSR166 method
164   * covering "normal" operation, and then as many exception-testing
165   * methods as there are exceptions the method can throw. Sometimes
166   * there are multiple tests per JSR166 method when the different
167   * "normal" behaviors differ significantly. And sometimes testcases
168 < * cover multiple methods when they cannot be tested in
87 < * isolation.</li>
168 > * cover multiple methods when they cannot be tested in isolation.
169   *
170 < * <li> The documentation style for testcases is to provide as javadoc
170 > * <li>The documentation style for testcases is to provide as javadoc
171   * a simple sentence or two describing the property that the testcase
172   * method purports to test. The javadocs do not say anything about how
173 < * the property is tested. To find out, read the code.</li>
173 > * the property is tested. To find out, read the code.
174   *
175 < * <li> These tests are "conformance tests", and do not attempt to
175 > * <li>These tests are "conformance tests", and do not attempt to
176   * test throughput, latency, scalability or other performance factors
177   * (see the separate "jtreg" tests for a set intended to check these
178   * for the most central aspects of functionality.) So, most tests use
179   * the smallest sensible numbers of threads, collection sizes, etc
180 < * needed to check basic conformance.</li>
180 > * needed to check basic conformance.
181   *
182   * <li>The test classes currently do not declare inclusion in
183   * any particular package to simplify things for people integrating
184 < * them in TCK test suites.</li>
184 > * them in TCK test suites.
185   *
186 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
187 < * runs all JSR166 unit tests.</li>
186 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
187 > * runs all JSR166 unit tests.
188   *
189   * </ul>
190   */
# Line 115 | Line 196 | public class JSR166TestCase extends Test
196          Boolean.getBoolean("jsr166.expensiveTests");
197  
198      /**
199 +     * If true, also run tests that are not part of the official tck
200 +     * because they test unspecified implementation details.
201 +     */
202 +    protected static final boolean testImplementationDetails =
203 +        Boolean.getBoolean("jsr166.testImplementationDetails");
204 +
205 +    /**
206       * If true, report on stdout all "slow" tests, that is, ones that
207       * take more than profileThreshold milliseconds to execute.
208       */
# Line 128 | Line 216 | public class JSR166TestCase extends Test
216      private static final long profileThreshold =
217          Long.getLong("jsr166.profileThreshold", 100);
218  
219 +    /**
220 +     * The number of repetitions per test (for tickling rare bugs).
221 +     */
222 +    private static final int runsPerTest =
223 +        Integer.getInteger("jsr166.runsPerTest", 1);
224 +
225 +    /**
226 +     * The number of repetitions of the test suite (for finding leaks?).
227 +     */
228 +    private static final int suiteRuns =
229 +        Integer.getInteger("jsr166.suiteRuns", 1);
230 +
231 +    /**
232 +     * Returns the value of the system property, or NaN if not defined.
233 +     */
234 +    private static float systemPropertyValue(String name) {
235 +        String floatString = System.getProperty(name);
236 +        if (floatString == null)
237 +            return Float.NaN;
238 +        try {
239 +            return Float.parseFloat(floatString);
240 +        } catch (NumberFormatException ex) {
241 +            throw new IllegalArgumentException(
242 +                String.format("Bad float value in system property %s=%s",
243 +                              name, floatString));
244 +        }
245 +    }
246 +
247 +    private static final ThreadMXBean THREAD_MXBEAN
248 +        = ManagementFactory.getThreadMXBean();
249 +
250 +    /**
251 +     * The scaling factor to apply to standard delays used in tests.
252 +     * May be initialized from any of:
253 +     * - the "jsr166.delay.factor" system property
254 +     * - the "test.timeout.factor" system property (as used by jtreg)
255 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
256 +     * - hard-coded fuzz factor when using a known slowpoke VM
257 +     */
258 +    private static final float delayFactor = delayFactor();
259 +
260 +    private static float delayFactor() {
261 +        float x;
262 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
263 +            return x;
264 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
265 +            return x;
266 +        String prop = System.getProperty("java.vm.version");
267 +        if (prop != null && prop.matches(".*debug.*"))
268 +            return 4.0f; // How much slower is fastdebug than product?!
269 +        return 1.0f;
270 +    }
271 +
272 +    public JSR166TestCase() { super(); }
273 +    public JSR166TestCase(String name) { super(name); }
274 +
275 +    /**
276 +     * A filter for tests to run, matching strings of the form
277 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
278 +     * Usefully combined with jsr166.runsPerTest.
279 +     */
280 +    private static final Pattern methodFilter = methodFilter();
281 +
282 +    private static Pattern methodFilter() {
283 +        String regex = System.getProperty("jsr166.methodFilter");
284 +        return (regex == null) ? null : Pattern.compile(regex);
285 +    }
286 +
287 +    // Instrumentation to debug very rare, but very annoying hung test runs.
288 +    static volatile TestCase currentTestCase;
289 +    // static volatile int currentRun = 0;
290 +    static {
291 +        Runnable wedgedTestDetector = new Runnable() { public void run() {
292 +            // Avoid spurious reports with enormous runsPerTest.
293 +            // A single test case run should never take more than 1 second.
294 +            // But let's cap it at the high end too ...
295 +            final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1)
296 +                * Math.max((int) delayFactor, 1);
297 +            final int timeoutMinutes = Math.min(15, timeoutMinutesMin);
298 +            for (TestCase lastTestCase = currentTestCase;;) {
299 +                try { MINUTES.sleep(timeoutMinutes); }
300 +                catch (InterruptedException unexpected) { break; }
301 +                if (lastTestCase == currentTestCase) {
302 +                    System.err.printf(
303 +                        "Looks like we're stuck running test: %s%n",
304 +                        lastTestCase);
305 + //                     System.err.printf(
306 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
307 + //                         lastTestCase, currentRun, runsPerTest);
308 + //                     System.err.println("availableProcessors=" +
309 + //                         Runtime.getRuntime().availableProcessors());
310 + //                     System.err.printf("cpu model = %s%n", cpuModel());
311 +                    dumpTestThreads();
312 +                    // one stack dump is probably enough; more would be spam
313 +                    break;
314 +                }
315 +                lastTestCase = currentTestCase;
316 +            }}};
317 +        Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector");
318 +        thread.setDaemon(true);
319 +        thread.start();
320 +    }
321 +
322 + //     public static String cpuModel() {
323 + //         try {
324 + //             java.util.regex.Matcher matcher
325 + //               = Pattern.compile("model name\\s*: (.*)")
326 + //                 .matcher(new String(
327 + //                     java.nio.file.Files.readAllBytes(
328 + //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
329 + //             matcher.find();
330 + //             return matcher.group(1);
331 + //         } catch (Exception ex) { return null; }
332 + //     }
333 +
334 +    public void runBare() throws Throwable {
335 +        currentTestCase = this;
336 +        if (methodFilter == null
337 +            || methodFilter.matcher(toString()).find())
338 +            super.runBare();
339 +    }
340 +
341      protected void runTest() throws Throwable {
342 <        if (profileTests)
343 <            runTestProfiled();
344 <        else
345 <            super.runTest();
342 >        for (int i = 0; i < runsPerTest; i++) {
343 >            // currentRun = i;
344 >            if (profileTests)
345 >                runTestProfiled();
346 >            else
347 >                super.runTest();
348 >        }
349      }
350  
351      protected void runTestProfiled() throws Throwable {
352 <        long t0 = System.nanoTime();
353 <        try {
352 >        for (int i = 0; i < 2; i++) {
353 >            long startTime = System.nanoTime();
354              super.runTest();
355 <        } finally {
356 <            long elapsedMillis =
357 <                (System.nanoTime() - t0) / (1000L * 1000L);
358 <            if (elapsedMillis >= profileThreshold)
359 <                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
355 >            long elapsedMillis = millisElapsedSince(startTime);
356 >            if (elapsedMillis < profileThreshold)
357 >                break;
358 >            // Never report first run of any test; treat it as a
359 >            // warmup run, notably to trigger all needed classloading,
360 >            if (i > 0)
361 >                System.out.printf("%s: %d%n", toString(), elapsedMillis);
362          }
363      }
364  
365      /**
366       * Runs all JSR166 unit tests using junit.textui.TestRunner.
152     * Optional command line arg provides the number of iterations to
153     * repeat running the tests.
367       */
368      public static void main(String[] args) {
369 +        main(suite(), args);
370 +    }
371 +
372 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
373 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
374 +        long runTime;
375 +        public void startTest(Test test) {}
376 +        protected void printHeader(long runTime) {
377 +            this.runTime = runTime; // defer printing for later
378 +        }
379 +        protected void printFooter(TestResult result) {
380 +            if (result.wasSuccessful()) {
381 +                getWriter().println("OK (" + result.runCount() + " tests)"
382 +                    + "  Time: " + elapsedTimeAsString(runTime));
383 +            } else {
384 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
385 +                super.printFooter(result);
386 +            }
387 +        }
388 +    }
389 +
390 +    /**
391 +     * Returns a TestRunner that doesn't bother with unnecessary
392 +     * fluff, like printing a "." for each test case.
393 +     */
394 +    static junit.textui.TestRunner newPithyTestRunner() {
395 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
396 +        runner.setPrinter(new PithyResultPrinter(System.out));
397 +        return runner;
398 +    }
399 +
400 +    /**
401 +     * Runs all unit tests in the given test suite.
402 +     * Actual behavior influenced by jsr166.* system properties.
403 +     */
404 +    static void main(Test suite, String[] args) {
405          if (useSecurityManager) {
406              System.err.println("Setting a permissive security manager");
407              Policy.setPolicy(permissivePolicy());
408              System.setSecurityManager(new SecurityManager());
409          }
410 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
411 <
412 <        Test s = suite();
413 <        for (int i = 0; i < iters; ++i) {
165 <            junit.textui.TestRunner.run(s);
410 >        for (int i = 0; i < suiteRuns; i++) {
411 >            TestResult result = newPithyTestRunner().doRun(suite);
412 >            if (!result.wasSuccessful())
413 >                System.exit(1);
414              System.gc();
415              System.runFinalization();
416          }
169        System.exit(0);
417      }
418  
419      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 187 | Line 434 | public class JSR166TestCase extends Test
434          for (String testClassName : testClassNames) {
435              try {
436                  Class<?> testClass = Class.forName(testClassName);
437 <                Method m = testClass.getDeclaredMethod("suite",
191 <                                                       new Class<?>[0]);
437 >                Method m = testClass.getDeclaredMethod("suite");
438                  suite.addTest(newTestSuite((Test)m.invoke(null)));
439 <            } catch (Exception e) {
440 <                throw new Error("Missing test class", e);
439 >            } catch (ReflectiveOperationException e) {
440 >                throw new AssertionError("Missing test class", e);
441              }
442          }
443      }
444  
445      public static final double JAVA_CLASS_VERSION;
446 +    public static final String JAVA_SPECIFICATION_VERSION;
447      static {
448          try {
449              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
450                  new java.security.PrivilegedAction<Double>() {
451                  public Double run() {
452                      return Double.valueOf(System.getProperty("java.class.version"));}});
453 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
454 +                new java.security.PrivilegedAction<String>() {
455 +                public String run() {
456 +                    return System.getProperty("java.specification.version");}});
457          } catch (Throwable t) {
458              throw new Error(t);
459          }
460      }
461  
462 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
463 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
464 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
462 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
463 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
464 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
465 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
466 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
467 >    public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
468 >    public static boolean atLeastJava12() { return JAVA_CLASS_VERSION >= 56.0; }
469 >    public static boolean atLeastJava13() { return JAVA_CLASS_VERSION >= 57.0; }
470 >    public static boolean atLeastJava14() { return JAVA_CLASS_VERSION >= 58.0; }
471 >    public static boolean atLeastJava15() { return JAVA_CLASS_VERSION >= 59.0; }
472 >    public static boolean atLeastJava16() { return JAVA_CLASS_VERSION >= 60.0; }
473 >    public static boolean atLeastJava17() { return JAVA_CLASS_VERSION >= 61.0; }
474  
475      /**
476       * Collects all JSR166 unit tests as one suite.
# Line 231 | Line 491 | public class JSR166TestCase extends Test
491              AbstractQueuedLongSynchronizerTest.suite(),
492              ArrayBlockingQueueTest.suite(),
493              ArrayDequeTest.suite(),
494 +            ArrayListTest.suite(),
495              AtomicBooleanTest.suite(),
496              AtomicIntegerArrayTest.suite(),
497              AtomicIntegerFieldUpdaterTest.suite(),
# Line 253 | Line 514 | public class JSR166TestCase extends Test
514              CopyOnWriteArrayListTest.suite(),
515              CopyOnWriteArraySetTest.suite(),
516              CountDownLatchTest.suite(),
517 +            CountedCompleterTest.suite(),
518              CyclicBarrierTest.suite(),
519              DelayQueueTest.suite(),
520              EntryTest.suite(),
# Line 260 | Line 522 | public class JSR166TestCase extends Test
522              ExecutorsTest.suite(),
523              ExecutorCompletionServiceTest.suite(),
524              FutureTaskTest.suite(),
525 +            HashtableTest.suite(),
526              LinkedBlockingDequeTest.suite(),
527              LinkedBlockingQueueTest.suite(),
528              LinkedListTest.suite(),
# Line 281 | Line 544 | public class JSR166TestCase extends Test
544              TreeMapTest.suite(),
545              TreeSetTest.suite(),
546              TreeSubMapTest.suite(),
547 <            TreeSubSetTest.suite());
547 >            TreeSubSetTest.suite(),
548 >            VectorTest.suite());
549  
550          // Java8+ test classes
551          if (atLeastJava8()) {
552              String[] java8TestClassNames = {
553 +                "ArrayDeque8Test",
554 +                "Atomic8Test",
555                  "CompletableFutureTest",
556 <                "CountedCompleterTest",
556 >                "ConcurrentHashMap8Test",
557 >                "CountedCompleter8Test",
558                  "DoubleAccumulatorTest",
559                  "DoubleAdderTest",
560                  "ForkJoinPool8Test",
561 +                "ForkJoinTask8Test",
562 +                "HashMapTest",
563 +                "LinkedBlockingDeque8Test",
564 +                "LinkedBlockingQueue8Test",
565 +                "LinkedHashMapTest",
566                  "LongAccumulatorTest",
567                  "LongAdderTest",
568 +                "SplittableRandomTest",
569                  "StampedLockTest",
570 +                "SubmissionPublisherTest",
571 +                "ThreadLocalRandom8Test",
572 +                "TimeUnit8Test",
573              };
574              addNamedTestClasses(suite, java8TestClassNames);
575          }
576  
577 +        // Java9+ test classes
578 +        if (atLeastJava9()) {
579 +            String[] java9TestClassNames = {
580 +                "AtomicBoolean9Test",
581 +                "AtomicInteger9Test",
582 +                "AtomicIntegerArray9Test",
583 +                "AtomicLong9Test",
584 +                "AtomicLongArray9Test",
585 +                "AtomicReference9Test",
586 +                "AtomicReferenceArray9Test",
587 +                "ExecutorCompletionService9Test",
588 +                "ForkJoinPool9Test",
589 +            };
590 +            addNamedTestClasses(suite, java9TestClassNames);
591 +        }
592 +
593          return suite;
594      }
595  
596 +    /** Returns list of junit-style test method names in given class. */
597 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
598 +        Method[] methods = testClass.getDeclaredMethods();
599 +        ArrayList<String> names = new ArrayList<>(methods.length);
600 +        for (Method method : methods) {
601 +            if (method.getName().startsWith("test")
602 +                && Modifier.isPublic(method.getModifiers())
603 +                // method.getParameterCount() requires jdk8+
604 +                && method.getParameterTypes().length == 0) {
605 +                names.add(method.getName());
606 +            }
607 +        }
608 +        return names;
609 +    }
610 +
611 +    /**
612 +     * Returns junit-style testSuite for the given test class, but
613 +     * parameterized by passing extra data to each test.
614 +     */
615 +    public static <ExtraData> Test parameterizedTestSuite
616 +        (Class<? extends JSR166TestCase> testClass,
617 +         Class<ExtraData> dataClass,
618 +         ExtraData data) {
619 +        try {
620 +            TestSuite suite = new TestSuite();
621 +            Constructor c =
622 +                testClass.getDeclaredConstructor(dataClass, String.class);
623 +            for (String methodName : testMethodNames(testClass))
624 +                suite.addTest((Test) c.newInstance(data, methodName));
625 +            return suite;
626 +        } catch (ReflectiveOperationException e) {
627 +            throw new AssertionError(e);
628 +        }
629 +    }
630 +
631 +    /**
632 +     * Returns junit-style testSuite for the jdk8 extension of the
633 +     * given test class, but parameterized by passing extra data to
634 +     * each test.  Uses reflection to allow compilation in jdk7.
635 +     */
636 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
637 +        (Class<? extends JSR166TestCase> testClass,
638 +         Class<ExtraData> dataClass,
639 +         ExtraData data) {
640 +        if (atLeastJava8()) {
641 +            String name = testClass.getName();
642 +            String name8 = name.replaceAll("Test$", "8Test");
643 +            if (name.equals(name8)) throw new AssertionError(name);
644 +            try {
645 +                return (Test)
646 +                    Class.forName(name8)
647 +                    .getMethod("testSuite", dataClass)
648 +                    .invoke(null, data);
649 +            } catch (ReflectiveOperationException e) {
650 +                throw new AssertionError(e);
651 +            }
652 +        } else {
653 +            return new TestSuite();
654 +        }
655 +    }
656 +
657 +    // Delays for timing-dependent tests, in milliseconds.
658  
659      public static long SHORT_DELAY_MS;
660      public static long SMALL_DELAY_MS;
661      public static long MEDIUM_DELAY_MS;
662      public static long LONG_DELAY_MS;
663  
664 +    /**
665 +     * A delay significantly longer than LONG_DELAY_MS.
666 +     * Use this in a thread that is waited for via awaitTermination(Thread).
667 +     */
668 +    public static long LONGER_DELAY_MS;
669 +
670 +    private static final long RANDOM_TIMEOUT;
671 +    private static final long RANDOM_EXPIRED_TIMEOUT;
672 +    private static final TimeUnit RANDOM_TIMEUNIT;
673 +    static {
674 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
675 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
676 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
677 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
678 +        TimeUnit[] timeUnits = TimeUnit.values();
679 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
680 +    }
681 +
682 +    /**
683 +     * Returns a timeout for use when any value at all will do.
684 +     */
685 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
686 +
687 +    /**
688 +     * Returns a timeout that means "no waiting", i.e. not positive.
689 +     */
690 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
691 +
692 +    /**
693 +     * Returns a random non-null TimeUnit.
694 +     */
695 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
696 +
697 +    /**
698 +     * Returns a random boolean; a "coin flip".
699 +     */
700 +    static boolean randomBoolean() {
701 +        return ThreadLocalRandom.current().nextBoolean();
702 +    }
703 +
704 +    /**
705 +     * Returns a random element from given choices.
706 +     */
707 +    <T> T chooseRandomly(T... choices) {
708 +        return choices[ThreadLocalRandom.current().nextInt(choices.length)];
709 +    }
710  
711      /**
712 <     * Returns the shortest timed delay. This could
713 <     * be reimplemented to use for example a Property.
712 >     * Returns the shortest timed delay. This can be scaled up for
713 >     * slow machines using the jsr166.delay.factor system property,
714 >     * or via jtreg's -timeoutFactor: flag.
715 >     * http://openjdk.java.net/jtreg/command-help.html
716       */
717      protected long getShortDelay() {
718 <        return 50;
718 >        return (long) (50 * delayFactor);
719      }
720  
721      /**
# Line 324 | Line 726 | public class JSR166TestCase extends Test
726          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
727          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
728          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
729 +        LONGER_DELAY_MS = 2 * LONG_DELAY_MS;
730      }
731  
732 +    private static final long TIMEOUT_DELAY_MS
733 +        = (long) (12.0 * Math.cbrt(delayFactor));
734 +
735      /**
736 <     * Returns a timeout in milliseconds to be used in tests that
737 <     * verify that operations block or time out.
736 >     * Returns a timeout in milliseconds to be used in tests that verify
737 >     * that operations block or time out.  We want this to be longer
738 >     * than the OS scheduling quantum, but not too long, so don't scale
739 >     * linearly with delayFactor; we use "crazy" cube root instead.
740       */
741 <    long timeoutMillis() {
742 <        return SHORT_DELAY_MS / 4;
741 >    static long timeoutMillis() {
742 >        return TIMEOUT_DELAY_MS;
743      }
744  
745      /**
746 <     * Returns a new Date instance representing a time delayMillis
747 <     * milliseconds in the future.
746 >     * Returns a new Date instance representing a time at least
747 >     * delayMillis milliseconds in the future.
748       */
749      Date delayedDate(long delayMillis) {
750 <        return new Date(System.currentTimeMillis() + delayMillis);
750 >        // Add 1 because currentTimeMillis is known to round into the past.
751 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
752      }
753  
754      /**
755       * The first exception encountered if any threadAssertXXX method fails.
756       */
757      private final AtomicReference<Throwable> threadFailure
758 <        = new AtomicReference<Throwable>(null);
758 >        = new AtomicReference<>(null);
759  
760      /**
761       * Records an exception so that it can be rethrown later in the test
# Line 355 | Line 764 | public class JSR166TestCase extends Test
764       * the same test have no effect.
765       */
766      public void threadRecordFailure(Throwable t) {
767 <        threadFailure.compareAndSet(null, t);
767 >        System.err.println(t);
768 >        if (threadFailure.compareAndSet(null, t))
769 >            dumpTestThreads();
770      }
771  
772      public void setUp() {
773          setDelays();
774      }
775  
776 +    void tearDownFail(String format, Object... args) {
777 +        String msg = toString() + ": " + String.format(format, args);
778 +        System.err.println(msg);
779 +        dumpTestThreads();
780 +        throw new AssertionError(msg);
781 +    }
782 +
783      /**
784       * Extra checks that get done for all test cases.
785       *
# Line 380 | Line 798 | public class JSR166TestCase extends Test
798                  throw (RuntimeException) t;
799              else if (t instanceof Exception)
800                  throw (Exception) t;
801 <            else {
802 <                AssertionFailedError afe =
385 <                    new AssertionFailedError(t.toString());
386 <                afe.initCause(t);
387 <                throw afe;
388 <            }
801 >            else
802 >                throw new AssertionError(t.toString(), t);
803          }
804  
805          if (Thread.interrupted())
806 <            throw new AssertionFailedError("interrupt status set in main thread");
806 >            tearDownFail("interrupt status set in main thread");
807  
808          checkForkJoinPoolThreadLeaks();
809      }
810  
811      /**
812 <     * Find missing try { ... } finally { joinPool(e); }
812 >     * Finds missing PoolCleaners
813       */
814      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
815 <        Thread[] survivors = new Thread[5];
815 >        Thread[] survivors = new Thread[7];
816          int count = Thread.enumerate(survivors);
817          for (int i = 0; i < count; i++) {
818              Thread thread = survivors[i];
# Line 406 | Line 820 | public class JSR166TestCase extends Test
820              if (name.startsWith("ForkJoinPool-")) {
821                  // give thread some time to terminate
822                  thread.join(LONG_DELAY_MS);
823 <                if (!thread.isAlive()) continue;
824 <                thread.stop();
825 <                throw new AssertionFailedError
412 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
413 <                                   toString(), name));
823 >                if (thread.isAlive())
824 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
825 >                                 thread);
826              }
827          }
828 +
829 +        if (!ForkJoinPool.commonPool()
830 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
831 +            tearDownFail("ForkJoin common pool thread stuck");
832      }
833  
834      /**
835       * Just like fail(reason), but additionally recording (using
836 <     * threadRecordFailure) any AssertionFailedError thrown, so that
837 <     * the current testcase will fail.
836 >     * threadRecordFailure) any AssertionError thrown, so that the
837 >     * current testcase will fail.
838       */
839      public void threadFail(String reason) {
840          try {
841              fail(reason);
842 <        } catch (AssertionFailedError t) {
843 <            threadRecordFailure(t);
844 <            fail(reason);
842 >        } catch (AssertionError fail) {
843 >            threadRecordFailure(fail);
844 >            throw fail;
845          }
846      }
847  
848      /**
849       * Just like assertTrue(b), but additionally recording (using
850 <     * threadRecordFailure) any AssertionFailedError thrown, so that
851 <     * the current testcase will fail.
850 >     * threadRecordFailure) any AssertionError thrown, so that the
851 >     * current testcase will fail.
852       */
853      public void threadAssertTrue(boolean b) {
854          try {
855              assertTrue(b);
856 <        } catch (AssertionFailedError t) {
857 <            threadRecordFailure(t);
858 <            throw t;
856 >        } catch (AssertionError fail) {
857 >            threadRecordFailure(fail);
858 >            throw fail;
859          }
860      }
861  
862      /**
863       * Just like assertFalse(b), but additionally recording (using
864 <     * threadRecordFailure) any AssertionFailedError thrown, so that
865 <     * the current testcase will fail.
864 >     * threadRecordFailure) any AssertionError thrown, so that the
865 >     * current testcase will fail.
866       */
867      public void threadAssertFalse(boolean b) {
868          try {
869              assertFalse(b);
870 <        } catch (AssertionFailedError t) {
871 <            threadRecordFailure(t);
872 <            throw t;
870 >        } catch (AssertionError fail) {
871 >            threadRecordFailure(fail);
872 >            throw fail;
873          }
874      }
875  
876      /**
877       * Just like assertNull(x), but additionally recording (using
878 <     * threadRecordFailure) any AssertionFailedError thrown, so that
879 <     * the current testcase will fail.
878 >     * threadRecordFailure) any AssertionError thrown, so that the
879 >     * current testcase will fail.
880       */
881      public void threadAssertNull(Object x) {
882          try {
883              assertNull(x);
884 <        } catch (AssertionFailedError t) {
885 <            threadRecordFailure(t);
886 <            throw t;
884 >        } catch (AssertionError fail) {
885 >            threadRecordFailure(fail);
886 >            throw fail;
887          }
888      }
889  
890      /**
891       * Just like assertEquals(x, y), but additionally recording (using
892 <     * threadRecordFailure) any AssertionFailedError thrown, so that
893 <     * the current testcase will fail.
892 >     * threadRecordFailure) any AssertionError thrown, so that the
893 >     * current testcase will fail.
894       */
895      public void threadAssertEquals(long x, long y) {
896          try {
897              assertEquals(x, y);
898 <        } catch (AssertionFailedError t) {
899 <            threadRecordFailure(t);
900 <            throw t;
898 >        } catch (AssertionError fail) {
899 >            threadRecordFailure(fail);
900 >            throw fail;
901          }
902      }
903  
904      /**
905       * Just like assertEquals(x, y), but additionally recording (using
906 <     * threadRecordFailure) any AssertionFailedError thrown, so that
907 <     * the current testcase will fail.
906 >     * threadRecordFailure) any AssertionError thrown, so that the
907 >     * current testcase will fail.
908       */
909      public void threadAssertEquals(Object x, Object y) {
910          try {
911              assertEquals(x, y);
912 <        } catch (AssertionFailedError t) {
913 <            threadRecordFailure(t);
914 <            throw t;
915 <        } catch (Throwable t) {
916 <            threadUnexpectedException(t);
912 >        } catch (AssertionError fail) {
913 >            threadRecordFailure(fail);
914 >            throw fail;
915 >        } catch (Throwable fail) {
916 >            threadUnexpectedException(fail);
917          }
918      }
919  
920      /**
921       * Just like assertSame(x, y), but additionally recording (using
922 <     * threadRecordFailure) any AssertionFailedError thrown, so that
923 <     * the current testcase will fail.
922 >     * threadRecordFailure) any AssertionError thrown, so that the
923 >     * current testcase will fail.
924       */
925      public void threadAssertSame(Object x, Object y) {
926          try {
927              assertSame(x, y);
928 <        } catch (AssertionFailedError t) {
929 <            threadRecordFailure(t);
930 <            throw t;
928 >        } catch (AssertionError fail) {
929 >            threadRecordFailure(fail);
930 >            throw fail;
931          }
932      }
933  
# Line 531 | Line 947 | public class JSR166TestCase extends Test
947  
948      /**
949       * Records the given exception using {@link #threadRecordFailure},
950 <     * then rethrows the exception, wrapping it in an
951 <     * AssertionFailedError if necessary.
950 >     * then rethrows the exception, wrapping it in an AssertionError
951 >     * if necessary.
952       */
953      public void threadUnexpectedException(Throwable t) {
954          threadRecordFailure(t);
# Line 541 | Line 957 | public class JSR166TestCase extends Test
957              throw (RuntimeException) t;
958          else if (t instanceof Error)
959              throw (Error) t;
960 <        else {
961 <            AssertionFailedError afe =
546 <                new AssertionFailedError("unexpected exception: " + t);
547 <            afe.initCause(t);
548 <            throw afe;
549 <        }
960 >        else
961 >            throw new AssertionError("unexpected exception: " + t, t);
962      }
963  
964      /**
965       * Delays, via Thread.sleep, for the given millisecond delay, but
966       * if the sleep is shorter than specified, may re-sleep or yield
967 <     * until time elapses.
967 >     * until time elapses.  Ensures that the given time, as measured
968 >     * by System.nanoTime(), has elapsed.
969       */
970      static void delay(long millis) throws InterruptedException {
971 <        long startTime = System.nanoTime();
972 <        long ns = millis * 1000 * 1000;
973 <        for (;;) {
971 >        long nanos = millis * (1000 * 1000);
972 >        final long wakeupTime = System.nanoTime() + nanos;
973 >        do {
974              if (millis > 0L)
975                  Thread.sleep(millis);
976              else // too short to sleep
977                  Thread.yield();
978 <            long d = ns - (System.nanoTime() - startTime);
979 <            if (d > 0L)
980 <                millis = d / (1000 * 1000);
981 <            else
982 <                break;
978 >            nanos = wakeupTime - System.nanoTime();
979 >            millis = nanos / (1000 * 1000);
980 >        } while (nanos >= 0L);
981 >    }
982 >
983 >    /**
984 >     * Allows use of try-with-resources with per-test thread pools.
985 >     */
986 >    class PoolCleaner implements AutoCloseable {
987 >        private final ExecutorService pool;
988 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
989 >        public void close() { joinPool(pool); }
990 >    }
991 >
992 >    /**
993 >     * An extension of PoolCleaner that has an action to release the pool.
994 >     */
995 >    class PoolCleanerWithReleaser extends PoolCleaner {
996 >        private final Runnable releaser;
997 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
998 >            super(pool);
999 >            this.releaser = releaser;
1000 >        }
1001 >        public void close() {
1002 >            try {
1003 >                releaser.run();
1004 >            } finally {
1005 >                super.close();
1006 >            }
1007          }
1008      }
1009  
1010 +    PoolCleaner cleaner(ExecutorService pool) {
1011 +        return new PoolCleaner(pool);
1012 +    }
1013 +
1014 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
1015 +        return new PoolCleanerWithReleaser(pool, releaser);
1016 +    }
1017 +
1018 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
1019 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
1020 +    }
1021 +
1022 +    Runnable releaser(final CountDownLatch latch) {
1023 +        return new Runnable() { public void run() {
1024 +            do { latch.countDown(); }
1025 +            while (latch.getCount() > 0);
1026 +        }};
1027 +    }
1028 +
1029 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1030 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
1031 +    }
1032 +
1033 +    Runnable releaser(final AtomicBoolean flag) {
1034 +        return new Runnable() { public void run() { flag.set(true); }};
1035 +    }
1036 +
1037      /**
1038       * Waits out termination of a thread pool or fails doing so.
1039       */
1040 <    void joinPool(ExecutorService exec) {
1040 >    void joinPool(ExecutorService pool) {
1041          try {
1042 <            exec.shutdown();
1043 <            assertTrue("ExecutorService did not terminate in a timely manner",
1044 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
1042 >            pool.shutdown();
1043 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1044 >                try {
1045 >                    threadFail("ExecutorService " + pool +
1046 >                               " did not terminate in a timely manner");
1047 >                } finally {
1048 >                    // last resort, for the benefit of subsequent tests
1049 >                    pool.shutdownNow();
1050 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1051 >                }
1052 >            }
1053          } catch (SecurityException ok) {
1054              // Allowed in case test doesn't have privs
1055 <        } catch (InterruptedException ie) {
1056 <            fail("Unexpected InterruptedException");
1055 >        } catch (InterruptedException fail) {
1056 >            threadFail("Unexpected InterruptedException");
1057          }
1058      }
1059  
1060      /**
1061 <     * A debugging tool to print all stack traces, as jstack does.
1061 >     * Like Runnable, but with the freedom to throw anything.
1062 >     * junit folks had the same idea:
1063 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1064       */
1065 <    static void printAllStackTraces() {
592 <        for (ThreadInfo info :
593 <                 ManagementFactory.getThreadMXBean()
594 <                 .dumpAllThreads(true, true))
595 <            System.err.print(info);
596 <    }
1065 >    interface Action { public void run() throws Throwable; }
1066  
1067      /**
1068 <     * Checks that thread does not terminate within the default
1069 <     * millisecond delay of {@code timeoutMillis()}.
1068 >     * Runs all the given actions in parallel, failing if any fail.
1069 >     * Useful for running multiple variants of tests that are
1070 >     * necessarily individually slow because they must block.
1071       */
1072 <    void assertThreadStaysAlive(Thread thread) {
1073 <        assertThreadStaysAlive(thread, timeoutMillis());
1072 >    void testInParallel(Action ... actions) {
1073 >        ExecutorService pool = Executors.newCachedThreadPool();
1074 >        try (PoolCleaner cleaner = cleaner(pool)) {
1075 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1076 >            for (final Action action : actions)
1077 >                futures.add(pool.submit(new CheckedRunnable() {
1078 >                    public void realRun() throws Throwable { action.run();}}));
1079 >            for (Future<?> future : futures)
1080 >                try {
1081 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1082 >                } catch (ExecutionException ex) {
1083 >                    threadUnexpectedException(ex.getCause());
1084 >                } catch (Exception ex) {
1085 >                    threadUnexpectedException(ex);
1086 >                }
1087 >        }
1088 >    }
1089 >
1090 >    /** Returns true if thread info might be useful in a thread dump. */
1091 >    static boolean threadOfInterest(ThreadInfo info) {
1092 >        final String name = info.getThreadName();
1093 >        String lockName;
1094 >        if (name == null)
1095 >            return true;
1096 >        if (name.equals("Signal Dispatcher")
1097 >            || name.equals("WedgedTestDetector"))
1098 >            return false;
1099 >        if (name.equals("Reference Handler")) {
1100 >            // Reference Handler stacktrace changed in JDK-8156500
1101 >            StackTraceElement[] stackTrace; String methodName;
1102 >            if ((stackTrace = info.getStackTrace()) != null
1103 >                && stackTrace.length > 0
1104 >                && (methodName = stackTrace[0].getMethodName()) != null
1105 >                && methodName.equals("waitForReferencePendingList"))
1106 >                return false;
1107 >            // jdk8 Reference Handler stacktrace
1108 >            if ((lockName = info.getLockName()) != null
1109 >                && lockName.startsWith("java.lang.ref"))
1110 >                return false;
1111 >        }
1112 >        if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
1113 >            && (lockName = info.getLockName()) != null
1114 >            && lockName.startsWith("java.lang.ref"))
1115 >            return false;
1116 >        if (name.startsWith("ForkJoinPool.commonPool-worker")
1117 >            && (lockName = info.getLockName()) != null
1118 >            && lockName.startsWith("java.util.concurrent.ForkJoinPool"))
1119 >            return false;
1120 >        return true;
1121      }
1122  
1123      /**
1124 <     * Checks that thread does not terminate within the given millisecond delay.
1124 >     * A debugging tool to print stack traces of most threads, as jstack does.
1125 >     * Uninteresting threads are filtered out.
1126       */
1127 <    void assertThreadStaysAlive(Thread thread, long millis) {
1128 <        try {
1129 <            // No need to optimize the failing case via Thread.join.
1130 <            delay(millis);
1131 <            assertTrue(thread.isAlive());
1132 <        } catch (InterruptedException ie) {
1133 <            fail("Unexpected InterruptedException");
1127 >    static void dumpTestThreads() {
1128 >        SecurityManager sm = System.getSecurityManager();
1129 >        if (sm != null) {
1130 >            try {
1131 >                System.setSecurityManager(null);
1132 >            } catch (SecurityException giveUp) {
1133 >                return;
1134 >            }
1135          }
1136 +
1137 +        System.err.println("------ stacktrace dump start ------");
1138 +        for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true))
1139 +            if (threadOfInterest(info))
1140 +                System.err.print(info);
1141 +        System.err.println("------ stacktrace dump end ------");
1142 +
1143 +        if (sm != null) System.setSecurityManager(sm);
1144      }
1145  
1146      /**
1147 <     * Checks that the threads do not terminate within the default
621 <     * millisecond delay of {@code timeoutMillis()}.
1147 >     * Checks that thread eventually enters the expected blocked thread state.
1148       */
1149 <    void assertThreadsStayAlive(Thread... threads) {
1150 <        assertThreadsStayAlive(timeoutMillis(), threads);
1149 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1150 >        // always sleep at least 1 ms, with high probability avoiding
1151 >        // transitory states
1152 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1153 >            try { delay(1); }
1154 >            catch (InterruptedException fail) {
1155 >                throw new AssertionError("Unexpected InterruptedException", fail);
1156 >            }
1157 >            Thread.State s = thread.getState();
1158 >            if (s == expected)
1159 >                return;
1160 >            else if (s == Thread.State.TERMINATED)
1161 >                fail("Unexpected thread termination");
1162 >        }
1163 >        fail("timed out waiting for thread to enter thread state " + expected);
1164      }
1165  
1166      /**
1167 <     * Checks that the threads do not terminate within the given millisecond delay.
1167 >     * Returns the thread's blocker's class name, if any, else null.
1168       */
1169 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1170 <        try {
1171 <            // No need to optimize the failing case via Thread.join.
1172 <            delay(millis);
1173 <            for (Thread thread : threads)
1174 <                assertTrue(thread.isAlive());
636 <        } catch (InterruptedException ie) {
637 <            fail("Unexpected InterruptedException");
638 <        }
1169 >    String blockerClassName(Thread thread) {
1170 >        ThreadInfo threadInfo; LockInfo lockInfo;
1171 >        if ((threadInfo = THREAD_MXBEAN.getThreadInfo(thread.getId(), 0)) != null
1172 >            && (lockInfo = threadInfo.getLockInfo()) != null)
1173 >            return lockInfo.getClassName();
1174 >        return null;
1175      }
1176  
1177      /**
# Line 655 | Line 1191 | public class JSR166TestCase extends Test
1191              future.get(timeoutMillis, MILLISECONDS);
1192              shouldThrow();
1193          } catch (TimeoutException success) {
1194 <        } catch (Exception e) {
1195 <            threadUnexpectedException(e);
1194 >        } catch (Exception fail) {
1195 >            threadUnexpectedException(fail);
1196          } finally { future.cancel(true); }
1197          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1198      }
# Line 676 | Line 1212 | public class JSR166TestCase extends Test
1212      }
1213  
1214      /**
1215 +     * The maximum number of consecutive spurious wakeups we should
1216 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1217 +     */
1218 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1219 +
1220 +    /**
1221       * The number of elements to place in collections, arrays, etc.
1222       */
1223      public static final int SIZE = 20;
# Line 700 | Line 1242 | public class JSR166TestCase extends Test
1242      public static final Integer m6  = new Integer(-6);
1243      public static final Integer m10 = new Integer(-10);
1244  
703
1245      /**
1246       * Runs Runnable r with a security policy that permits precisely
1247       * the specified permissions.  If there is no current security
# Line 780 | Line 1321 | public class JSR166TestCase extends Test
1321          }
1322          public void refresh() {}
1323          public String toString() {
1324 <            List<Permission> ps = new ArrayList<Permission>();
1324 >            List<Permission> ps = new ArrayList<>();
1325              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1326                  ps.add(e.nextElement());
1327              return "AdjustablePolicy with permissions " + ps;
# Line 808 | Line 1349 | public class JSR166TestCase extends Test
1349  
1350      /**
1351       * Sleeps until the given time has elapsed.
1352 <     * Throws AssertionFailedError if interrupted.
1352 >     * Throws AssertionError if interrupted.
1353       */
1354 <    void sleep(long millis) {
1354 >    static void sleep(long millis) {
1355          try {
1356              delay(millis);
1357 <        } catch (InterruptedException ie) {
1358 <            AssertionFailedError afe =
818 <                new AssertionFailedError("Unexpected InterruptedException");
819 <            afe.initCause(ie);
820 <            throw afe;
1357 >        } catch (InterruptedException fail) {
1358 >            throw new AssertionError("Unexpected InterruptedException", fail);
1359          }
1360      }
1361  
1362      /**
1363       * Spin-waits up to the specified number of milliseconds for the given
1364       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1365 +     * @param waitingForGodot if non-null, an additional condition to satisfy
1366       */
1367 <    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1368 <        long startTime = System.nanoTime();
1369 <        for (;;) {
1370 <            Thread.State s = thread.getState();
1371 <            if (s == Thread.State.BLOCKED ||
1372 <                s == Thread.State.WAITING ||
1373 <                s == Thread.State.TIMED_WAITING)
1374 <                return;
1375 <            else if (s == Thread.State.TERMINATED)
1367 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis,
1368 >                                       Callable<Boolean> waitingForGodot) {
1369 >        for (long startTime = 0L;;) {
1370 >            switch (thread.getState()) {
1371 >            default: break;
1372 >            case BLOCKED: case WAITING: case TIMED_WAITING:
1373 >                try {
1374 >                    if (waitingForGodot == null || waitingForGodot.call())
1375 >                        return;
1376 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1377 >                break;
1378 >            case TERMINATED:
1379                  fail("Unexpected thread termination");
1380 +            }
1381 +
1382 +            if (startTime == 0L)
1383 +                startTime = System.nanoTime();
1384              else if (millisElapsedSince(startTime) > timeoutMillis) {
1385 <                threadAssertTrue(thread.isAlive());
1386 <                return;
1385 >                assertTrue(thread.isAlive());
1386 >                if (waitingForGodot == null
1387 >                    || thread.getState() == Thread.State.RUNNABLE)
1388 >                    fail("timed out waiting for thread to enter wait state");
1389 >                else
1390 >                    fail("timed out waiting for condition, thread state="
1391 >                         + thread.getState());
1392              }
1393              Thread.yield();
1394          }
1395      }
1396  
1397      /**
1398 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1399 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1398 >     * Spin-waits up to the specified number of milliseconds for the given
1399 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1400 >     */
1401 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1402 >        waitForThreadToEnterWaitState(thread, timeoutMillis, null);
1403 >    }
1404 >
1405 >    /**
1406 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1407 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1408       */
1409      void waitForThreadToEnterWaitState(Thread thread) {
1410 <        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1410 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1411 >    }
1412 >
1413 >    /**
1414 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1415 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1416 >     * and additionally satisfy the given condition.
1417 >     */
1418 >    void waitForThreadToEnterWaitState(Thread thread,
1419 >                                       Callable<Boolean> waitingForGodot) {
1420 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1421 >    }
1422 >
1423 >    /**
1424 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1425 >     * be interrupted.  Clears the interrupt status before returning.
1426 >     */
1427 >    void awaitInterrupted() {
1428 >        for (long startTime = 0L; !Thread.interrupted(); ) {
1429 >            if (startTime == 0L)
1430 >                startTime = System.nanoTime();
1431 >            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1432 >                fail("timed out waiting for thread interrupt");
1433 >            Thread.yield();
1434 >        }
1435      }
1436  
1437      /**
1438       * Returns the number of milliseconds since time given by
1439       * startNanoTime, which must have been previously returned from a
1440 <     * call to {@link System.nanoTime()}.
1440 >     * call to {@link System#nanoTime()}.
1441       */
1442 <    long millisElapsedSince(long startNanoTime) {
1442 >    static long millisElapsedSince(long startNanoTime) {
1443          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1444      }
1445  
1446      /**
1447 +     * Checks that timed f.get() returns the expected value, and does not
1448 +     * wait for the timeout to elapse before returning.
1449 +     */
1450 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1451 +        long startTime = System.nanoTime();
1452 +        T actual = null;
1453 +        try {
1454 +            actual = f.get(timeoutMillis, MILLISECONDS);
1455 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1456 +        assertEquals(expectedValue, actual);
1457 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1458 +            throw new AssertionError("timed get did not return promptly");
1459 +    }
1460 +
1461 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1462 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1463 +    }
1464 +
1465 +    /**
1466       * Returns a new started daemon Thread running the given runnable.
1467       */
1468      Thread newStartedThread(Runnable runnable) {
# Line 871 | Line 1473 | public class JSR166TestCase extends Test
1473      }
1474  
1475      /**
1476 +     * Returns a new started daemon Thread running the given action,
1477 +     * wrapped in a CheckedRunnable.
1478 +     */
1479 +    Thread newStartedThread(Action action) {
1480 +        return newStartedThread(checkedRunnable(action));
1481 +    }
1482 +
1483 +    /**
1484       * Waits for the specified time (in milliseconds) for the thread
1485       * to terminate (using {@link Thread#join(long)}), else interrupts
1486       * the thread (in the hope that it may terminate later) and fails.
1487       */
1488 <    void awaitTermination(Thread t, long timeoutMillis) {
1488 >    void awaitTermination(Thread thread, long timeoutMillis) {
1489          try {
1490 <            t.join(timeoutMillis);
1491 <        } catch (InterruptedException ie) {
1492 <            threadUnexpectedException(ie);
1493 <        } finally {
1494 <            if (t.getState() != Thread.State.TERMINATED) {
1495 <                t.interrupt();
1496 <                fail("Test timed out");
1490 >            thread.join(timeoutMillis);
1491 >        } catch (InterruptedException fail) {
1492 >            threadUnexpectedException(fail);
1493 >        }
1494 >        if (thread.getState() != Thread.State.TERMINATED) {
1495 >            String detail = String.format(
1496 >                    "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1497 >                    thread, thread.getState());
1498 >            try {
1499 >                threadFail(detail);
1500 >            } finally {
1501 >                // Interrupt thread __after__ having reported its stack trace
1502 >                thread.interrupt();
1503              }
1504          }
1505      }
# Line 905 | Line 1521 | public class JSR166TestCase extends Test
1521          public final void run() {
1522              try {
1523                  realRun();
1524 <            } catch (Throwable t) {
1525 <                threadUnexpectedException(t);
1524 >            } catch (Throwable fail) {
1525 >                threadUnexpectedException(fail);
1526              }
1527          }
1528      }
1529  
1530 <    public abstract class RunnableShouldThrow implements Runnable {
1531 <        protected abstract void realRun() throws Throwable;
1532 <
1533 <        final Class<?> exceptionClass;
1534 <
919 <        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
920 <            this.exceptionClass = exceptionClass;
921 <        }
922 <
923 <        public final void run() {
924 <            try {
925 <                realRun();
926 <                threadShouldThrow(exceptionClass.getSimpleName());
927 <            } catch (Throwable t) {
928 <                if (! exceptionClass.isInstance(t))
929 <                    threadUnexpectedException(t);
930 <            }
931 <        }
1530 >    Runnable checkedRunnable(Action action) {
1531 >        return new CheckedRunnable() {
1532 >            public void realRun() throws Throwable {
1533 >                action.run();
1534 >            }};
1535      }
1536  
1537      public abstract class ThreadShouldThrow extends Thread {
# Line 943 | Line 1546 | public class JSR166TestCase extends Test
1546          public final void run() {
1547              try {
1548                  realRun();
946                threadShouldThrow(exceptionClass.getSimpleName());
1549              } catch (Throwable t) {
1550                  if (! exceptionClass.isInstance(t))
1551                      threadUnexpectedException(t);
1552 +                return;
1553              }
1554 +            threadShouldThrow(exceptionClass.getSimpleName());
1555          }
1556      }
1557  
# Line 957 | Line 1561 | public class JSR166TestCase extends Test
1561          public final void run() {
1562              try {
1563                  realRun();
960                threadShouldThrow("InterruptedException");
1564              } catch (InterruptedException success) {
1565                  threadAssertFalse(Thread.interrupted());
1566 <            } catch (Throwable t) {
1567 <                threadUnexpectedException(t);
1566 >                return;
1567 >            } catch (Throwable fail) {
1568 >                threadUnexpectedException(fail);
1569              }
1570 +            threadShouldThrow("InterruptedException");
1571          }
1572      }
1573  
# Line 972 | Line 1577 | public class JSR166TestCase extends Test
1577          public final T call() {
1578              try {
1579                  return realCall();
1580 <            } catch (Throwable t) {
1581 <                threadUnexpectedException(t);
977 <                return null;
1580 >            } catch (Throwable fail) {
1581 >                threadUnexpectedException(fail);
1582              }
1583 <        }
980 <    }
981 <
982 <    public abstract class CheckedInterruptedCallable<T>
983 <        implements Callable<T> {
984 <        protected abstract T realCall() throws Throwable;
985 <
986 <        public final T call() {
987 <            try {
988 <                T result = realCall();
989 <                threadShouldThrow("InterruptedException");
990 <                return result;
991 <            } catch (InterruptedException success) {
992 <                threadAssertFalse(Thread.interrupted());
993 <            } catch (Throwable t) {
994 <                threadUnexpectedException(t);
995 <            }
996 <            return null;
1583 >            throw new AssertionError("unreached");
1584          }
1585      }
1586  
# Line 1008 | Line 1595 | public class JSR166TestCase extends Test
1595      public static final String TEST_STRING = "a test string";
1596  
1597      public static class StringTask implements Callable<String> {
1598 <        public String call() { return TEST_STRING; }
1598 >        final String value;
1599 >        public StringTask() { this(TEST_STRING); }
1600 >        public StringTask(String value) { this.value = value; }
1601 >        public String call() { return value; }
1602      }
1603  
1604      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1021 | Line 1611 | public class JSR166TestCase extends Test
1611              }};
1612      }
1613  
1614 <    public Runnable awaiter(final CountDownLatch latch) {
1614 >    public Runnable countDowner(final CountDownLatch latch) {
1615          return new CheckedRunnable() {
1616              public void realRun() throws InterruptedException {
1617 <                await(latch);
1617 >                latch.countDown();
1618              }};
1619      }
1620  
1621 +    class LatchAwaiter extends CheckedRunnable {
1622 +        static final int NEW = 0;
1623 +        static final int RUNNING = 1;
1624 +        static final int DONE = 2;
1625 +        final CountDownLatch latch;
1626 +        int state = NEW;
1627 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1628 +        public void realRun() throws InterruptedException {
1629 +            state = 1;
1630 +            await(latch);
1631 +            state = 2;
1632 +        }
1633 +    }
1634 +
1635 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1636 +        return new LatchAwaiter(latch);
1637 +    }
1638 +
1639 +    public void await(CountDownLatch latch, long timeoutMillis) {
1640 +        boolean timedOut = false;
1641 +        try {
1642 +            timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1643 +        } catch (Throwable fail) {
1644 +            threadUnexpectedException(fail);
1645 +        }
1646 +        if (timedOut)
1647 +            fail("timed out waiting for CountDownLatch for "
1648 +                 + (timeoutMillis/1000) + " sec");
1649 +    }
1650 +
1651      public void await(CountDownLatch latch) {
1652 +        await(latch, LONG_DELAY_MS);
1653 +    }
1654 +
1655 +    public void await(Semaphore semaphore) {
1656 +        boolean timedOut = false;
1657          try {
1658 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1659 <        } catch (Throwable t) {
1660 <            threadUnexpectedException(t);
1658 >            timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1659 >        } catch (Throwable fail) {
1660 >            threadUnexpectedException(fail);
1661          }
1662 +        if (timedOut)
1663 +            fail("timed out waiting for Semaphore for "
1664 +                 + (LONG_DELAY_MS/1000) + " sec");
1665      }
1666  
1667 <    public void await(Semaphore semaphore) {
1667 >    public void await(CyclicBarrier barrier) {
1668          try {
1669 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1670 <        } catch (Throwable t) {
1671 <            threadUnexpectedException(t);
1669 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1670 >        } catch (Throwable fail) {
1671 >            threadUnexpectedException(fail);
1672          }
1673      }
1674  
# Line 1058 | Line 1686 | public class JSR166TestCase extends Test
1686   //         long startTime = System.nanoTime();
1687   //         while (!flag.get()) {
1688   //             if (millisElapsedSince(startTime) > timeoutMillis)
1689 < //                 throw new AssertionFailedError("timed out");
1689 > //                 throw new AssertionError("timed out");
1690   //             Thread.yield();
1691   //         }
1692   //     }
# Line 1067 | Line 1695 | public class JSR166TestCase extends Test
1695          public String call() { throw new NullPointerException(); }
1696      }
1697  
1070    public static class CallableOne implements Callable<Integer> {
1071        public Integer call() { return one; }
1072    }
1073
1074    public class ShortRunnable extends CheckedRunnable {
1075        protected void realRun() throws Throwable {
1076            delay(SHORT_DELAY_MS);
1077        }
1078    }
1079
1080    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1081        protected void realRun() throws InterruptedException {
1082            delay(SHORT_DELAY_MS);
1083        }
1084    }
1085
1086    public class SmallRunnable extends CheckedRunnable {
1087        protected void realRun() throws Throwable {
1088            delay(SMALL_DELAY_MS);
1089        }
1090    }
1091
1092    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1093        protected void realRun() {
1094            try {
1095                delay(SMALL_DELAY_MS);
1096            } catch (InterruptedException ok) {}
1097        }
1098    }
1099
1100    public class SmallCallable extends CheckedCallable {
1101        protected Object realCall() throws InterruptedException {
1102            delay(SMALL_DELAY_MS);
1103            return Boolean.TRUE;
1104        }
1105    }
1106
1107    public class MediumRunnable extends CheckedRunnable {
1108        protected void realRun() throws Throwable {
1109            delay(MEDIUM_DELAY_MS);
1110        }
1111    }
1112
1113    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1114        protected void realRun() throws InterruptedException {
1115            delay(MEDIUM_DELAY_MS);
1116        }
1117    }
1118
1698      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1699          return new CheckedRunnable() {
1700              protected void realRun() {
# Line 1125 | Line 1704 | public class JSR166TestCase extends Test
1704              }};
1705      }
1706  
1128    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1129        protected void realRun() {
1130            try {
1131                delay(MEDIUM_DELAY_MS);
1132            } catch (InterruptedException ok) {}
1133        }
1134    }
1135
1136    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1137        protected void realRun() {
1138            try {
1139                delay(LONG_DELAY_MS);
1140            } catch (InterruptedException ok) {}
1141        }
1142    }
1143
1707      /**
1708       * For use as ThreadFactory in constructors
1709       */
# Line 1154 | Line 1717 | public class JSR166TestCase extends Test
1717          boolean isDone();
1718      }
1719  
1157    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1158        return new TrackedRunnable() {
1159                private volatile boolean done = false;
1160                public boolean isDone() { return done; }
1161                public void run() {
1162                    try {
1163                        delay(timeoutMillis);
1164                        done = true;
1165                    } catch (InterruptedException ok) {}
1166                }
1167            };
1168    }
1169
1170    public static class TrackedShortRunnable implements Runnable {
1171        public volatile boolean done = false;
1172        public void run() {
1173            try {
1174                delay(SHORT_DELAY_MS);
1175                done = true;
1176            } catch (InterruptedException ok) {}
1177        }
1178    }
1179
1180    public static class TrackedSmallRunnable implements Runnable {
1181        public volatile boolean done = false;
1182        public void run() {
1183            try {
1184                delay(SMALL_DELAY_MS);
1185                done = true;
1186            } catch (InterruptedException ok) {}
1187        }
1188    }
1189
1190    public static class TrackedMediumRunnable implements Runnable {
1191        public volatile boolean done = false;
1192        public void run() {
1193            try {
1194                delay(MEDIUM_DELAY_MS);
1195                done = true;
1196            } catch (InterruptedException ok) {}
1197        }
1198    }
1199
1200    public static class TrackedLongRunnable implements Runnable {
1201        public volatile boolean done = false;
1202        public void run() {
1203            try {
1204                delay(LONG_DELAY_MS);
1205                done = true;
1206            } catch (InterruptedException ok) {}
1207        }
1208    }
1209
1720      public static class TrackedNoOpRunnable implements Runnable {
1721          public volatile boolean done = false;
1722          public void run() {
# Line 1214 | Line 1724 | public class JSR166TestCase extends Test
1724          }
1725      }
1726  
1217    public static class TrackedCallable implements Callable {
1218        public volatile boolean done = false;
1219        public Object call() {
1220            try {
1221                delay(SMALL_DELAY_MS);
1222                done = true;
1223            } catch (InterruptedException ok) {}
1224            return Boolean.TRUE;
1225        }
1226    }
1227
1727      /**
1728       * Analog of CheckedRunnable for RecursiveAction
1729       */
1730      public abstract class CheckedRecursiveAction extends RecursiveAction {
1731          protected abstract void realCompute() throws Throwable;
1732  
1733 <        public final void compute() {
1733 >        @Override protected final void compute() {
1734              try {
1735                  realCompute();
1736 <            } catch (Throwable t) {
1737 <                threadUnexpectedException(t);
1736 >            } catch (Throwable fail) {
1737 >                threadUnexpectedException(fail);
1738              }
1739          }
1740      }
# Line 1246 | Line 1745 | public class JSR166TestCase extends Test
1745      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1746          protected abstract T realCompute() throws Throwable;
1747  
1748 <        public final T compute() {
1748 >        @Override protected final T compute() {
1749              try {
1750                  return realCompute();
1751 <            } catch (Throwable t) {
1752 <                threadUnexpectedException(t);
1254 <                return null;
1751 >            } catch (Throwable fail) {
1752 >                threadUnexpectedException(fail);
1753              }
1754 +            throw new AssertionError("unreached");
1755          }
1756      }
1757  
# Line 1266 | Line 1765 | public class JSR166TestCase extends Test
1765  
1766      /**
1767       * A CyclicBarrier that uses timed await and fails with
1768 <     * AssertionFailedErrors instead of throwing checked exceptions.
1768 >     * AssertionErrors instead of throwing checked exceptions.
1769       */
1770 <    public class CheckedBarrier extends CyclicBarrier {
1770 >    public static class CheckedBarrier extends CyclicBarrier {
1771          public CheckedBarrier(int parties) { super(parties); }
1772  
1773          public int await() {
1774              try {
1775                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1776 <            } catch (TimeoutException e) {
1777 <                throw new AssertionFailedError("timed out");
1778 <            } catch (Exception e) {
1779 <                AssertionFailedError afe =
1281 <                    new AssertionFailedError("Unexpected exception: " + e);
1282 <                afe.initCause(e);
1283 <                throw afe;
1776 >            } catch (TimeoutException timedOut) {
1777 >                throw new AssertionError("timed out");
1778 >            } catch (Exception fail) {
1779 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1780              }
1781          }
1782      }
# Line 1291 | Line 1787 | public class JSR166TestCase extends Test
1787              assertEquals(0, q.size());
1788              assertNull(q.peek());
1789              assertNull(q.poll());
1790 <            assertNull(q.poll(0, MILLISECONDS));
1790 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1791              assertEquals(q.toString(), "[]");
1792              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1793              assertFalse(q.iterator().hasNext());
# Line 1307 | Line 1803 | public class JSR166TestCase extends Test
1803                  q.remove();
1804                  shouldThrow();
1805              } catch (NoSuchElementException success) {}
1806 <        } catch (InterruptedException ie) {
1311 <            threadUnexpectedException(ie);
1312 <        }
1806 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1807      }
1808  
1809      void assertSerialEquals(Object x, Object y) {
# Line 1328 | Line 1822 | public class JSR166TestCase extends Test
1822              oos.flush();
1823              oos.close();
1824              return bos.toByteArray();
1825 <        } catch (Throwable t) {
1826 <            threadUnexpectedException(t);
1825 >        } catch (Throwable fail) {
1826 >            threadUnexpectedException(fail);
1827              return new byte[0];
1828          }
1829      }
1830  
1831 +    void assertImmutable(Object o) {
1832 +        if (o instanceof Collection) {
1833 +            assertThrows(
1834 +                UnsupportedOperationException.class,
1835 +                () -> ((Collection) o).add(null));
1836 +        }
1837 +    }
1838 +
1839      @SuppressWarnings("unchecked")
1840      <T> T serialClone(T o) {
1841 +        T clone = null;
1842          try {
1843              ObjectInputStream ois = new ObjectInputStream
1844                  (new ByteArrayInputStream(serialBytes(o)));
1845 <            T clone = (T) ois.readObject();
1846 <            assertSame(o.getClass(), clone.getClass());
1847 <            return clone;
1848 <        } catch (Throwable t) {
1849 <            threadUnexpectedException(t);
1845 >            clone = (T) ois.readObject();
1846 >        } catch (Throwable fail) {
1847 >            threadUnexpectedException(fail);
1848 >        }
1849 >        if (o == clone) assertImmutable(o);
1850 >        else assertSame(o.getClass(), clone.getClass());
1851 >        return clone;
1852 >    }
1853 >
1854 >    /**
1855 >     * A version of serialClone that leaves error handling (for
1856 >     * e.g. NotSerializableException) up to the caller.
1857 >     */
1858 >    @SuppressWarnings("unchecked")
1859 >    <T> T serialClonePossiblyFailing(T o)
1860 >        throws ReflectiveOperationException, java.io.IOException {
1861 >        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1862 >        ObjectOutputStream oos = new ObjectOutputStream(bos);
1863 >        oos.writeObject(o);
1864 >        oos.flush();
1865 >        oos.close();
1866 >        ObjectInputStream ois = new ObjectInputStream
1867 >            (new ByteArrayInputStream(bos.toByteArray()));
1868 >        T clone = (T) ois.readObject();
1869 >        if (o == clone) assertImmutable(o);
1870 >        else assertSame(o.getClass(), clone.getClass());
1871 >        return clone;
1872 >    }
1873 >
1874 >    /**
1875 >     * If o implements Cloneable and has a public clone method,
1876 >     * returns a clone of o, else null.
1877 >     */
1878 >    @SuppressWarnings("unchecked")
1879 >    <T> T cloneableClone(T o) {
1880 >        if (!(o instanceof Cloneable)) return null;
1881 >        final T clone;
1882 >        try {
1883 >            clone = (T) o.getClass().getMethod("clone").invoke(o);
1884 >        } catch (NoSuchMethodException ok) {
1885              return null;
1886 +        } catch (ReflectiveOperationException unexpected) {
1887 +            throw new Error(unexpected);
1888 +        }
1889 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1890 +        assertSame(o.getClass(), clone.getClass());
1891 +        return clone;
1892 +    }
1893 +
1894 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1895 +                             Action... throwingActions) {
1896 +        for (Action throwingAction : throwingActions) {
1897 +            boolean threw = false;
1898 +            try { throwingAction.run(); }
1899 +            catch (Throwable t) {
1900 +                threw = true;
1901 +                if (!expectedExceptionClass.isInstance(t))
1902 +                    throw new AssertionError(
1903 +                            "Expected " + expectedExceptionClass.getName() +
1904 +                            ", got " + t.getClass().getName(),
1905 +                            t);
1906 +            }
1907 +            if (!threw)
1908 +                shouldThrow(expectedExceptionClass.getName());
1909 +        }
1910 +    }
1911 +
1912 +    public void assertIteratorExhausted(Iterator<?> it) {
1913 +        try {
1914 +            it.next();
1915 +            shouldThrow();
1916 +        } catch (NoSuchElementException success) {}
1917 +        assertFalse(it.hasNext());
1918 +    }
1919 +
1920 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1921 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1922 +    }
1923 +
1924 +    public Runnable runnableThrowing(final RuntimeException ex) {
1925 +        return new Runnable() { public void run() { throw ex; }};
1926 +    }
1927 +
1928 +    /** A reusable thread pool to be shared by tests. */
1929 +    static final ExecutorService cachedThreadPool =
1930 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1931 +                               1000L, MILLISECONDS,
1932 +                               new SynchronousQueue<Runnable>());
1933 +
1934 +    static <T> void shuffle(T[] array) {
1935 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1936 +    }
1937 +
1938 +    /**
1939 +     * Returns the same String as would be returned by {@link
1940 +     * Object#toString}, whether or not the given object's class
1941 +     * overrides toString().
1942 +     *
1943 +     * @see System#identityHashCode
1944 +     */
1945 +    static String identityString(Object x) {
1946 +        return x.getClass().getName()
1947 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1948 +    }
1949 +
1950 +    // --- Shared assertions for Executor tests ---
1951 +
1952 +    /**
1953 +     * Returns maximum number of tasks that can be submitted to given
1954 +     * pool (with bounded queue) before saturation (when submission
1955 +     * throws RejectedExecutionException).
1956 +     */
1957 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1958 +        BlockingQueue<Runnable> q = pool.getQueue();
1959 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1960 +    }
1961 +
1962 +    @SuppressWarnings("FutureReturnValueIgnored")
1963 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1964 +        try {
1965 +            e.execute((Runnable) null);
1966 +            shouldThrow();
1967 +        } catch (NullPointerException success) {}
1968 +
1969 +        if (! (e instanceof ExecutorService)) return;
1970 +        ExecutorService es = (ExecutorService) e;
1971 +        try {
1972 +            es.submit((Runnable) null);
1973 +            shouldThrow();
1974 +        } catch (NullPointerException success) {}
1975 +        try {
1976 +            es.submit((Runnable) null, Boolean.TRUE);
1977 +            shouldThrow();
1978 +        } catch (NullPointerException success) {}
1979 +        try {
1980 +            es.submit((Callable) null);
1981 +            shouldThrow();
1982 +        } catch (NullPointerException success) {}
1983 +
1984 +        if (! (e instanceof ScheduledExecutorService)) return;
1985 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1986 +        try {
1987 +            ses.schedule((Runnable) null,
1988 +                         randomTimeout(), randomTimeUnit());
1989 +            shouldThrow();
1990 +        } catch (NullPointerException success) {}
1991 +        try {
1992 +            ses.schedule((Callable) null,
1993 +                         randomTimeout(), randomTimeUnit());
1994 +            shouldThrow();
1995 +        } catch (NullPointerException success) {}
1996 +        try {
1997 +            ses.scheduleAtFixedRate((Runnable) null,
1998 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1999 +            shouldThrow();
2000 +        } catch (NullPointerException success) {}
2001 +        try {
2002 +            ses.scheduleWithFixedDelay((Runnable) null,
2003 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2004 +            shouldThrow();
2005 +        } catch (NullPointerException success) {}
2006 +    }
2007 +
2008 +    void setRejectedExecutionHandler(
2009 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2010 +        p.setRejectedExecutionHandler(handler);
2011 +        assertSame(handler, p.getRejectedExecutionHandler());
2012 +    }
2013 +
2014 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2015 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2016 +        final long savedTaskCount = p.getTaskCount();
2017 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2018 +        final int savedQueueSize = p.getQueue().size();
2019 +        final boolean stock = (p.getClass().getClassLoader() == null);
2020 +
2021 +        Runnable r = () -> {};
2022 +        Callable<Boolean> c = () -> Boolean.TRUE;
2023 +
2024 +        class Recorder implements RejectedExecutionHandler {
2025 +            public volatile Runnable r = null;
2026 +            public volatile ThreadPoolExecutor p = null;
2027 +            public void reset() { r = null; p = null; }
2028 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2029 +                assertNull(this.r);
2030 +                assertNull(this.p);
2031 +                this.r = r;
2032 +                this.p = p;
2033 +            }
2034 +        }
2035 +
2036 +        // check custom handler is invoked exactly once per task
2037 +        Recorder recorder = new Recorder();
2038 +        setRejectedExecutionHandler(p, recorder);
2039 +        for (int i = 2; i--> 0; ) {
2040 +            recorder.reset();
2041 +            p.execute(r);
2042 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
2043 +                assertSame(r, recorder.r);
2044 +            assertSame(p, recorder.p);
2045 +
2046 +            recorder.reset();
2047 +            assertFalse(p.submit(r).isDone());
2048 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2049 +            assertSame(p, recorder.p);
2050 +
2051 +            recorder.reset();
2052 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2053 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2054 +            assertSame(p, recorder.p);
2055 +
2056 +            recorder.reset();
2057 +            assertFalse(p.submit(c).isDone());
2058 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2059 +            assertSame(p, recorder.p);
2060 +
2061 +            if (p instanceof ScheduledExecutorService) {
2062 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2063 +                ScheduledFuture<?> future;
2064 +
2065 +                recorder.reset();
2066 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2067 +                assertFalse(future.isDone());
2068 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2069 +                assertSame(p, recorder.p);
2070 +
2071 +                recorder.reset();
2072 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2073 +                assertFalse(future.isDone());
2074 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2075 +                assertSame(p, recorder.p);
2076 +
2077 +                recorder.reset();
2078 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2079 +                assertFalse(future.isDone());
2080 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2081 +                assertSame(p, recorder.p);
2082 +
2083 +                recorder.reset();
2084 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2085 +                assertFalse(future.isDone());
2086 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2087 +                assertSame(p, recorder.p);
2088 +            }
2089 +        }
2090 +
2091 +        // Checking our custom handler above should be sufficient, but
2092 +        // we add some integration tests of standard handlers.
2093 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2094 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2095 +
2096 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2097 +        try {
2098 +            p.execute(setThread);
2099 +            shouldThrow();
2100 +        } catch (RejectedExecutionException success) {}
2101 +        assertNull(thread.get());
2102 +
2103 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2104 +        p.execute(setThread);
2105 +        assertNull(thread.get());
2106 +
2107 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2108 +        p.execute(setThread);
2109 +        if (p.isShutdown())
2110 +            assertNull(thread.get());
2111 +        else
2112 +            assertSame(Thread.currentThread(), thread.get());
2113 +
2114 +        setRejectedExecutionHandler(p, savedHandler);
2115 +
2116 +        // check that pool was not perturbed by handlers
2117 +        assertEquals(savedTaskCount, p.getTaskCount());
2118 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2119 +        assertEquals(savedQueueSize, p.getQueue().size());
2120 +    }
2121 +
2122 +    void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2123 +        assertEquals(x, y);
2124 +        assertEquals(y, x);
2125 +        assertEquals(x.isEmpty(), y.isEmpty());
2126 +        assertEquals(x.size(), y.size());
2127 +        if (x instanceof List) {
2128 +            assertEquals(x.toString(), y.toString());
2129 +        }
2130 +        if (x instanceof List || x instanceof Set) {
2131 +            assertEquals(x.hashCode(), y.hashCode());
2132 +        }
2133 +        if (x instanceof List || x instanceof Deque) {
2134 +            assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2135 +            assertTrue(Arrays.equals(x.toArray(new Object[0]),
2136 +                                     y.toArray(new Object[0])));
2137 +        }
2138 +    }
2139 +
2140 +    /**
2141 +     * A weaker form of assertCollectionsEquals which does not insist
2142 +     * that the two collections satisfy Object#equals(Object), since
2143 +     * they may use identity semantics as Deques do.
2144 +     */
2145 +    void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2146 +        if (x instanceof List || x instanceof Set)
2147 +            assertCollectionsEquals(x, y);
2148 +        else {
2149 +            assertEquals(x.isEmpty(), y.isEmpty());
2150 +            assertEquals(x.size(), y.size());
2151 +            assertEquals(new HashSet(x), new HashSet(y));
2152 +            if (x instanceof Deque) {
2153 +                assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2154 +                assertTrue(Arrays.equals(x.toArray(new Object[0]),
2155 +                                         y.toArray(new Object[0])));
2156 +            }
2157          }
2158      }
2159   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines