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.129 by jsr166, Fri Feb 27 22:10:29 2015 UTC vs.
Revision 1.192 by jsr166, Sun May 22 01:09:21 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 + /*
10 + * @test
11 + * @summary JSR-166 tck tests
12 + * @modules java.management
13 + * @build *
14 + * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
15 + */
16 +
17   import static java.util.concurrent.TimeUnit.MILLISECONDS;
18 + import static java.util.concurrent.TimeUnit.MINUTES;
19   import static java.util.concurrent.TimeUnit.NANOSECONDS;
20  
21   import java.io.ByteArrayInputStream;
# Line 15 | Line 24 | import java.io.ObjectInputStream;
24   import java.io.ObjectOutputStream;
25   import java.lang.management.ManagementFactory;
26   import java.lang.management.ThreadInfo;
27 + import java.lang.management.ThreadMXBean;
28 + import java.lang.reflect.Constructor;
29   import java.lang.reflect.Method;
30 + import java.lang.reflect.Modifier;
31 + import java.nio.file.Files;
32 + import java.nio.file.Paths;
33   import java.security.CodeSource;
34   import java.security.Permission;
35   import java.security.PermissionCollection;
# Line 35 | Line 49 | import java.util.concurrent.BlockingQueu
49   import java.util.concurrent.Callable;
50   import java.util.concurrent.CountDownLatch;
51   import java.util.concurrent.CyclicBarrier;
52 + import java.util.concurrent.ExecutionException;
53 + import java.util.concurrent.Executors;
54   import java.util.concurrent.ExecutorService;
55 + import java.util.concurrent.ForkJoinPool;
56   import java.util.concurrent.Future;
57   import java.util.concurrent.RecursiveAction;
58   import java.util.concurrent.RecursiveTask;
# Line 44 | Line 61 | import java.util.concurrent.Semaphore;
61   import java.util.concurrent.ThreadFactory;
62   import java.util.concurrent.ThreadPoolExecutor;
63   import java.util.concurrent.TimeoutException;
64 + import java.util.concurrent.atomic.AtomicBoolean;
65   import java.util.concurrent.atomic.AtomicReference;
66 + import java.util.regex.Matcher;
67   import java.util.regex.Pattern;
68  
69   import junit.framework.AssertionFailedError;
70   import junit.framework.Test;
71   import junit.framework.TestCase;
72 + import junit.framework.TestResult;
73   import junit.framework.TestSuite;
74  
75   /**
# Line 62 | Line 82 | import junit.framework.TestSuite;
82   *
83   * <ol>
84   *
85 < * <li> All assertions in code running in generated threads must use
85 > * <li>All assertions in code running in generated threads must use
86   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
87   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
88   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
89   * particularly recommended) for other code to use these forms too.
90   * Only the most typically used JUnit assertion methods are defined
91 < * this way, but enough to live with.</li>
91 > * this way, but enough to live with.
92   *
93 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
93 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
94   * to invoke {@code super.setUp} and {@code super.tearDown} within
95   * them. These methods are used to clear and check for thread
96 < * assertion failures.</li>
96 > * assertion failures.
97   *
98   * <li>All delays and timeouts must use one of the constants {@code
99   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 84 | Line 104 | import junit.framework.TestSuite;
104   * is always discriminable as larger than SHORT and smaller than
105   * MEDIUM.  And so on. These constants are set to conservative values,
106   * but even so, if there is ever any doubt, they can all be increased
107 < * in one spot to rerun tests on slower platforms.</li>
107 > * in one spot to rerun tests on slower platforms.
108   *
109 < * <li> All threads generated must be joined inside each test case
109 > * <li>All threads generated must be joined inside each test case
110   * method (or {@code fail} to do so) before returning from the
111   * method. The {@code joinPool} method can be used to do this when
112 < * using Executors.</li>
112 > * using Executors.
113   *
114   * </ol>
115   *
116   * <p><b>Other notes</b>
117   * <ul>
118   *
119 < * <li> Usually, there is one testcase method per JSR166 method
119 > * <li>Usually, there is one testcase method per JSR166 method
120   * covering "normal" operation, and then as many exception-testing
121   * methods as there are exceptions the method can throw. Sometimes
122   * there are multiple tests per JSR166 method when the different
123   * "normal" behaviors differ significantly. And sometimes testcases
124 < * cover multiple methods when they cannot be tested in
105 < * isolation.</li>
124 > * cover multiple methods when they cannot be tested in isolation.
125   *
126 < * <li> The documentation style for testcases is to provide as javadoc
126 > * <li>The documentation style for testcases is to provide as javadoc
127   * a simple sentence or two describing the property that the testcase
128   * method purports to test. The javadocs do not say anything about how
129 < * the property is tested. To find out, read the code.</li>
129 > * the property is tested. To find out, read the code.
130   *
131 < * <li> These tests are "conformance tests", and do not attempt to
131 > * <li>These tests are "conformance tests", and do not attempt to
132   * test throughput, latency, scalability or other performance factors
133   * (see the separate "jtreg" tests for a set intended to check these
134   * for the most central aspects of functionality.) So, most tests use
135   * the smallest sensible numbers of threads, collection sizes, etc
136 < * needed to check basic conformance.</li>
136 > * needed to check basic conformance.
137   *
138   * <li>The test classes currently do not declare inclusion in
139   * any particular package to simplify things for people integrating
140 < * them in TCK test suites.</li>
140 > * them in TCK test suites.
141   *
142 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
143 < * runs all JSR166 unit tests.</li>
142 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
143 > * runs all JSR166 unit tests.
144   *
145   * </ul>
146   */
# Line 160 | Line 179 | public class JSR166TestCase extends Test
179          Integer.getInteger("jsr166.runsPerTest", 1);
180  
181      /**
182 +     * The number of repetitions of the test suite (for finding leaks?).
183 +     */
184 +    private static final int suiteRuns =
185 +        Integer.getInteger("jsr166.suiteRuns", 1);
186 +
187 +    /**
188 +     * Returns the value of the system property, or NaN if not defined.
189 +     */
190 +    private static float systemPropertyValue(String name) {
191 +        String floatString = System.getProperty(name);
192 +        if (floatString == null)
193 +            return Float.NaN;
194 +        try {
195 +            return Float.parseFloat(floatString);
196 +        } catch (NumberFormatException ex) {
197 +            throw new IllegalArgumentException(
198 +                String.format("Bad float value in system property %s=%s",
199 +                              name, floatString));
200 +        }
201 +    }
202 +
203 +    /**
204 +     * The scaling factor to apply to standard delays used in tests.
205 +     * May be initialized from any of:
206 +     * - the "jsr166.delay.factor" system property
207 +     * - the "test.timeout.factor" system property (as used by jtreg)
208 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
209 +     * - hard-coded fuzz factor when using a known slowpoke VM
210 +     */
211 +    private static final float delayFactor = delayFactor();
212 +
213 +    private static float delayFactor() {
214 +        float x;
215 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
216 +            return x;
217 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
218 +            return x;
219 +        String prop = System.getProperty("java.vm.version");
220 +        if (prop != null && prop.matches(".*debug.*"))
221 +            return 4.0f; // How much slower is fastdebug than product?!
222 +        return 1.0f;
223 +    }
224 +
225 +    public JSR166TestCase() { super(); }
226 +    public JSR166TestCase(String name) { super(name); }
227 +
228 +    /**
229       * A filter for tests to run, matching strings of the form
230       * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
231       * Usefully combined with jsr166.runsPerTest.
# Line 171 | Line 237 | public class JSR166TestCase extends Test
237          return (regex == null) ? null : Pattern.compile(regex);
238      }
239  
240 <    protected void runTest() throws Throwable {
240 >    // Instrumentation to debug very rare, but very annoying hung test runs.
241 >    static volatile TestCase currentTestCase;
242 >    // static volatile int currentRun = 0;
243 >    static {
244 >        Runnable checkForWedgedTest = new Runnable() { public void run() {
245 >            // Avoid spurious reports with enormous runsPerTest.
246 >            // A single test case run should never take more than 1 second.
247 >            // But let's cap it at the high end too ...
248 >            final int timeoutMinutes =
249 >                Math.min(15, Math.max(runsPerTest / 60, 1));
250 >            for (TestCase lastTestCase = currentTestCase;;) {
251 >                try { MINUTES.sleep(timeoutMinutes); }
252 >                catch (InterruptedException unexpected) { break; }
253 >                if (lastTestCase == currentTestCase) {
254 >                    System.err.printf(
255 >                        "Looks like we're stuck running test: %s%n",
256 >                        lastTestCase);
257 > //                     System.err.printf(
258 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
259 > //                         lastTestCase, currentRun, runsPerTest);
260 > //                     System.err.println("availableProcessors=" +
261 > //                         Runtime.getRuntime().availableProcessors());
262 > //                     System.err.printf("cpu model = %s%n", cpuModel());
263 >                    dumpTestThreads();
264 >                    // one stack dump is probably enough; more would be spam
265 >                    break;
266 >                }
267 >                lastTestCase = currentTestCase;
268 >            }}};
269 >        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
270 >        thread.setDaemon(true);
271 >        thread.start();
272 >    }
273 >
274 > //     public static String cpuModel() {
275 > //         try {
276 > //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
277 > //                 .matcher(new String(
278 > //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
279 > //             matcher.find();
280 > //             return matcher.group(1);
281 > //         } catch (Exception ex) { return null; }
282 > //     }
283 >
284 >    public void runBare() throws Throwable {
285 >        currentTestCase = this;
286          if (methodFilter == null
287 <            || methodFilter.matcher(toString()).find()) {
288 <            for (int i = 0; i < runsPerTest; i++) {
289 <                if (profileTests)
290 <                    runTestProfiled();
291 <                else
292 <                    super.runTest();
293 <            }
287 >            || methodFilter.matcher(toString()).find())
288 >            super.runBare();
289 >    }
290 >
291 >    protected void runTest() throws Throwable {
292 >        for (int i = 0; i < runsPerTest; i++) {
293 >            // currentRun = i;
294 >            if (profileTests)
295 >                runTestProfiled();
296 >            else
297 >                super.runTest();
298          }
299      }
300  
301      protected void runTestProfiled() throws Throwable {
302 <        // Warmup run, notably to trigger all needed classloading.
303 <        super.runTest();
189 <        long t0 = System.nanoTime();
190 <        try {
302 >        for (int i = 0; i < 2; i++) {
303 >            long startTime = System.nanoTime();
304              super.runTest();
305 <        } finally {
306 <            long elapsedMillis = millisElapsedSince(t0);
307 <            if (elapsedMillis >= profileThreshold)
305 >            long elapsedMillis = millisElapsedSince(startTime);
306 >            if (elapsedMillis < profileThreshold)
307 >                break;
308 >            // Never report first run of any test; treat it as a
309 >            // warmup run, notably to trigger all needed classloading,
310 >            if (i > 0)
311                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
312          }
313      }
314  
315      /**
316       * Runs all JSR166 unit tests using junit.textui.TestRunner.
201     * Optional command line arg provides the number of iterations to
202     * repeat running the tests.
317       */
318      public static void main(String[] args) {
319 +        main(suite(), args);
320 +    }
321 +
322 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
323 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
324 +        long runTime;
325 +        public void startTest(Test test) {}
326 +        protected void printHeader(long runTime) {
327 +            this.runTime = runTime; // defer printing for later
328 +        }
329 +        protected void printFooter(TestResult result) {
330 +            if (result.wasSuccessful()) {
331 +                getWriter().println("OK (" + result.runCount() + " tests)"
332 +                    + "  Time: " + elapsedTimeAsString(runTime));
333 +            } else {
334 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
335 +                super.printFooter(result);
336 +            }
337 +        }
338 +    }
339 +
340 +    /**
341 +     * Returns a TestRunner that doesn't bother with unnecessary
342 +     * fluff, like printing a "." for each test case.
343 +     */
344 +    static junit.textui.TestRunner newPithyTestRunner() {
345 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
346 +        runner.setPrinter(new PithyResultPrinter(System.out));
347 +        return runner;
348 +    }
349 +
350 +    /**
351 +     * Runs all unit tests in the given test suite.
352 +     * Actual behavior influenced by jsr166.* system properties.
353 +     */
354 +    static void main(Test suite, String[] args) {
355          if (useSecurityManager) {
356              System.err.println("Setting a permissive security manager");
357              Policy.setPolicy(permissivePolicy());
358              System.setSecurityManager(new SecurityManager());
359          }
360 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
361 <
362 <        Test s = suite();
363 <        for (int i = 0; i < iters; ++i) {
214 <            junit.textui.TestRunner.run(s);
360 >        for (int i = 0; i < suiteRuns; i++) {
361 >            TestResult result = newPithyTestRunner().doRun(suite);
362 >            if (!result.wasSuccessful())
363 >                System.exit(1);
364              System.gc();
365              System.runFinalization();
366          }
218        System.exit(0);
367      }
368  
369      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 266 | Line 414 | public class JSR166TestCase extends Test
414      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
415      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
416      public static boolean atLeastJava9() {
417 <        // As of 2014-05, java9 still uses 52.0 class file version
418 <        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
417 >        return JAVA_CLASS_VERSION >= 53.0
418 >            // As of 2015-09, java9 still uses 52.0 class file version
419 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
420 >    }
421 >    public static boolean atLeastJava10() {
422 >        return JAVA_CLASS_VERSION >= 54.0
423 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
424      }
425  
426      /**
# Line 356 | Line 509 | public class JSR166TestCase extends Test
509                  "LongAdderTest",
510                  "SplittableRandomTest",
511                  "StampedLockTest",
512 +                "SubmissionPublisherTest",
513                  "ThreadLocalRandom8Test",
514 +                "TimeUnit8Test",
515              };
516              addNamedTestClasses(suite, java8TestClassNames);
517          }
# Line 364 | Line 519 | public class JSR166TestCase extends Test
519          // Java9+ test classes
520          if (atLeastJava9()) {
521              String[] java9TestClassNames = {
522 <                "ThreadPoolExecutor9Test",
522 >                "ExecutorCompletionService9Test",
523              };
524              addNamedTestClasses(suite, java9TestClassNames);
525          }
# Line 372 | Line 527 | public class JSR166TestCase extends Test
527          return suite;
528      }
529  
530 +    /** Returns list of junit-style test method names in given class. */
531 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
532 +        Method[] methods = testClass.getDeclaredMethods();
533 +        ArrayList<String> names = new ArrayList<String>(methods.length);
534 +        for (Method method : methods) {
535 +            if (method.getName().startsWith("test")
536 +                && Modifier.isPublic(method.getModifiers())
537 +                // method.getParameterCount() requires jdk8+
538 +                && method.getParameterTypes().length == 0) {
539 +                names.add(method.getName());
540 +            }
541 +        }
542 +        return names;
543 +    }
544 +
545 +    /**
546 +     * Returns junit-style testSuite for the given test class, but
547 +     * parameterized by passing extra data to each test.
548 +     */
549 +    public static <ExtraData> Test parameterizedTestSuite
550 +        (Class<? extends JSR166TestCase> testClass,
551 +         Class<ExtraData> dataClass,
552 +         ExtraData data) {
553 +        try {
554 +            TestSuite suite = new TestSuite();
555 +            Constructor c =
556 +                testClass.getDeclaredConstructor(dataClass, String.class);
557 +            for (String methodName : testMethodNames(testClass))
558 +                suite.addTest((Test) c.newInstance(data, methodName));
559 +            return suite;
560 +        } catch (Exception e) {
561 +            throw new Error(e);
562 +        }
563 +    }
564 +
565 +    /**
566 +     * Returns junit-style testSuite for the jdk8 extension of the
567 +     * given test class, but parameterized by passing extra data to
568 +     * each test.  Uses reflection to allow compilation in jdk7.
569 +     */
570 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
571 +        (Class<? extends JSR166TestCase> testClass,
572 +         Class<ExtraData> dataClass,
573 +         ExtraData data) {
574 +        if (atLeastJava8()) {
575 +            String name = testClass.getName();
576 +            String name8 = name.replaceAll("Test$", "8Test");
577 +            if (name.equals(name8)) throw new Error(name);
578 +            try {
579 +                return (Test)
580 +                    Class.forName(name8)
581 +                    .getMethod("testSuite", new Class[] { dataClass })
582 +                    .invoke(null, data);
583 +            } catch (Exception e) {
584 +                throw new Error(e);
585 +            }
586 +        } else {
587 +            return new TestSuite();
588 +        }
589 +    }
590 +
591      // Delays for timing-dependent tests, in milliseconds.
592  
593      public static long SHORT_DELAY_MS;
# Line 380 | Line 596 | public class JSR166TestCase extends Test
596      public static long LONG_DELAY_MS;
597  
598      /**
599 <     * Returns the shortest timed delay. This could
600 <     * be reimplemented to use for example a Property.
599 >     * Returns the shortest timed delay. This can be scaled up for
600 >     * slow machines using the jsr166.delay.factor system property,
601 >     * or via jtreg's -timeoutFactor: flag.
602 >     * http://openjdk.java.net/jtreg/command-help.html
603       */
604      protected long getShortDelay() {
605 <        return 50;
605 >        return (long) (50 * delayFactor);
606      }
607  
608      /**
# Line 406 | Line 624 | public class JSR166TestCase extends Test
624      }
625  
626      /**
627 <     * Returns a new Date instance representing a time delayMillis
628 <     * milliseconds in the future.
627 >     * Returns a new Date instance representing a time at least
628 >     * delayMillis milliseconds in the future.
629       */
630      Date delayedDate(long delayMillis) {
631 <        return new Date(System.currentTimeMillis() + delayMillis);
631 >        // Add 1 because currentTimeMillis is known to round into the past.
632 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
633      }
634  
635      /**
# Line 426 | Line 645 | public class JSR166TestCase extends Test
645       * the same test have no effect.
646       */
647      public void threadRecordFailure(Throwable t) {
648 +        System.err.println(t);
649 +        dumpTestThreads();
650          threadFailure.compareAndSet(null, t);
651      }
652  
# Line 433 | Line 654 | public class JSR166TestCase extends Test
654          setDelays();
655      }
656  
657 +    void tearDownFail(String format, Object... args) {
658 +        String msg = toString() + ": " + String.format(format, args);
659 +        System.err.println(msg);
660 +        dumpTestThreads();
661 +        throw new AssertionFailedError(msg);
662 +    }
663 +
664      /**
665       * Extra checks that get done for all test cases.
666       *
# Line 460 | Line 688 | public class JSR166TestCase extends Test
688          }
689  
690          if (Thread.interrupted())
691 <            throw new AssertionFailedError("interrupt status set in main thread");
691 >            tearDownFail("interrupt status set in main thread");
692  
693          checkForkJoinPoolThreadLeaks();
694      }
695  
696      /**
697 <     * Finds missing try { ... } finally { joinPool(e); }
697 >     * Finds missing PoolCleaners
698       */
699      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
700 <        Thread[] survivors = new Thread[5];
700 >        Thread[] survivors = new Thread[7];
701          int count = Thread.enumerate(survivors);
702          for (int i = 0; i < count; i++) {
703              Thread thread = survivors[i];
# Line 477 | Line 705 | public class JSR166TestCase extends Test
705              if (name.startsWith("ForkJoinPool-")) {
706                  // give thread some time to terminate
707                  thread.join(LONG_DELAY_MS);
708 <                if (!thread.isAlive()) continue;
709 <                thread.stop();
710 <                throw new AssertionFailedError
483 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
484 <                                   toString(), name));
708 >                if (thread.isAlive())
709 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
710 >                                 thread);
711              }
712          }
713 +
714 +        if (!ForkJoinPool.commonPool()
715 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
716 +            tearDownFail("ForkJoin common pool thread stuck");
717      }
718  
719      /**
# Line 496 | Line 726 | public class JSR166TestCase extends Test
726              fail(reason);
727          } catch (AssertionFailedError t) {
728              threadRecordFailure(t);
729 <            fail(reason);
729 >            throw t;
730          }
731      }
732  
# Line 623 | Line 853 | public class JSR166TestCase extends Test
853      /**
854       * Delays, via Thread.sleep, for the given millisecond delay, but
855       * if the sleep is shorter than specified, may re-sleep or yield
856 <     * until time elapses.
856 >     * until time elapses.  Ensures that the given time, as measured
857 >     * by System.nanoTime(), has elapsed.
858       */
859      static void delay(long millis) throws InterruptedException {
860 <        long startTime = System.nanoTime();
861 <        long ns = millis * 1000 * 1000;
862 <        for (;;) {
860 >        long nanos = millis * (1000 * 1000);
861 >        final long wakeupTime = System.nanoTime() + nanos;
862 >        do {
863              if (millis > 0L)
864                  Thread.sleep(millis);
865              else // too short to sleep
866                  Thread.yield();
867 <            long d = ns - (System.nanoTime() - startTime);
868 <            if (d > 0L)
869 <                millis = d / (1000 * 1000);
870 <            else
871 <                break;
867 >            nanos = wakeupTime - System.nanoTime();
868 >            millis = nanos / (1000 * 1000);
869 >        } while (nanos >= 0L);
870 >    }
871 >
872 >    /**
873 >     * Allows use of try-with-resources with per-test thread pools.
874 >     */
875 >    class PoolCleaner implements AutoCloseable {
876 >        private final ExecutorService pool;
877 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
878 >        public void close() { joinPool(pool); }
879 >    }
880 >
881 >    /**
882 >     * An extension of PoolCleaner that has an action to release the pool.
883 >     */
884 >    class PoolCleanerWithReleaser extends PoolCleaner {
885 >        private final Runnable releaser;
886 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
887 >            super(pool);
888 >            this.releaser = releaser;
889 >        }
890 >        public void close() {
891 >            try {
892 >                releaser.run();
893 >            } finally {
894 >                super.close();
895 >            }
896          }
897      }
898  
899 +    PoolCleaner cleaner(ExecutorService pool) {
900 +        return new PoolCleaner(pool);
901 +    }
902 +
903 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
904 +        return new PoolCleanerWithReleaser(pool, releaser);
905 +    }
906 +
907 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
908 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
909 +    }
910 +
911 +    Runnable releaser(final CountDownLatch latch) {
912 +        return new Runnable() { public void run() {
913 +            do { latch.countDown(); }
914 +            while (latch.getCount() > 0);
915 +        }};
916 +    }
917 +
918 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
919 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
920 +    }
921 +
922 +    Runnable releaser(final AtomicBoolean flag) {
923 +        return new Runnable() { public void run() { flag.set(true); }};
924 +    }
925 +
926      /**
927       * Waits out termination of a thread pool or fails doing so.
928       */
929 <    void joinPool(ExecutorService exec) {
929 >    void joinPool(ExecutorService pool) {
930          try {
931 <            exec.shutdown();
932 <            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
933 <                fail("ExecutorService " + exec +
934 <                     " did not terminate in a timely manner");
931 >            pool.shutdown();
932 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
933 >                try {
934 >                    threadFail("ExecutorService " + pool +
935 >                               " did not terminate in a timely manner");
936 >                } finally {
937 >                    // last resort, for the benefit of subsequent tests
938 >                    pool.shutdownNow();
939 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
940 >                }
941 >            }
942          } catch (SecurityException ok) {
943              // Allowed in case test doesn't have privs
944          } catch (InterruptedException fail) {
945 <            fail("Unexpected InterruptedException");
945 >            threadFail("Unexpected InterruptedException");
946 >        }
947 >    }
948 >
949 >    /** Like Runnable, but with the freedom to throw anything */
950 >    interface Action { public void run() throws Throwable; }
951 >
952 >    /**
953 >     * Runs all the given actions in parallel, failing if any fail.
954 >     * Useful for running multiple variants of tests that are
955 >     * necessarily individually slow because they must block.
956 >     */
957 >    void testInParallel(Action ... actions) {
958 >        ExecutorService pool = Executors.newCachedThreadPool();
959 >        try (PoolCleaner cleaner = cleaner(pool)) {
960 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
961 >            for (final Action action : actions)
962 >                futures.add(pool.submit(new CheckedRunnable() {
963 >                    public void realRun() throws Throwable { action.run();}}));
964 >            for (Future<?> future : futures)
965 >                try {
966 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
967 >                } catch (ExecutionException ex) {
968 >                    threadUnexpectedException(ex.getCause());
969 >                } catch (Exception ex) {
970 >                    threadUnexpectedException(ex);
971 >                }
972          }
973      }
974  
975      /**
976 <     * A debugging tool to print all stack traces, as jstack does.
976 >     * A debugging tool to print stack traces of most threads, as jstack does.
977 >     * Uninteresting threads are filtered out.
978       */
979 <    static void printAllStackTraces() {
980 <        for (ThreadInfo info :
981 <                 ManagementFactory.getThreadMXBean()
982 <                 .dumpAllThreads(true, true))
979 >    static void dumpTestThreads() {
980 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
981 >        System.err.println("------ stacktrace dump start ------");
982 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
983 >            String name = info.getThreadName();
984 >            if ("Signal Dispatcher".equals(name))
985 >                continue;
986 >            if ("Reference Handler".equals(name)
987 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
988 >                continue;
989 >            if ("Finalizer".equals(name)
990 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
991 >                continue;
992 >            if ("checkForWedgedTest".equals(name))
993 >                continue;
994              System.err.print(info);
995 +        }
996 +        System.err.println("------ stacktrace dump end ------");
997      }
998  
999      /**
# Line 684 | Line 1013 | public class JSR166TestCase extends Test
1013              delay(millis);
1014              assertTrue(thread.isAlive());
1015          } catch (InterruptedException fail) {
1016 <            fail("Unexpected InterruptedException");
1016 >            threadFail("Unexpected InterruptedException");
1017          }
1018      }
1019  
# Line 706 | Line 1035 | public class JSR166TestCase extends Test
1035              for (Thread thread : threads)
1036                  assertTrue(thread.isAlive());
1037          } catch (InterruptedException fail) {
1038 <            fail("Unexpected InterruptedException");
1038 >            threadFail("Unexpected InterruptedException");
1039          }
1040      }
1041  
# Line 984 | Line 1313 | public class JSR166TestCase extends Test
1313          } finally {
1314              if (t.getState() != Thread.State.TERMINATED) {
1315                  t.interrupt();
1316 <                fail("Test timed out");
1316 >                threadFail("timed out waiting for thread to terminate");
1317              }
1318          }
1319      }
# Line 1109 | Line 1438 | public class JSR166TestCase extends Test
1438      public static final String TEST_STRING = "a test string";
1439  
1440      public static class StringTask implements Callable<String> {
1441 <        public String call() { return TEST_STRING; }
1441 >        final String value;
1442 >        public StringTask() { this(TEST_STRING); }
1443 >        public StringTask(String value) { this.value = value; }
1444 >        public String call() { return value; }
1445      }
1446  
1447      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1122 | Line 1454 | public class JSR166TestCase extends Test
1454              }};
1455      }
1456  
1457 <    public Runnable awaiter(final CountDownLatch latch) {
1457 >    public Runnable countDowner(final CountDownLatch latch) {
1458          return new CheckedRunnable() {
1459              public void realRun() throws InterruptedException {
1460 <                await(latch);
1460 >                latch.countDown();
1461              }};
1462      }
1463  
1464 <    public void await(CountDownLatch latch) {
1464 >    class LatchAwaiter extends CheckedRunnable {
1465 >        static final int NEW = 0;
1466 >        static final int RUNNING = 1;
1467 >        static final int DONE = 2;
1468 >        final CountDownLatch latch;
1469 >        int state = NEW;
1470 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1471 >        public void realRun() throws InterruptedException {
1472 >            state = 1;
1473 >            await(latch);
1474 >            state = 2;
1475 >        }
1476 >    }
1477 >
1478 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1479 >        return new LatchAwaiter(latch);
1480 >    }
1481 >
1482 >    public void await(CountDownLatch latch, long timeoutMillis) {
1483          try {
1484 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1484 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1485 >                fail("timed out waiting for CountDownLatch for "
1486 >                     + (timeoutMillis/1000) + " sec");
1487          } catch (Throwable fail) {
1488              threadUnexpectedException(fail);
1489          }
1490      }
1491  
1492 +    public void await(CountDownLatch latch) {
1493 +        await(latch, LONG_DELAY_MS);
1494 +    }
1495 +
1496      public void await(Semaphore semaphore) {
1497          try {
1498 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1498 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1499 >                fail("timed out waiting for Semaphore for "
1500 >                     + (LONG_DELAY_MS/1000) + " sec");
1501          } catch (Throwable fail) {
1502              threadUnexpectedException(fail);
1503          }
# Line 1475 | Line 1833 | public class JSR166TestCase extends Test
1833          } catch (NoSuchElementException success) {}
1834          assertFalse(it.hasNext());
1835      }
1836 +
1837 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1838 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1839 +    }
1840 +
1841 +    public Runnable runnableThrowing(final RuntimeException ex) {
1842 +        return new Runnable() { public void run() { throw ex; }};
1843 +    }
1844   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines