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.137 by jsr166, Fri Sep 4 18:27:33 2015 UTC vs.
Revision 1.239 by jsr166, Tue Jan 23 20:44:11 2018 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
8   */
9  
10 + /*
11 + * @test
12 + * @summary JSR-166 tck tests, in a number of variations.
13 + *          The first is the conformance testing variant,
14 + *          while others also test implementation details.
15 + * @build *
16 + * @modules java.management
17 + * @run junit/othervm/timeout=1000 JSR166TestCase
18 + * @run junit/othervm/timeout=1000
19 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 + *      --add-opens java.base/java.lang=ALL-UNNAMED
21 + *      -Djsr166.testImplementationDetails=true
22 + *      JSR166TestCase
23 + * @run junit/othervm/timeout=1000
24 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 + *      --add-opens java.base/java.lang=ALL-UNNAMED
26 + *      -Djsr166.testImplementationDetails=true
27 + *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28 + *      JSR166TestCase
29 + * @run junit/othervm/timeout=1000
30 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 + *      --add-opens java.base/java.lang=ALL-UNNAMED
32 + *      -Djsr166.testImplementationDetails=true
33 + *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
34 + *      -Djava.util.secureRandomSeed=true
35 + *      JSR166TestCase
36 + * @run junit/othervm/timeout=1000/policy=tck.policy
37 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 + *      --add-opens java.base/java.lang=ALL-UNNAMED
39 + *      -Djsr166.testImplementationDetails=true
40 + *      JSR166TestCase
41 + */
42 +
43   import static java.util.concurrent.TimeUnit.MILLISECONDS;
44 + import static java.util.concurrent.TimeUnit.MINUTES;
45   import static java.util.concurrent.TimeUnit.NANOSECONDS;
46  
47   import java.io.ByteArrayInputStream;
# Line 15 | Line 50 | import java.io.ObjectInputStream;
50   import java.io.ObjectOutputStream;
51   import java.lang.management.ManagementFactory;
52   import java.lang.management.ThreadInfo;
53 + import java.lang.management.ThreadMXBean;
54   import java.lang.reflect.Constructor;
55   import java.lang.reflect.Method;
56   import java.lang.reflect.Modifier;
# Line 27 | Line 63 | import java.security.ProtectionDomain;
63   import java.security.SecurityPermission;
64   import java.util.ArrayList;
65   import java.util.Arrays;
66 + import java.util.Collection;
67 + import java.util.Collections;
68   import java.util.Date;
69   import java.util.Enumeration;
70   import java.util.Iterator;
# Line 37 | Line 75 | import java.util.concurrent.BlockingQueu
75   import java.util.concurrent.Callable;
76   import java.util.concurrent.CountDownLatch;
77   import java.util.concurrent.CyclicBarrier;
78 + import java.util.concurrent.ExecutionException;
79 + import java.util.concurrent.Executor;
80 + import java.util.concurrent.Executors;
81   import java.util.concurrent.ExecutorService;
82 + import java.util.concurrent.ForkJoinPool;
83   import java.util.concurrent.Future;
84 + import java.util.concurrent.FutureTask;
85   import java.util.concurrent.RecursiveAction;
86   import java.util.concurrent.RecursiveTask;
87 + import java.util.concurrent.RejectedExecutionException;
88   import java.util.concurrent.RejectedExecutionHandler;
89   import java.util.concurrent.Semaphore;
90 + import java.util.concurrent.ScheduledExecutorService;
91 + import java.util.concurrent.ScheduledFuture;
92 + import java.util.concurrent.SynchronousQueue;
93   import java.util.concurrent.ThreadFactory;
94 + import java.util.concurrent.ThreadLocalRandom;
95   import java.util.concurrent.ThreadPoolExecutor;
96 + import java.util.concurrent.TimeUnit;
97   import java.util.concurrent.TimeoutException;
98 + import java.util.concurrent.atomic.AtomicBoolean;
99   import java.util.concurrent.atomic.AtomicReference;
100   import java.util.regex.Pattern;
101  
52 import junit.framework.AssertionFailedError;
102   import junit.framework.Test;
103   import junit.framework.TestCase;
104   import junit.framework.TestResult;
# Line 65 | Line 114 | import junit.framework.TestSuite;
114   *
115   * <ol>
116   *
117 < * <li> All assertions in code running in generated threads must use
117 > * <li>All assertions in code running in generated threads must use
118   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
119   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
120   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
121   * particularly recommended) for other code to use these forms too.
122   * Only the most typically used JUnit assertion methods are defined
123 < * this way, but enough to live with.</li>
123 > * this way, but enough to live with.
124   *
125 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
125 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
126   * to invoke {@code super.setUp} and {@code super.tearDown} within
127   * them. These methods are used to clear and check for thread
128 < * assertion failures.</li>
128 > * assertion failures.
129   *
130   * <li>All delays and timeouts must use one of the constants {@code
131   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 87 | Line 136 | import junit.framework.TestSuite;
136   * is always discriminable as larger than SHORT and smaller than
137   * MEDIUM.  And so on. These constants are set to conservative values,
138   * but even so, if there is ever any doubt, they can all be increased
139 < * in one spot to rerun tests on slower platforms.</li>
139 > * in one spot to rerun tests on slower platforms.
140   *
141 < * <li> All threads generated must be joined inside each test case
141 > * <li>All threads generated must be joined inside each test case
142   * method (or {@code fail} to do so) before returning from the
143   * method. The {@code joinPool} method can be used to do this when
144 < * using Executors.</li>
144 > * using Executors.
145   *
146   * </ol>
147   *
148   * <p><b>Other notes</b>
149   * <ul>
150   *
151 < * <li> Usually, there is one testcase method per JSR166 method
151 > * <li>Usually, there is one testcase method per JSR166 method
152   * covering "normal" operation, and then as many exception-testing
153   * methods as there are exceptions the method can throw. Sometimes
154   * there are multiple tests per JSR166 method when the different
155   * "normal" behaviors differ significantly. And sometimes testcases
156 < * cover multiple methods when they cannot be tested in
108 < * isolation.</li>
156 > * cover multiple methods when they cannot be tested in isolation.
157   *
158 < * <li> The documentation style for testcases is to provide as javadoc
158 > * <li>The documentation style for testcases is to provide as javadoc
159   * a simple sentence or two describing the property that the testcase
160   * method purports to test. The javadocs do not say anything about how
161 < * the property is tested. To find out, read the code.</li>
161 > * the property is tested. To find out, read the code.
162   *
163 < * <li> These tests are "conformance tests", and do not attempt to
163 > * <li>These tests are "conformance tests", and do not attempt to
164   * test throughput, latency, scalability or other performance factors
165   * (see the separate "jtreg" tests for a set intended to check these
166   * for the most central aspects of functionality.) So, most tests use
167   * the smallest sensible numbers of threads, collection sizes, etc
168 < * needed to check basic conformance.</li>
168 > * needed to check basic conformance.
169   *
170   * <li>The test classes currently do not declare inclusion in
171   * any particular package to simplify things for people integrating
172 < * them in TCK test suites.</li>
172 > * them in TCK test suites.
173   *
174 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
175 < * runs all JSR166 unit tests.</li>
174 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
175 > * runs all JSR166 unit tests.
176   *
177   * </ul>
178   */
# Line 168 | Line 216 | public class JSR166TestCase extends Test
216      private static final int suiteRuns =
217          Integer.getInteger("jsr166.suiteRuns", 1);
218  
219 +    /**
220 +     * Returns the value of the system property, or NaN if not defined.
221 +     */
222 +    private static float systemPropertyValue(String name) {
223 +        String floatString = System.getProperty(name);
224 +        if (floatString == null)
225 +            return Float.NaN;
226 +        try {
227 +            return Float.parseFloat(floatString);
228 +        } catch (NumberFormatException ex) {
229 +            throw new IllegalArgumentException(
230 +                String.format("Bad float value in system property %s=%s",
231 +                              name, floatString));
232 +        }
233 +    }
234 +
235 +    /**
236 +     * The scaling factor to apply to standard delays used in tests.
237 +     * May be initialized from any of:
238 +     * - the "jsr166.delay.factor" system property
239 +     * - the "test.timeout.factor" system property (as used by jtreg)
240 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
241 +     * - hard-coded fuzz factor when using a known slowpoke VM
242 +     */
243 +    private static final float delayFactor = delayFactor();
244 +
245 +    private static float delayFactor() {
246 +        float x;
247 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
248 +            return x;
249 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
250 +            return x;
251 +        String prop = System.getProperty("java.vm.version");
252 +        if (prop != null && prop.matches(".*debug.*"))
253 +            return 4.0f; // How much slower is fastdebug than product?!
254 +        return 1.0f;
255 +    }
256 +
257      public JSR166TestCase() { super(); }
258      public JSR166TestCase(String name) { super(name); }
259  
# Line 183 | Line 269 | public class JSR166TestCase extends Test
269          return (regex == null) ? null : Pattern.compile(regex);
270      }
271  
272 <    protected void runTest() throws Throwable {
272 >    // Instrumentation to debug very rare, but very annoying hung test runs.
273 >    static volatile TestCase currentTestCase;
274 >    // static volatile int currentRun = 0;
275 >    static {
276 >        Runnable checkForWedgedTest = new Runnable() { public void run() {
277 >            // Avoid spurious reports with enormous runsPerTest.
278 >            // A single test case run should never take more than 1 second.
279 >            // But let's cap it at the high end too ...
280 >            final int timeoutMinutes =
281 >                Math.min(15, Math.max(runsPerTest / 60, 1));
282 >            for (TestCase lastTestCase = currentTestCase;;) {
283 >                try { MINUTES.sleep(timeoutMinutes); }
284 >                catch (InterruptedException unexpected) { break; }
285 >                if (lastTestCase == currentTestCase) {
286 >                    System.err.printf(
287 >                        "Looks like we're stuck running test: %s%n",
288 >                        lastTestCase);
289 > //                     System.err.printf(
290 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
291 > //                         lastTestCase, currentRun, runsPerTest);
292 > //                     System.err.println("availableProcessors=" +
293 > //                         Runtime.getRuntime().availableProcessors());
294 > //                     System.err.printf("cpu model = %s%n", cpuModel());
295 >                    dumpTestThreads();
296 >                    // one stack dump is probably enough; more would be spam
297 >                    break;
298 >                }
299 >                lastTestCase = currentTestCase;
300 >            }}};
301 >        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
302 >        thread.setDaemon(true);
303 >        thread.start();
304 >    }
305 >
306 > //     public static String cpuModel() {
307 > //         try {
308 > //             java.util.regex.Matcher matcher
309 > //               = Pattern.compile("model name\\s*: (.*)")
310 > //                 .matcher(new String(
311 > //                     java.nio.file.Files.readAllBytes(
312 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
313 > //             matcher.find();
314 > //             return matcher.group(1);
315 > //         } catch (Exception ex) { return null; }
316 > //     }
317 >
318 >    public void runBare() throws Throwable {
319 >        currentTestCase = this;
320          if (methodFilter == null
321 <            || methodFilter.matcher(toString()).find()) {
322 <            for (int i = 0; i < runsPerTest; i++) {
323 <                if (profileTests)
324 <                    runTestProfiled();
325 <                else
326 <                    super.runTest();
327 <            }
321 >            || methodFilter.matcher(toString()).find())
322 >            super.runBare();
323 >    }
324 >
325 >    protected void runTest() throws Throwable {
326 >        for (int i = 0; i < runsPerTest; i++) {
327 >            // currentRun = i;
328 >            if (profileTests)
329 >                runTestProfiled();
330 >            else
331 >                super.runTest();
332          }
333      }
334  
335      protected void runTestProfiled() throws Throwable {
336 <        // Warmup run, notably to trigger all needed classloading.
337 <        super.runTest();
201 <        long t0 = System.nanoTime();
202 <        try {
336 >        for (int i = 0; i < 2; i++) {
337 >            long startTime = System.nanoTime();
338              super.runTest();
339 <        } finally {
340 <            long elapsedMillis = millisElapsedSince(t0);
341 <            if (elapsedMillis >= profileThreshold)
339 >            long elapsedMillis = millisElapsedSince(startTime);
340 >            if (elapsedMillis < profileThreshold)
341 >                break;
342 >            // Never report first run of any test; treat it as a
343 >            // warmup run, notably to trigger all needed classloading,
344 >            if (i > 0)
345                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
346          }
347      }
# Line 215 | Line 353 | public class JSR166TestCase extends Test
353          main(suite(), args);
354      }
355  
356 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
357 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
358 +        long runTime;
359 +        public void startTest(Test test) {}
360 +        protected void printHeader(long runTime) {
361 +            this.runTime = runTime; // defer printing for later
362 +        }
363 +        protected void printFooter(TestResult result) {
364 +            if (result.wasSuccessful()) {
365 +                getWriter().println("OK (" + result.runCount() + " tests)"
366 +                    + "  Time: " + elapsedTimeAsString(runTime));
367 +            } else {
368 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
369 +                super.printFooter(result);
370 +            }
371 +        }
372 +    }
373 +
374 +    /**
375 +     * Returns a TestRunner that doesn't bother with unnecessary
376 +     * fluff, like printing a "." for each test case.
377 +     */
378 +    static junit.textui.TestRunner newPithyTestRunner() {
379 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
380 +        runner.setPrinter(new PithyResultPrinter(System.out));
381 +        return runner;
382 +    }
383 +
384      /**
385       * Runs all unit tests in the given test suite.
386       * Actual behavior influenced by jsr166.* system properties.
# Line 226 | Line 392 | public class JSR166TestCase extends Test
392              System.setSecurityManager(new SecurityManager());
393          }
394          for (int i = 0; i < suiteRuns; i++) {
395 <            TestResult result = junit.textui.TestRunner.run(suite);
395 >            TestResult result = newPithyTestRunner().doRun(suite);
396              if (!result.wasSuccessful())
397                  System.exit(1);
398              System.gc();
# Line 278 | Line 444 | public class JSR166TestCase extends Test
444          }
445      }
446  
447 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
448 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
449 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
450 <    public static boolean atLeastJava9() {
451 <        return JAVA_CLASS_VERSION >= 53.0
286 <            // As of 2015-09, java9 still uses 52.0 class file version
287 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
288 <    }
289 <    public static boolean atLeastJava10() {
290 <        return JAVA_CLASS_VERSION >= 54.0
291 <            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
292 <    }
447 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
448 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
449 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
450 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
451 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
452  
453      /**
454       * Collects all JSR166 unit tests as one suite.
# Line 310 | Line 469 | public class JSR166TestCase extends Test
469              AbstractQueuedLongSynchronizerTest.suite(),
470              ArrayBlockingQueueTest.suite(),
471              ArrayDequeTest.suite(),
472 +            ArrayListTest.suite(),
473              AtomicBooleanTest.suite(),
474              AtomicIntegerArrayTest.suite(),
475              AtomicIntegerFieldUpdaterTest.suite(),
# Line 332 | Line 492 | public class JSR166TestCase extends Test
492              CopyOnWriteArrayListTest.suite(),
493              CopyOnWriteArraySetTest.suite(),
494              CountDownLatchTest.suite(),
495 +            CountedCompleterTest.suite(),
496              CyclicBarrierTest.suite(),
497              DelayQueueTest.suite(),
498              EntryTest.suite(),
# Line 360 | Line 521 | public class JSR166TestCase extends Test
521              TreeMapTest.suite(),
522              TreeSetTest.suite(),
523              TreeSubMapTest.suite(),
524 <            TreeSubSetTest.suite());
524 >            TreeSubSetTest.suite(),
525 >            VectorTest.suite());
526  
527          // Java8+ test classes
528          if (atLeastJava8()) {
529              String[] java8TestClassNames = {
530 +                "ArrayDeque8Test",
531                  "Atomic8Test",
532                  "CompletableFutureTest",
533                  "ConcurrentHashMap8Test",
534 <                "CountedCompleterTest",
534 >                "CountedCompleter8Test",
535                  "DoubleAccumulatorTest",
536                  "DoubleAdderTest",
537                  "ForkJoinPool8Test",
538                  "ForkJoinTask8Test",
539 +                "HashMapTest",
540 +                "LinkedBlockingDeque8Test",
541 +                "LinkedBlockingQueue8Test",
542                  "LongAccumulatorTest",
543                  "LongAdderTest",
544                  "SplittableRandomTest",
545                  "StampedLockTest",
546 +                "SubmissionPublisherTest",
547                  "ThreadLocalRandom8Test",
548 +                "TimeUnit8Test",
549              };
550              addNamedTestClasses(suite, java8TestClassNames);
551          }
# Line 385 | Line 553 | public class JSR166TestCase extends Test
553          // Java9+ test classes
554          if (atLeastJava9()) {
555              String[] java9TestClassNames = {
556 <                "ThreadPoolExecutor9Test",
556 >                "AtomicBoolean9Test",
557 >                "AtomicInteger9Test",
558 >                "AtomicIntegerArray9Test",
559 >                "AtomicLong9Test",
560 >                "AtomicLongArray9Test",
561 >                "AtomicReference9Test",
562 >                "AtomicReferenceArray9Test",
563 >                "ExecutorCompletionService9Test",
564 >                "ForkJoinPool9Test",
565              };
566              addNamedTestClasses(suite, java9TestClassNames);
567          }
# Line 396 | Line 572 | public class JSR166TestCase extends Test
572      /** Returns list of junit-style test method names in given class. */
573      public static ArrayList<String> testMethodNames(Class<?> testClass) {
574          Method[] methods = testClass.getDeclaredMethods();
575 <        ArrayList<String> names = new ArrayList<String>(methods.length);
575 >        ArrayList<String> names = new ArrayList<>(methods.length);
576          for (Method method : methods) {
577              if (method.getName().startsWith("test")
578                  && Modifier.isPublic(method.getModifiers())
# Line 452 | Line 628 | public class JSR166TestCase extends Test
628          } else {
629              return new TestSuite();
630          }
455
631      }
632  
633      // Delays for timing-dependent tests, in milliseconds.
# Line 462 | Line 637 | public class JSR166TestCase extends Test
637      public static long MEDIUM_DELAY_MS;
638      public static long LONG_DELAY_MS;
639  
640 +    private static final long RANDOM_TIMEOUT;
641 +    private static final long RANDOM_EXPIRED_TIMEOUT;
642 +    private static final TimeUnit RANDOM_TIMEUNIT;
643 +    static {
644 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
645 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
646 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
647 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
648 +        TimeUnit[] timeUnits = TimeUnit.values();
649 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
650 +    }
651 +
652 +    /**
653 +     * Returns a timeout for use when any value at all will do.
654 +     */
655 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
656 +
657      /**
658 <     * Returns the shortest timed delay. This could
659 <     * be reimplemented to use for example a Property.
658 >     * Returns a timeout that means "no waiting", i.e. not positive.
659 >     */
660 >    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
661 >
662 >    /**
663 >     * Returns a random non-null TimeUnit.
664 >     */
665 >    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
666 >
667 >    /**
668 >     * Returns the shortest timed delay. This can be scaled up for
669 >     * slow machines using the jsr166.delay.factor system property,
670 >     * or via jtreg's -timeoutFactor: flag.
671 >     * http://openjdk.java.net/jtreg/command-help.html
672       */
673      protected long getShortDelay() {
674 <        return 50;
674 >        return (long) (50 * delayFactor);
675      }
676  
677      /**
# Line 480 | Line 684 | public class JSR166TestCase extends Test
684          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
685      }
686  
687 +    private static final long TIMEOUT_DELAY_MS
688 +        = (long) (12.0 * Math.cbrt(delayFactor));
689 +
690      /**
691 <     * Returns a timeout in milliseconds to be used in tests that
692 <     * verify that operations block or time out.
691 >     * Returns a timeout in milliseconds to be used in tests that verify
692 >     * that operations block or time out.  We want this to be longer
693 >     * than the OS scheduling quantum, but not too long, so don't scale
694 >     * linearly with delayFactor; we use "crazy" cube root instead.
695       */
696 <    long timeoutMillis() {
697 <        return SHORT_DELAY_MS / 4;
696 >    static long timeoutMillis() {
697 >        return TIMEOUT_DELAY_MS;
698      }
699  
700      /**
# Line 501 | Line 710 | public class JSR166TestCase extends Test
710       * The first exception encountered if any threadAssertXXX method fails.
711       */
712      private final AtomicReference<Throwable> threadFailure
713 <        = new AtomicReference<Throwable>(null);
713 >        = new AtomicReference<>(null);
714  
715      /**
716       * Records an exception so that it can be rethrown later in the test
# Line 510 | Line 719 | public class JSR166TestCase extends Test
719       * the same test have no effect.
720       */
721      public void threadRecordFailure(Throwable t) {
722 +        System.err.println(t);
723 +        dumpTestThreads();
724          threadFailure.compareAndSet(null, t);
725      }
726  
# Line 517 | Line 728 | public class JSR166TestCase extends Test
728          setDelays();
729      }
730  
731 +    void tearDownFail(String format, Object... args) {
732 +        String msg = toString() + ": " + String.format(format, args);
733 +        System.err.println(msg);
734 +        dumpTestThreads();
735 +        throw new AssertionError(msg);
736 +    }
737 +
738      /**
739       * Extra checks that get done for all test cases.
740       *
# Line 535 | Line 753 | public class JSR166TestCase extends Test
753                  throw (RuntimeException) t;
754              else if (t instanceof Exception)
755                  throw (Exception) t;
756 <            else {
757 <                AssertionFailedError afe =
540 <                    new AssertionFailedError(t.toString());
541 <                afe.initCause(t);
542 <                throw afe;
543 <            }
756 >            else
757 >                throw new AssertionError(t.toString(), t);
758          }
759  
760          if (Thread.interrupted())
761 <            throw new AssertionFailedError("interrupt status set in main thread");
761 >            tearDownFail("interrupt status set in main thread");
762  
763          checkForkJoinPoolThreadLeaks();
764      }
765  
766      /**
767 <     * Finds missing try { ... } finally { joinPool(e); }
767 >     * Finds missing PoolCleaners
768       */
769      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
770 <        Thread[] survivors = new Thread[5];
770 >        Thread[] survivors = new Thread[7];
771          int count = Thread.enumerate(survivors);
772          for (int i = 0; i < count; i++) {
773              Thread thread = survivors[i];
# Line 561 | Line 775 | public class JSR166TestCase extends Test
775              if (name.startsWith("ForkJoinPool-")) {
776                  // give thread some time to terminate
777                  thread.join(LONG_DELAY_MS);
778 <                if (!thread.isAlive()) continue;
779 <                throw new AssertionFailedError
780 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
567 <                                   toString(), name));
778 >                if (thread.isAlive())
779 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
780 >                                 thread);
781              }
782          }
783 +
784 +        if (!ForkJoinPool.commonPool()
785 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
786 +            tearDownFail("ForkJoin common pool thread stuck");
787      }
788  
789      /**
790       * Just like fail(reason), but additionally recording (using
791 <     * threadRecordFailure) any AssertionFailedError thrown, so that
792 <     * the current testcase will fail.
791 >     * threadRecordFailure) any AssertionError thrown, so that the
792 >     * current testcase will fail.
793       */
794      public void threadFail(String reason) {
795          try {
796              fail(reason);
797 <        } catch (AssertionFailedError t) {
798 <            threadRecordFailure(t);
799 <            fail(reason);
797 >        } catch (AssertionError fail) {
798 >            threadRecordFailure(fail);
799 >            throw fail;
800          }
801      }
802  
803      /**
804       * Just like assertTrue(b), but additionally recording (using
805 <     * threadRecordFailure) any AssertionFailedError thrown, so that
806 <     * the current testcase will fail.
805 >     * threadRecordFailure) any AssertionError thrown, so that the
806 >     * current testcase will fail.
807       */
808      public void threadAssertTrue(boolean b) {
809          try {
810              assertTrue(b);
811 <        } catch (AssertionFailedError t) {
812 <            threadRecordFailure(t);
813 <            throw t;
811 >        } catch (AssertionError fail) {
812 >            threadRecordFailure(fail);
813 >            throw fail;
814          }
815      }
816  
817      /**
818       * Just like assertFalse(b), but additionally recording (using
819 <     * threadRecordFailure) any AssertionFailedError thrown, so that
820 <     * the current testcase will fail.
819 >     * threadRecordFailure) any AssertionError thrown, so that the
820 >     * current testcase will fail.
821       */
822      public void threadAssertFalse(boolean b) {
823          try {
824              assertFalse(b);
825 <        } catch (AssertionFailedError t) {
826 <            threadRecordFailure(t);
827 <            throw t;
825 >        } catch (AssertionError fail) {
826 >            threadRecordFailure(fail);
827 >            throw fail;
828          }
829      }
830  
831      /**
832       * Just like assertNull(x), but additionally recording (using
833 <     * threadRecordFailure) any AssertionFailedError thrown, so that
834 <     * the current testcase will fail.
833 >     * threadRecordFailure) any AssertionError thrown, so that the
834 >     * current testcase will fail.
835       */
836      public void threadAssertNull(Object x) {
837          try {
838              assertNull(x);
839 <        } catch (AssertionFailedError t) {
840 <            threadRecordFailure(t);
841 <            throw t;
839 >        } catch (AssertionError fail) {
840 >            threadRecordFailure(fail);
841 >            throw fail;
842          }
843      }
844  
845      /**
846       * Just like assertEquals(x, y), but additionally recording (using
847 <     * threadRecordFailure) any AssertionFailedError thrown, so that
848 <     * the current testcase will fail.
847 >     * threadRecordFailure) any AssertionError thrown, so that the
848 >     * current testcase will fail.
849       */
850      public void threadAssertEquals(long x, long y) {
851          try {
852              assertEquals(x, y);
853 <        } catch (AssertionFailedError t) {
854 <            threadRecordFailure(t);
855 <            throw t;
853 >        } catch (AssertionError fail) {
854 >            threadRecordFailure(fail);
855 >            throw fail;
856          }
857      }
858  
859      /**
860       * Just like assertEquals(x, y), but additionally recording (using
861 <     * threadRecordFailure) any AssertionFailedError thrown, so that
862 <     * the current testcase will fail.
861 >     * threadRecordFailure) any AssertionError thrown, so that the
862 >     * current testcase will fail.
863       */
864      public void threadAssertEquals(Object x, Object y) {
865          try {
866              assertEquals(x, y);
867 <        } catch (AssertionFailedError fail) {
867 >        } catch (AssertionError fail) {
868              threadRecordFailure(fail);
869              throw fail;
870          } catch (Throwable fail) {
# Line 657 | Line 874 | public class JSR166TestCase extends Test
874  
875      /**
876       * Just like assertSame(x, y), but additionally recording (using
877 <     * threadRecordFailure) any AssertionFailedError thrown, so that
878 <     * the current testcase will fail.
877 >     * threadRecordFailure) any AssertionError thrown, so that the
878 >     * current testcase will fail.
879       */
880      public void threadAssertSame(Object x, Object y) {
881          try {
882              assertSame(x, y);
883 <        } catch (AssertionFailedError fail) {
883 >        } catch (AssertionError fail) {
884              threadRecordFailure(fail);
885              throw fail;
886          }
# Line 685 | Line 902 | public class JSR166TestCase extends Test
902  
903      /**
904       * Records the given exception using {@link #threadRecordFailure},
905 <     * then rethrows the exception, wrapping it in an
906 <     * AssertionFailedError if necessary.
905 >     * then rethrows the exception, wrapping it in an AssertionError
906 >     * if necessary.
907       */
908      public void threadUnexpectedException(Throwable t) {
909          threadRecordFailure(t);
# Line 695 | Line 912 | public class JSR166TestCase extends Test
912              throw (RuntimeException) t;
913          else if (t instanceof Error)
914              throw (Error) t;
915 <        else {
916 <            AssertionFailedError afe =
700 <                new AssertionFailedError("unexpected exception: " + t);
701 <            afe.initCause(t);
702 <            throw afe;
703 <        }
915 >        else
916 >            throw new AssertionError("unexpected exception: " + t, t);
917      }
918  
919      /**
920       * Delays, via Thread.sleep, for the given millisecond delay, but
921       * if the sleep is shorter than specified, may re-sleep or yield
922 <     * until time elapses.
922 >     * until time elapses.  Ensures that the given time, as measured
923 >     * by System.nanoTime(), has elapsed.
924       */
925      static void delay(long millis) throws InterruptedException {
926 <        long startTime = System.nanoTime();
927 <        long ns = millis * 1000 * 1000;
928 <        for (;;) {
926 >        long nanos = millis * (1000 * 1000);
927 >        final long wakeupTime = System.nanoTime() + nanos;
928 >        do {
929              if (millis > 0L)
930                  Thread.sleep(millis);
931              else // too short to sleep
932                  Thread.yield();
933 <            long d = ns - (System.nanoTime() - startTime);
934 <            if (d > 0L)
935 <                millis = d / (1000 * 1000);
936 <            else
937 <                break;
933 >            nanos = wakeupTime - System.nanoTime();
934 >            millis = nanos / (1000 * 1000);
935 >        } while (nanos >= 0L);
936 >    }
937 >
938 >    /**
939 >     * Allows use of try-with-resources with per-test thread pools.
940 >     */
941 >    class PoolCleaner implements AutoCloseable {
942 >        private final ExecutorService pool;
943 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
944 >        public void close() { joinPool(pool); }
945 >    }
946 >
947 >    /**
948 >     * An extension of PoolCleaner that has an action to release the pool.
949 >     */
950 >    class PoolCleanerWithReleaser extends PoolCleaner {
951 >        private final Runnable releaser;
952 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
953 >            super(pool);
954 >            this.releaser = releaser;
955 >        }
956 >        public void close() {
957 >            try {
958 >                releaser.run();
959 >            } finally {
960 >                super.close();
961 >            }
962          }
963      }
964  
965 +    PoolCleaner cleaner(ExecutorService pool) {
966 +        return new PoolCleaner(pool);
967 +    }
968 +
969 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
970 +        return new PoolCleanerWithReleaser(pool, releaser);
971 +    }
972 +
973 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
974 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
975 +    }
976 +
977 +    Runnable releaser(final CountDownLatch latch) {
978 +        return new Runnable() { public void run() {
979 +            do { latch.countDown(); }
980 +            while (latch.getCount() > 0);
981 +        }};
982 +    }
983 +
984 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
985 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
986 +    }
987 +
988 +    Runnable releaser(final AtomicBoolean flag) {
989 +        return new Runnable() { public void run() { flag.set(true); }};
990 +    }
991 +
992      /**
993       * Waits out termination of a thread pool or fails doing so.
994       */
995 <    void joinPool(ExecutorService exec) {
995 >    void joinPool(ExecutorService pool) {
996          try {
997 <            exec.shutdown();
998 <            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
999 <                fail("ExecutorService " + exec +
1000 <                     " did not terminate in a timely manner");
997 >            pool.shutdown();
998 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
999 >                try {
1000 >                    threadFail("ExecutorService " + pool +
1001 >                               " did not terminate in a timely manner");
1002 >                } finally {
1003 >                    // last resort, for the benefit of subsequent tests
1004 >                    pool.shutdownNow();
1005 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1006 >                }
1007 >            }
1008          } catch (SecurityException ok) {
1009              // Allowed in case test doesn't have privs
1010          } catch (InterruptedException fail) {
1011 <            fail("Unexpected InterruptedException");
1011 >            threadFail("Unexpected InterruptedException");
1012          }
1013      }
1014  
1015      /**
1016 <     * A debugging tool to print all stack traces, as jstack does.
1016 >     * Like Runnable, but with the freedom to throw anything.
1017 >     * junit folks had the same idea:
1018 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1019       */
1020 <    static void printAllStackTraces() {
747 <        for (ThreadInfo info :
748 <                 ManagementFactory.getThreadMXBean()
749 <                 .dumpAllThreads(true, true))
750 <            System.err.print(info);
751 <    }
1020 >    interface Action { public void run() throws Throwable; }
1021  
1022      /**
1023 <     * Checks that thread does not terminate within the default
1024 <     * millisecond delay of {@code timeoutMillis()}.
1023 >     * Runs all the given actions in parallel, failing if any fail.
1024 >     * Useful for running multiple variants of tests that are
1025 >     * necessarily individually slow because they must block.
1026       */
1027 <    void assertThreadStaysAlive(Thread thread) {
1028 <        assertThreadStaysAlive(thread, timeoutMillis());
1027 >    void testInParallel(Action ... actions) {
1028 >        ExecutorService pool = Executors.newCachedThreadPool();
1029 >        try (PoolCleaner cleaner = cleaner(pool)) {
1030 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1031 >            for (final Action action : actions)
1032 >                futures.add(pool.submit(new CheckedRunnable() {
1033 >                    public void realRun() throws Throwable { action.run();}}));
1034 >            for (Future<?> future : futures)
1035 >                try {
1036 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1037 >                } catch (ExecutionException ex) {
1038 >                    threadUnexpectedException(ex.getCause());
1039 >                } catch (Exception ex) {
1040 >                    threadUnexpectedException(ex);
1041 >                }
1042 >        }
1043      }
1044  
1045      /**
1046 <     * Checks that thread does not terminate within the given millisecond delay.
1046 >     * A debugging tool to print stack traces of most threads, as jstack does.
1047 >     * Uninteresting threads are filtered out.
1048       */
1049 <    void assertThreadStaysAlive(Thread thread, long millis) {
1050 <        try {
1051 <            // No need to optimize the failing case via Thread.join.
1052 <            delay(millis);
1053 <            assertTrue(thread.isAlive());
1054 <        } catch (InterruptedException fail) {
1055 <            fail("Unexpected InterruptedException");
1049 >    static void dumpTestThreads() {
1050 >        SecurityManager sm = System.getSecurityManager();
1051 >        if (sm != null) {
1052 >            try {
1053 >                System.setSecurityManager(null);
1054 >            } catch (SecurityException giveUp) {
1055 >                return;
1056 >            }
1057          }
772    }
1058  
1059 <    /**
1060 <     * Checks that the threads do not terminate within the default
1061 <     * millisecond delay of {@code timeoutMillis()}.
1062 <     */
1063 <    void assertThreadsStayAlive(Thread... threads) {
1064 <        assertThreadsStayAlive(timeoutMillis(), threads);
1059 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1060 >        System.err.println("------ stacktrace dump start ------");
1061 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1062 >            final String name = info.getThreadName();
1063 >            String lockName;
1064 >            if ("Signal Dispatcher".equals(name))
1065 >                continue;
1066 >            if ("Reference Handler".equals(name)
1067 >                && (lockName = info.getLockName()) != null
1068 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1069 >                continue;
1070 >            if ("Finalizer".equals(name)
1071 >                && (lockName = info.getLockName()) != null
1072 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1073 >                continue;
1074 >            if ("checkForWedgedTest".equals(name))
1075 >                continue;
1076 >            System.err.print(info);
1077 >        }
1078 >        System.err.println("------ stacktrace dump end ------");
1079 >
1080 >        if (sm != null) System.setSecurityManager(sm);
1081      }
1082  
1083      /**
1084 <     * Checks that the threads do not terminate within the given millisecond delay.
1084 >     * Checks that thread eventually enters the expected blocked thread state.
1085       */
1086 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1087 <        try {
1088 <            // No need to optimize the failing case via Thread.join.
1089 <            delay(millis);
1090 <            for (Thread thread : threads)
1091 <                assertTrue(thread.isAlive());
1092 <        } catch (InterruptedException fail) {
1093 <            fail("Unexpected InterruptedException");
1086 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1087 >        // always sleep at least 1 ms, with high probability avoiding
1088 >        // transitory states
1089 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1090 >            try { delay(1); }
1091 >            catch (InterruptedException fail) {
1092 >                fail("Unexpected InterruptedException");
1093 >            }
1094 >            Thread.State s = thread.getState();
1095 >            if (s == expected)
1096 >                return;
1097 >            else if (s == Thread.State.TERMINATED)
1098 >                fail("Unexpected thread termination");
1099          }
1100 +        fail("timed out waiting for thread to enter thread state " + expected);
1101      }
1102  
1103      /**
# Line 831 | Line 1138 | public class JSR166TestCase extends Test
1138      }
1139  
1140      /**
1141 +     * The maximum number of consecutive spurious wakeups we should
1142 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1143 +     */
1144 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1145 +
1146 +    /**
1147       * The number of elements to place in collections, arrays, etc.
1148       */
1149      public static final int SIZE = 20;
# Line 934 | Line 1247 | public class JSR166TestCase extends Test
1247          }
1248          public void refresh() {}
1249          public String toString() {
1250 <            List<Permission> ps = new ArrayList<Permission>();
1250 >            List<Permission> ps = new ArrayList<>();
1251              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1252                  ps.add(e.nextElement());
1253              return "AdjustablePolicy with permissions " + ps;
# Line 962 | Line 1275 | public class JSR166TestCase extends Test
1275  
1276      /**
1277       * Sleeps until the given time has elapsed.
1278 <     * Throws AssertionFailedError if interrupted.
1278 >     * Throws AssertionError if interrupted.
1279       */
1280 <    void sleep(long millis) {
1280 >    static void sleep(long millis) {
1281          try {
1282              delay(millis);
1283          } catch (InterruptedException fail) {
1284 <            AssertionFailedError afe =
972 <                new AssertionFailedError("Unexpected InterruptedException");
973 <            afe.initCause(fail);
974 <            throw afe;
1284 >            throw new AssertionError("Unexpected InterruptedException", fail);
1285          }
1286      }
1287  
# Line 980 | Line 1290 | public class JSR166TestCase extends Test
1290       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1291       */
1292      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1293 <        long startTime = System.nanoTime();
1293 >        long startTime = 0L;
1294          for (;;) {
1295              Thread.State s = thread.getState();
1296              if (s == Thread.State.BLOCKED ||
# Line 989 | Line 1299 | public class JSR166TestCase extends Test
1299                  return;
1300              else if (s == Thread.State.TERMINATED)
1301                  fail("Unexpected thread termination");
1302 +            else if (startTime == 0L)
1303 +                startTime = System.nanoTime();
1304              else if (millisElapsedSince(startTime) > timeoutMillis) {
1305                  threadAssertTrue(thread.isAlive());
1306 <                return;
1306 >                fail("timed out waiting for thread to enter wait state");
1307 >            }
1308 >            Thread.yield();
1309 >        }
1310 >    }
1311 >
1312 >    /**
1313 >     * Spin-waits up to the specified number of milliseconds for the given
1314 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1315 >     * and additionally satisfy the given condition.
1316 >     */
1317 >    void waitForThreadToEnterWaitState(
1318 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1319 >        long startTime = 0L;
1320 >        for (;;) {
1321 >            Thread.State s = thread.getState();
1322 >            if (s == Thread.State.BLOCKED ||
1323 >                s == Thread.State.WAITING ||
1324 >                s == Thread.State.TIMED_WAITING) {
1325 >                try {
1326 >                    if (waitingForGodot.call())
1327 >                        return;
1328 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1329 >            }
1330 >            else if (s == Thread.State.TERMINATED)
1331 >                fail("Unexpected thread termination");
1332 >            else if (startTime == 0L)
1333 >                startTime = System.nanoTime();
1334 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1335 >                threadAssertTrue(thread.isAlive());
1336 >                fail("timed out waiting for thread to enter wait state");
1337              }
1338              Thread.yield();
1339          }
1340      }
1341  
1342      /**
1343 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1344 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1343 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1344 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1345       */
1346      void waitForThreadToEnterWaitState(Thread thread) {
1347          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1348      }
1349  
1350      /**
1351 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1352 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1353 +     * and additionally satisfy the given condition.
1354 +     */
1355 +    void waitForThreadToEnterWaitState(
1356 +        Thread thread, Callable<Boolean> waitingForGodot) {
1357 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1358 +    }
1359 +
1360 +    /**
1361       * Returns the number of milliseconds since time given by
1362       * startNanoTime, which must have been previously returned from a
1363       * call to {@link System#nanoTime()}.
# Line 1020 | Line 1372 | public class JSR166TestCase extends Test
1372   //             r.run();
1373   //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1374   //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1375 < //             throw new AssertionFailedError("did not return promptly");
1375 > //             throw new AssertionError("did not return promptly");
1376   //     }
1377  
1378   //     void assertTerminatesPromptly(Runnable r) {
# Line 1037 | Line 1389 | public class JSR166TestCase extends Test
1389              assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1390          } catch (Throwable fail) { threadUnexpectedException(fail); }
1391          if (millisElapsedSince(startTime) > timeoutMillis/2)
1392 <            throw new AssertionFailedError("timed get did not return promptly");
1392 >            throw new AssertionError("timed get did not return promptly");
1393      }
1394  
1395      <T> void checkTimedGet(Future<T> f, T expectedValue) {
# Line 1067 | Line 1419 | public class JSR166TestCase extends Test
1419          } finally {
1420              if (t.getState() != Thread.State.TERMINATED) {
1421                  t.interrupt();
1422 <                fail("Test timed out");
1422 >                threadFail("timed out waiting for thread to terminate");
1423              }
1424          }
1425      }
# Line 1192 | Line 1544 | public class JSR166TestCase extends Test
1544      public static final String TEST_STRING = "a test string";
1545  
1546      public static class StringTask implements Callable<String> {
1547 <        public String call() { return TEST_STRING; }
1547 >        final String value;
1548 >        public StringTask() { this(TEST_STRING); }
1549 >        public StringTask(String value) { this.value = value; }
1550 >        public String call() { return value; }
1551      }
1552  
1553      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1205 | Line 1560 | public class JSR166TestCase extends Test
1560              }};
1561      }
1562  
1563 <    public Runnable awaiter(final CountDownLatch latch) {
1563 >    public Runnable countDowner(final CountDownLatch latch) {
1564          return new CheckedRunnable() {
1565              public void realRun() throws InterruptedException {
1566 <                await(latch);
1566 >                latch.countDown();
1567              }};
1568      }
1569  
1570 <    public void await(CountDownLatch latch) {
1570 >    class LatchAwaiter extends CheckedRunnable {
1571 >        static final int NEW = 0;
1572 >        static final int RUNNING = 1;
1573 >        static final int DONE = 2;
1574 >        final CountDownLatch latch;
1575 >        int state = NEW;
1576 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1577 >        public void realRun() throws InterruptedException {
1578 >            state = 1;
1579 >            await(latch);
1580 >            state = 2;
1581 >        }
1582 >    }
1583 >
1584 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1585 >        return new LatchAwaiter(latch);
1586 >    }
1587 >
1588 >    public void await(CountDownLatch latch, long timeoutMillis) {
1589          try {
1590 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1590 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1591 >                fail("timed out waiting for CountDownLatch for "
1592 >                     + (timeoutMillis/1000) + " sec");
1593          } catch (Throwable fail) {
1594              threadUnexpectedException(fail);
1595          }
1596      }
1597  
1598 +    public void await(CountDownLatch latch) {
1599 +        await(latch, LONG_DELAY_MS);
1600 +    }
1601 +
1602      public void await(Semaphore semaphore) {
1603          try {
1604 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1604 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1605 >                fail("timed out waiting for Semaphore for "
1606 >                     + (LONG_DELAY_MS/1000) + " sec");
1607 >        } catch (Throwable fail) {
1608 >            threadUnexpectedException(fail);
1609 >        }
1610 >    }
1611 >
1612 >    public void await(CyclicBarrier barrier) {
1613 >        try {
1614 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1615          } catch (Throwable fail) {
1616              threadUnexpectedException(fail);
1617          }
# Line 1242 | Line 1631 | public class JSR166TestCase extends Test
1631   //         long startTime = System.nanoTime();
1632   //         while (!flag.get()) {
1633   //             if (millisElapsedSince(startTime) > timeoutMillis)
1634 < //                 throw new AssertionFailedError("timed out");
1634 > //                 throw new AssertionError("timed out");
1635   //             Thread.yield();
1636   //         }
1637   //     }
# Line 1251 | Line 1640 | public class JSR166TestCase extends Test
1640          public String call() { throw new NullPointerException(); }
1641      }
1642  
1254    public static class CallableOne implements Callable<Integer> {
1255        public Integer call() { return one; }
1256    }
1257
1258    public class ShortRunnable extends CheckedRunnable {
1259        protected void realRun() throws Throwable {
1260            delay(SHORT_DELAY_MS);
1261        }
1262    }
1263
1264    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1265        protected void realRun() throws InterruptedException {
1266            delay(SHORT_DELAY_MS);
1267        }
1268    }
1269
1270    public class SmallRunnable extends CheckedRunnable {
1271        protected void realRun() throws Throwable {
1272            delay(SMALL_DELAY_MS);
1273        }
1274    }
1275
1643      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1644          protected void realRun() {
1645              try {
# Line 1281 | Line 1648 | public class JSR166TestCase extends Test
1648          }
1649      }
1650  
1284    public class SmallCallable extends CheckedCallable {
1285        protected Object realCall() throws InterruptedException {
1286            delay(SMALL_DELAY_MS);
1287            return Boolean.TRUE;
1288        }
1289    }
1290
1291    public class MediumRunnable extends CheckedRunnable {
1292        protected void realRun() throws Throwable {
1293            delay(MEDIUM_DELAY_MS);
1294        }
1295    }
1296
1297    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1298        protected void realRun() throws InterruptedException {
1299            delay(MEDIUM_DELAY_MS);
1300        }
1301    }
1302
1651      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1652          return new CheckedRunnable() {
1653              protected void realRun() {
# Line 1309 | Line 1657 | public class JSR166TestCase extends Test
1657              }};
1658      }
1659  
1312    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1313        protected void realRun() {
1314            try {
1315                delay(MEDIUM_DELAY_MS);
1316            } catch (InterruptedException ok) {}
1317        }
1318    }
1319
1320    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1321        protected void realRun() {
1322            try {
1323                delay(LONG_DELAY_MS);
1324            } catch (InterruptedException ok) {}
1325        }
1326    }
1327
1660      /**
1661       * For use as ThreadFactory in constructors
1662       */
# Line 1338 | Line 1670 | public class JSR166TestCase extends Test
1670          boolean isDone();
1671      }
1672  
1341    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1342        return new TrackedRunnable() {
1343                private volatile boolean done = false;
1344                public boolean isDone() { return done; }
1345                public void run() {
1346                    try {
1347                        delay(timeoutMillis);
1348                        done = true;
1349                    } catch (InterruptedException ok) {}
1350                }
1351            };
1352    }
1353
1354    public static class TrackedShortRunnable implements Runnable {
1355        public volatile boolean done = false;
1356        public void run() {
1357            try {
1358                delay(SHORT_DELAY_MS);
1359                done = true;
1360            } catch (InterruptedException ok) {}
1361        }
1362    }
1363
1364    public static class TrackedSmallRunnable implements Runnable {
1365        public volatile boolean done = false;
1366        public void run() {
1367            try {
1368                delay(SMALL_DELAY_MS);
1369                done = true;
1370            } catch (InterruptedException ok) {}
1371        }
1372    }
1373
1374    public static class TrackedMediumRunnable implements Runnable {
1375        public volatile boolean done = false;
1376        public void run() {
1377            try {
1378                delay(MEDIUM_DELAY_MS);
1379                done = true;
1380            } catch (InterruptedException ok) {}
1381        }
1382    }
1383
1384    public static class TrackedLongRunnable implements Runnable {
1385        public volatile boolean done = false;
1386        public void run() {
1387            try {
1388                delay(LONG_DELAY_MS);
1389                done = true;
1390            } catch (InterruptedException ok) {}
1391        }
1392    }
1393
1673      public static class TrackedNoOpRunnable implements Runnable {
1674          public volatile boolean done = false;
1675          public void run() {
# Line 1398 | Line 1677 | public class JSR166TestCase extends Test
1677          }
1678      }
1679  
1401    public static class TrackedCallable implements Callable {
1402        public volatile boolean done = false;
1403        public Object call() {
1404            try {
1405                delay(SMALL_DELAY_MS);
1406                done = true;
1407            } catch (InterruptedException ok) {}
1408            return Boolean.TRUE;
1409        }
1410    }
1411
1680      /**
1681       * Analog of CheckedRunnable for RecursiveAction
1682       */
# Line 1450 | Line 1718 | public class JSR166TestCase extends Test
1718  
1719      /**
1720       * A CyclicBarrier that uses timed await and fails with
1721 <     * AssertionFailedErrors instead of throwing checked exceptions.
1721 >     * AssertionErrors instead of throwing checked exceptions.
1722       */
1723 <    public class CheckedBarrier extends CyclicBarrier {
1723 >    public static class CheckedBarrier extends CyclicBarrier {
1724          public CheckedBarrier(int parties) { super(parties); }
1725  
1726          public int await() {
1727              try {
1728                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1729              } catch (TimeoutException timedOut) {
1730 <                throw new AssertionFailedError("timed out");
1730 >                throw new AssertionError("timed out");
1731              } catch (Exception fail) {
1732 <                AssertionFailedError afe =
1465 <                    new AssertionFailedError("Unexpected exception: " + fail);
1466 <                afe.initCause(fail);
1467 <                throw afe;
1732 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1733              }
1734          }
1735      }
# Line 1475 | Line 1740 | public class JSR166TestCase extends Test
1740              assertEquals(0, q.size());
1741              assertNull(q.peek());
1742              assertNull(q.poll());
1743 <            assertNull(q.poll(0, MILLISECONDS));
1743 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1744              assertEquals(q.toString(), "[]");
1745              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1746              assertFalse(q.iterator().hasNext());
# Line 1516 | Line 1781 | public class JSR166TestCase extends Test
1781          }
1782      }
1783  
1784 +    void assertImmutable(final Object o) {
1785 +        if (o instanceof Collection) {
1786 +            assertThrows(
1787 +                UnsupportedOperationException.class,
1788 +                new Runnable() { public void run() {
1789 +                        ((Collection) o).add(null);}});
1790 +        }
1791 +    }
1792 +
1793      @SuppressWarnings("unchecked")
1794      <T> T serialClone(T o) {
1795          try {
1796              ObjectInputStream ois = new ObjectInputStream
1797                  (new ByteArrayInputStream(serialBytes(o)));
1798              T clone = (T) ois.readObject();
1799 +            if (o == clone) assertImmutable(o);
1800              assertSame(o.getClass(), clone.getClass());
1801              return clone;
1802          } catch (Throwable fail) {
# Line 1530 | Line 1805 | public class JSR166TestCase extends Test
1805          }
1806      }
1807  
1808 +    /**
1809 +     * A version of serialClone that leaves error handling (for
1810 +     * e.g. NotSerializableException) up to the caller.
1811 +     */
1812 +    @SuppressWarnings("unchecked")
1813 +    <T> T serialClonePossiblyFailing(T o)
1814 +        throws ReflectiveOperationException, java.io.IOException {
1815 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1816 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1817 +        oos.writeObject(o);
1818 +        oos.flush();
1819 +        oos.close();
1820 +        ObjectInputStream ois = new ObjectInputStream
1821 +            (new ByteArrayInputStream(bos.toByteArray()));
1822 +        T clone = (T) ois.readObject();
1823 +        if (o == clone) assertImmutable(o);
1824 +        assertSame(o.getClass(), clone.getClass());
1825 +        return clone;
1826 +    }
1827 +
1828 +    /**
1829 +     * If o implements Cloneable and has a public clone method,
1830 +     * returns a clone of o, else null.
1831 +     */
1832 +    @SuppressWarnings("unchecked")
1833 +    <T> T cloneableClone(T o) {
1834 +        if (!(o instanceof Cloneable)) return null;
1835 +        final T clone;
1836 +        try {
1837 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1838 +        } catch (NoSuchMethodException ok) {
1839 +            return null;
1840 +        } catch (ReflectiveOperationException unexpected) {
1841 +            throw new Error(unexpected);
1842 +        }
1843 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1844 +        assertSame(o.getClass(), clone.getClass());
1845 +        return clone;
1846 +    }
1847 +
1848      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1849                               Runnable... throwingActions) {
1850          for (Runnable throwingAction : throwingActions) {
# Line 1537 | Line 1852 | public class JSR166TestCase extends Test
1852              try { throwingAction.run(); }
1853              catch (Throwable t) {
1854                  threw = true;
1855 <                if (!expectedExceptionClass.isInstance(t)) {
1856 <                    AssertionFailedError afe =
1857 <                        new AssertionFailedError
1858 <                        ("Expected " + expectedExceptionClass.getName() +
1859 <                         ", got " + t.getClass().getName());
1545 <                    afe.initCause(t);
1546 <                    threadUnexpectedException(afe);
1547 <                }
1855 >                if (!expectedExceptionClass.isInstance(t))
1856 >                    throw new AssertionError(
1857 >                            "Expected " + expectedExceptionClass.getName() +
1858 >                            ", got " + t.getClass().getName(),
1859 >                            t);
1860              }
1861              if (!threw)
1862                  shouldThrow(expectedExceptionClass.getName());
# Line 1558 | Line 1870 | public class JSR166TestCase extends Test
1870          } catch (NoSuchElementException success) {}
1871          assertFalse(it.hasNext());
1872      }
1873 +
1874 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1875 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1876 +    }
1877 +
1878 +    public Runnable runnableThrowing(final RuntimeException ex) {
1879 +        return new Runnable() { public void run() { throw ex; }};
1880 +    }
1881 +
1882 +    /** A reusable thread pool to be shared by tests. */
1883 +    static final ExecutorService cachedThreadPool =
1884 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1885 +                               1000L, MILLISECONDS,
1886 +                               new SynchronousQueue<Runnable>());
1887 +
1888 +    static <T> void shuffle(T[] array) {
1889 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1890 +    }
1891 +
1892 +    /**
1893 +     * Returns the same String as would be returned by {@link
1894 +     * Object#toString}, whether or not the given object's class
1895 +     * overrides toString().
1896 +     *
1897 +     * @see System#identityHashCode
1898 +     */
1899 +    static String identityString(Object x) {
1900 +        return x.getClass().getName()
1901 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1902 +    }
1903 +
1904 +    // --- Shared assertions for Executor tests ---
1905 +
1906 +    /**
1907 +     * Returns maximum number of tasks that can be submitted to given
1908 +     * pool (with bounded queue) before saturation (when submission
1909 +     * throws RejectedExecutionException).
1910 +     */
1911 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1912 +        BlockingQueue<Runnable> q = pool.getQueue();
1913 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1914 +    }
1915 +
1916 +    @SuppressWarnings("FutureReturnValueIgnored")
1917 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1918 +        try {
1919 +            e.execute((Runnable) null);
1920 +            shouldThrow();
1921 +        } catch (NullPointerException success) {}
1922 +
1923 +        if (! (e instanceof ExecutorService)) return;
1924 +        ExecutorService es = (ExecutorService) e;
1925 +        try {
1926 +            es.submit((Runnable) null);
1927 +            shouldThrow();
1928 +        } catch (NullPointerException success) {}
1929 +        try {
1930 +            es.submit((Runnable) null, Boolean.TRUE);
1931 +            shouldThrow();
1932 +        } catch (NullPointerException success) {}
1933 +        try {
1934 +            es.submit((Callable) null);
1935 +            shouldThrow();
1936 +        } catch (NullPointerException success) {}
1937 +
1938 +        if (! (e instanceof ScheduledExecutorService)) return;
1939 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1940 +        try {
1941 +            ses.schedule((Runnable) null,
1942 +                         randomTimeout(), randomTimeUnit());
1943 +            shouldThrow();
1944 +        } catch (NullPointerException success) {}
1945 +        try {
1946 +            ses.schedule((Callable) null,
1947 +                         randomTimeout(), randomTimeUnit());
1948 +            shouldThrow();
1949 +        } catch (NullPointerException success) {}
1950 +        try {
1951 +            ses.scheduleAtFixedRate((Runnable) null,
1952 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1953 +            shouldThrow();
1954 +        } catch (NullPointerException success) {}
1955 +        try {
1956 +            ses.scheduleWithFixedDelay((Runnable) null,
1957 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1958 +            shouldThrow();
1959 +        } catch (NullPointerException success) {}
1960 +    }
1961 +
1962 +    void setRejectedExecutionHandler(
1963 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1964 +        p.setRejectedExecutionHandler(handler);
1965 +        assertSame(handler, p.getRejectedExecutionHandler());
1966 +    }
1967 +
1968 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1969 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1970 +        final long savedTaskCount = p.getTaskCount();
1971 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1972 +        final int savedQueueSize = p.getQueue().size();
1973 +        final boolean stock = (p.getClass().getClassLoader() == null);
1974 +
1975 +        Runnable r = () -> {};
1976 +        Callable<Boolean> c = () -> Boolean.TRUE;
1977 +
1978 +        class Recorder implements RejectedExecutionHandler {
1979 +            public volatile Runnable r = null;
1980 +            public volatile ThreadPoolExecutor p = null;
1981 +            public void reset() { r = null; p = null; }
1982 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1983 +                assertNull(this.r);
1984 +                assertNull(this.p);
1985 +                this.r = r;
1986 +                this.p = p;
1987 +            }
1988 +        }
1989 +
1990 +        // check custom handler is invoked exactly once per task
1991 +        Recorder recorder = new Recorder();
1992 +        setRejectedExecutionHandler(p, recorder);
1993 +        for (int i = 2; i--> 0; ) {
1994 +            recorder.reset();
1995 +            p.execute(r);
1996 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
1997 +                assertSame(r, recorder.r);
1998 +            assertSame(p, recorder.p);
1999 +
2000 +            recorder.reset();
2001 +            assertFalse(p.submit(r).isDone());
2002 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2003 +            assertSame(p, recorder.p);
2004 +
2005 +            recorder.reset();
2006 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2007 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2008 +            assertSame(p, recorder.p);
2009 +
2010 +            recorder.reset();
2011 +            assertFalse(p.submit(c).isDone());
2012 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2013 +            assertSame(p, recorder.p);
2014 +
2015 +            if (p instanceof ScheduledExecutorService) {
2016 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
2017 +                ScheduledFuture<?> future;
2018 +
2019 +                recorder.reset();
2020 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2021 +                assertFalse(future.isDone());
2022 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2023 +                assertSame(p, recorder.p);
2024 +
2025 +                recorder.reset();
2026 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2027 +                assertFalse(future.isDone());
2028 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2029 +                assertSame(p, recorder.p);
2030 +
2031 +                recorder.reset();
2032 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2033 +                assertFalse(future.isDone());
2034 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2035 +                assertSame(p, recorder.p);
2036 +
2037 +                recorder.reset();
2038 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2039 +                assertFalse(future.isDone());
2040 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2041 +                assertSame(p, recorder.p);
2042 +            }
2043 +        }
2044 +
2045 +        // Checking our custom handler above should be sufficient, but
2046 +        // we add some integration tests of standard handlers.
2047 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2048 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2049 +
2050 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2051 +        try {
2052 +            p.execute(setThread);
2053 +            shouldThrow();
2054 +        } catch (RejectedExecutionException success) {}
2055 +        assertNull(thread.get());
2056 +
2057 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2058 +        p.execute(setThread);
2059 +        assertNull(thread.get());
2060 +
2061 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2062 +        p.execute(setThread);
2063 +        if (p.isShutdown())
2064 +            assertNull(thread.get());
2065 +        else
2066 +            assertSame(Thread.currentThread(), thread.get());
2067 +
2068 +        setRejectedExecutionHandler(p, savedHandler);
2069 +
2070 +        // check that pool was not perturbed by handlers
2071 +        assertEquals(savedTaskCount, p.getTaskCount());
2072 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2073 +        assertEquals(savedQueueSize, p.getQueue().size());
2074 +    }
2075   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines