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.121 by jsr166, Wed Jul 9 16:51:40 2014 UTC vs.
Revision 1.214 by jsr166, Fri Dec 9 07:26:04 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > /*
10 > * @test
11 > * @summary JSR-166 tck tests (conformance testing mode)
12 > * @build *
13 > * @modules java.management
14 > * @run junit/othervm/timeout=1000 JSR166TestCase
15 > */
16 >
17 > /*
18 > * @test
19 > * @summary JSR-166 tck tests (whitebox tests allowed)
20 > * @build *
21 > * @modules java.base/java.util.concurrent:open
22 > *          java.management
23 > * @run junit/othervm/timeout=1000
24 > *      -Djsr166.testImplementationDetails=true
25 > *      JSR166TestCase
26 > * @run junit/othervm/timeout=1000
27 > *      -Djsr166.testImplementationDetails=true
28 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
29 > *      JSR166TestCase
30 > * @run junit/othervm/timeout=1000
31 > *      -Djsr166.testImplementationDetails=true
32 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
33 > *      -Djava.util.secureRandomSeed=true
34 > *      JSR166TestCase
35 > */
36 >
37 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
38 > import static java.util.concurrent.TimeUnit.MINUTES;
39 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
40 >
41   import java.io.ByteArrayInputStream;
42   import java.io.ByteArrayOutputStream;
43   import java.io.ObjectInputStream;
44   import java.io.ObjectOutputStream;
45   import java.lang.management.ManagementFactory;
46   import java.lang.management.ThreadInfo;
47 + import java.lang.management.ThreadMXBean;
48 + import java.lang.reflect.Constructor;
49   import java.lang.reflect.Method;
50 + import java.lang.reflect.Modifier;
51 + import java.nio.file.Files;
52 + import java.nio.file.Paths;
53 + import java.security.CodeSource;
54 + import java.security.Permission;
55 + import java.security.PermissionCollection;
56 + import java.security.Permissions;
57 + import java.security.Policy;
58 + import java.security.ProtectionDomain;
59 + import java.security.SecurityPermission;
60   import java.util.ArrayList;
61   import java.util.Arrays;
62 + import java.util.Collection;
63 + import java.util.Collections;
64   import java.util.Date;
65   import java.util.Enumeration;
66 + import java.util.Iterator;
67   import java.util.List;
68   import java.util.NoSuchElementException;
69   import java.util.PropertyPermission;
70 < import java.util.concurrent.*;
70 > import java.util.concurrent.BlockingQueue;
71 > import java.util.concurrent.Callable;
72 > import java.util.concurrent.CountDownLatch;
73 > import java.util.concurrent.CyclicBarrier;
74 > import java.util.concurrent.ExecutionException;
75 > import java.util.concurrent.Executors;
76 > import java.util.concurrent.ExecutorService;
77 > import java.util.concurrent.ForkJoinPool;
78 > import java.util.concurrent.Future;
79 > import java.util.concurrent.RecursiveAction;
80 > import java.util.concurrent.RecursiveTask;
81 > import java.util.concurrent.RejectedExecutionHandler;
82 > import java.util.concurrent.Semaphore;
83 > import java.util.concurrent.SynchronousQueue;
84 > import java.util.concurrent.ThreadFactory;
85 > import java.util.concurrent.ThreadLocalRandom;
86 > import java.util.concurrent.ThreadPoolExecutor;
87 > import java.util.concurrent.TimeoutException;
88   import java.util.concurrent.atomic.AtomicBoolean;
89   import java.util.concurrent.atomic.AtomicReference;
90 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
90 > import java.util.regex.Matcher;
91   import java.util.regex.Pattern;
92 < import java.security.CodeSource;
93 < import java.security.Permission;
94 < import java.security.PermissionCollection;
95 < import java.security.Permissions;
96 < import java.security.Policy;
97 < import java.security.ProtectionDomain;
36 < import java.security.SecurityPermission;
92 >
93 > import junit.framework.AssertionFailedError;
94 > import junit.framework.Test;
95 > import junit.framework.TestCase;
96 > import junit.framework.TestResult;
97 > import junit.framework.TestSuite;
98  
99   /**
100   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 45 | Line 106 | import java.security.SecurityPermission;
106   *
107   * <ol>
108   *
109 < * <li> All assertions in code running in generated threads must use
109 > * <li>All assertions in code running in generated threads must use
110   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
111   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
112   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
113   * particularly recommended) for other code to use these forms too.
114   * Only the most typically used JUnit assertion methods are defined
115 < * this way, but enough to live with.</li>
115 > * this way, but enough to live with.
116   *
117 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
117 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
118   * to invoke {@code super.setUp} and {@code super.tearDown} within
119   * them. These methods are used to clear and check for thread
120 < * assertion failures.</li>
120 > * assertion failures.
121   *
122   * <li>All delays and timeouts must use one of the constants {@code
123   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 67 | Line 128 | import java.security.SecurityPermission;
128   * is always discriminable as larger than SHORT and smaller than
129   * MEDIUM.  And so on. These constants are set to conservative values,
130   * but even so, if there is ever any doubt, they can all be increased
131 < * in one spot to rerun tests on slower platforms.</li>
131 > * in one spot to rerun tests on slower platforms.
132   *
133 < * <li> All threads generated must be joined inside each test case
133 > * <li>All threads generated must be joined inside each test case
134   * method (or {@code fail} to do so) before returning from the
135   * method. The {@code joinPool} method can be used to do this when
136 < * using Executors.</li>
136 > * using Executors.
137   *
138   * </ol>
139   *
140   * <p><b>Other notes</b>
141   * <ul>
142   *
143 < * <li> Usually, there is one testcase method per JSR166 method
143 > * <li>Usually, there is one testcase method per JSR166 method
144   * covering "normal" operation, and then as many exception-testing
145   * methods as there are exceptions the method can throw. Sometimes
146   * there are multiple tests per JSR166 method when the different
147   * "normal" behaviors differ significantly. And sometimes testcases
148 < * cover multiple methods when they cannot be tested in
88 < * isolation.</li>
148 > * cover multiple methods when they cannot be tested in isolation.
149   *
150 < * <li> The documentation style for testcases is to provide as javadoc
150 > * <li>The documentation style for testcases is to provide as javadoc
151   * a simple sentence or two describing the property that the testcase
152   * method purports to test. The javadocs do not say anything about how
153 < * the property is tested. To find out, read the code.</li>
153 > * the property is tested. To find out, read the code.
154   *
155 < * <li> These tests are "conformance tests", and do not attempt to
155 > * <li>These tests are "conformance tests", and do not attempt to
156   * test throughput, latency, scalability or other performance factors
157   * (see the separate "jtreg" tests for a set intended to check these
158   * for the most central aspects of functionality.) So, most tests use
159   * the smallest sensible numbers of threads, collection sizes, etc
160 < * needed to check basic conformance.</li>
160 > * needed to check basic conformance.
161   *
162   * <li>The test classes currently do not declare inclusion in
163   * any particular package to simplify things for people integrating
164 < * them in TCK test suites.</li>
164 > * them in TCK test suites.
165   *
166 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
167 < * runs all JSR166 unit tests.</li>
166 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
167 > * runs all JSR166 unit tests.
168   *
169   * </ul>
170   */
# Line 143 | Line 203 | public class JSR166TestCase extends Test
203          Integer.getInteger("jsr166.runsPerTest", 1);
204  
205      /**
206 +     * The number of repetitions of the test suite (for finding leaks?).
207 +     */
208 +    private static final int suiteRuns =
209 +        Integer.getInteger("jsr166.suiteRuns", 1);
210 +
211 +    /**
212 +     * Returns the value of the system property, or NaN if not defined.
213 +     */
214 +    private static float systemPropertyValue(String name) {
215 +        String floatString = System.getProperty(name);
216 +        if (floatString == null)
217 +            return Float.NaN;
218 +        try {
219 +            return Float.parseFloat(floatString);
220 +        } catch (NumberFormatException ex) {
221 +            throw new IllegalArgumentException(
222 +                String.format("Bad float value in system property %s=%s",
223 +                              name, floatString));
224 +        }
225 +    }
226 +
227 +    /**
228 +     * The scaling factor to apply to standard delays used in tests.
229 +     * May be initialized from any of:
230 +     * - the "jsr166.delay.factor" system property
231 +     * - the "test.timeout.factor" system property (as used by jtreg)
232 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
233 +     * - hard-coded fuzz factor when using a known slowpoke VM
234 +     */
235 +    private static final float delayFactor = delayFactor();
236 +
237 +    private static float delayFactor() {
238 +        float x;
239 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
240 +            return x;
241 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
242 +            return x;
243 +        String prop = System.getProperty("java.vm.version");
244 +        if (prop != null && prop.matches(".*debug.*"))
245 +            return 4.0f; // How much slower is fastdebug than product?!
246 +        return 1.0f;
247 +    }
248 +
249 +    public JSR166TestCase() { super(); }
250 +    public JSR166TestCase(String name) { super(name); }
251 +
252 +    /**
253       * A filter for tests to run, matching strings of the form
254       * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
255       * Usefully combined with jsr166.runsPerTest.
# Line 154 | Line 261 | public class JSR166TestCase extends Test
261          return (regex == null) ? null : Pattern.compile(regex);
262      }
263  
264 <    protected void runTest() throws Throwable {
264 >    // Instrumentation to debug very rare, but very annoying hung test runs.
265 >    static volatile TestCase currentTestCase;
266 >    // static volatile int currentRun = 0;
267 >    static {
268 >        Runnable checkForWedgedTest = new Runnable() { public void run() {
269 >            // Avoid spurious reports with enormous runsPerTest.
270 >            // A single test case run should never take more than 1 second.
271 >            // But let's cap it at the high end too ...
272 >            final int timeoutMinutes =
273 >                Math.min(15, Math.max(runsPerTest / 60, 1));
274 >            for (TestCase lastTestCase = currentTestCase;;) {
275 >                try { MINUTES.sleep(timeoutMinutes); }
276 >                catch (InterruptedException unexpected) { break; }
277 >                if (lastTestCase == currentTestCase) {
278 >                    System.err.printf(
279 >                        "Looks like we're stuck running test: %s%n",
280 >                        lastTestCase);
281 > //                     System.err.printf(
282 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
283 > //                         lastTestCase, currentRun, runsPerTest);
284 > //                     System.err.println("availableProcessors=" +
285 > //                         Runtime.getRuntime().availableProcessors());
286 > //                     System.err.printf("cpu model = %s%n", cpuModel());
287 >                    dumpTestThreads();
288 >                    // one stack dump is probably enough; more would be spam
289 >                    break;
290 >                }
291 >                lastTestCase = currentTestCase;
292 >            }}};
293 >        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
294 >        thread.setDaemon(true);
295 >        thread.start();
296 >    }
297 >
298 > //     public static String cpuModel() {
299 > //         try {
300 > //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
301 > //                 .matcher(new String(
302 > //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
303 > //             matcher.find();
304 > //             return matcher.group(1);
305 > //         } catch (Exception ex) { return null; }
306 > //     }
307 >
308 >    public void runBare() throws Throwable {
309 >        currentTestCase = this;
310          if (methodFilter == null
311 <            || methodFilter.matcher(toString()).find()) {
312 <            for (int i = 0; i < runsPerTest; i++) {
313 <                if (profileTests)
314 <                    runTestProfiled();
315 <                else
316 <                    super.runTest();
317 <            }
311 >            || methodFilter.matcher(toString()).find())
312 >            super.runBare();
313 >    }
314 >
315 >    protected void runTest() throws Throwable {
316 >        for (int i = 0; i < runsPerTest; i++) {
317 >            // currentRun = i;
318 >            if (profileTests)
319 >                runTestProfiled();
320 >            else
321 >                super.runTest();
322          }
323      }
324  
325      protected void runTestProfiled() throws Throwable {
326 <        // Warmup run, notably to trigger all needed classloading.
327 <        super.runTest();
172 <        long t0 = System.nanoTime();
173 <        try {
326 >        for (int i = 0; i < 2; i++) {
327 >            long startTime = System.nanoTime();
328              super.runTest();
329 <        } finally {
330 <            long elapsedMillis = millisElapsedSince(t0);
331 <            if (elapsedMillis >= profileThreshold)
329 >            long elapsedMillis = millisElapsedSince(startTime);
330 >            if (elapsedMillis < profileThreshold)
331 >                break;
332 >            // Never report first run of any test; treat it as a
333 >            // warmup run, notably to trigger all needed classloading,
334 >            if (i > 0)
335                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
336          }
337      }
338  
339      /**
340       * Runs all JSR166 unit tests using junit.textui.TestRunner.
184     * Optional command line arg provides the number of iterations to
185     * repeat running the tests.
341       */
342      public static void main(String[] args) {
343 +        main(suite(), args);
344 +    }
345 +
346 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
347 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
348 +        long runTime;
349 +        public void startTest(Test test) {}
350 +        protected void printHeader(long runTime) {
351 +            this.runTime = runTime; // defer printing for later
352 +        }
353 +        protected void printFooter(TestResult result) {
354 +            if (result.wasSuccessful()) {
355 +                getWriter().println("OK (" + result.runCount() + " tests)"
356 +                    + "  Time: " + elapsedTimeAsString(runTime));
357 +            } else {
358 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
359 +                super.printFooter(result);
360 +            }
361 +        }
362 +    }
363 +
364 +    /**
365 +     * Returns a TestRunner that doesn't bother with unnecessary
366 +     * fluff, like printing a "." for each test case.
367 +     */
368 +    static junit.textui.TestRunner newPithyTestRunner() {
369 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
370 +        runner.setPrinter(new PithyResultPrinter(System.out));
371 +        return runner;
372 +    }
373 +
374 +    /**
375 +     * Runs all unit tests in the given test suite.
376 +     * Actual behavior influenced by jsr166.* system properties.
377 +     */
378 +    static void main(Test suite, String[] args) {
379          if (useSecurityManager) {
380              System.err.println("Setting a permissive security manager");
381              Policy.setPolicy(permissivePolicy());
382              System.setSecurityManager(new SecurityManager());
383          }
384 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
385 <
386 <        Test s = suite();
387 <        for (int i = 0; i < iters; ++i) {
197 <            junit.textui.TestRunner.run(s);
384 >        for (int i = 0; i < suiteRuns; i++) {
385 >            TestResult result = newPithyTestRunner().doRun(suite);
386 >            if (!result.wasSuccessful())
387 >                System.exit(1);
388              System.gc();
389              System.runFinalization();
390          }
201        System.exit(0);
391      }
392  
393      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 249 | Line 438 | public class JSR166TestCase extends Test
438      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
439      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
440      public static boolean atLeastJava9() {
441 <        // As of 2014-05, java9 still uses 52.0 class file version
442 <        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
441 >        return JAVA_CLASS_VERSION >= 53.0
442 >            // As of 2015-09, java9 still uses 52.0 class file version
443 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
444 >    }
445 >    public static boolean atLeastJava10() {
446 >        return JAVA_CLASS_VERSION >= 54.0
447 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
448      }
449  
450      /**
# Line 272 | Line 466 | public class JSR166TestCase extends Test
466              AbstractQueuedLongSynchronizerTest.suite(),
467              ArrayBlockingQueueTest.suite(),
468              ArrayDequeTest.suite(),
469 +            ArrayListTest.suite(),
470              AtomicBooleanTest.suite(),
471              AtomicIntegerArrayTest.suite(),
472              AtomicIntegerFieldUpdaterTest.suite(),
# Line 294 | Line 489 | public class JSR166TestCase extends Test
489              CopyOnWriteArrayListTest.suite(),
490              CopyOnWriteArraySetTest.suite(),
491              CountDownLatchTest.suite(),
492 +            CountedCompleterTest.suite(),
493              CyclicBarrierTest.suite(),
494              DelayQueueTest.suite(),
495              EntryTest.suite(),
# Line 322 | Line 518 | public class JSR166TestCase extends Test
518              TreeMapTest.suite(),
519              TreeSetTest.suite(),
520              TreeSubMapTest.suite(),
521 <            TreeSubSetTest.suite());
521 >            TreeSubSetTest.suite(),
522 >            VectorTest.suite());
523  
524          // Java8+ test classes
525          if (atLeastJava8()) {
526              String[] java8TestClassNames = {
527 +                "ArrayDeque8Test",
528                  "Atomic8Test",
529                  "CompletableFutureTest",
530                  "ConcurrentHashMap8Test",
531 <                "CountedCompleterTest",
531 >                "CountedCompleter8Test",
532                  "DoubleAccumulatorTest",
533                  "DoubleAdderTest",
534                  "ForkJoinPool8Test",
# Line 339 | Line 537 | public class JSR166TestCase extends Test
537                  "LongAdderTest",
538                  "SplittableRandomTest",
539                  "StampedLockTest",
540 +                "SubmissionPublisherTest",
541                  "ThreadLocalRandom8Test",
542 +                "TimeUnit8Test",
543              };
544              addNamedTestClasses(suite, java8TestClassNames);
545          }
# Line 347 | Line 547 | public class JSR166TestCase extends Test
547          // Java9+ test classes
548          if (atLeastJava9()) {
549              String[] java9TestClassNames = {
550 <                "ThreadPoolExecutor9Test",
550 >                "AtomicBoolean9Test",
551 >                "AtomicInteger9Test",
552 >                "AtomicIntegerArray9Test",
553 >                "AtomicLong9Test",
554 >                "AtomicLongArray9Test",
555 >                "AtomicReference9Test",
556 >                "AtomicReferenceArray9Test",
557 >                "ExecutorCompletionService9Test",
558              };
559              addNamedTestClasses(suite, java9TestClassNames);
560          }
# Line 355 | Line 562 | public class JSR166TestCase extends Test
562          return suite;
563      }
564  
565 +    /** Returns list of junit-style test method names in given class. */
566 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
567 +        Method[] methods = testClass.getDeclaredMethods();
568 +        ArrayList<String> names = new ArrayList<String>(methods.length);
569 +        for (Method method : methods) {
570 +            if (method.getName().startsWith("test")
571 +                && Modifier.isPublic(method.getModifiers())
572 +                // method.getParameterCount() requires jdk8+
573 +                && method.getParameterTypes().length == 0) {
574 +                names.add(method.getName());
575 +            }
576 +        }
577 +        return names;
578 +    }
579 +
580 +    /**
581 +     * Returns junit-style testSuite for the given test class, but
582 +     * parameterized by passing extra data to each test.
583 +     */
584 +    public static <ExtraData> Test parameterizedTestSuite
585 +        (Class<? extends JSR166TestCase> testClass,
586 +         Class<ExtraData> dataClass,
587 +         ExtraData data) {
588 +        try {
589 +            TestSuite suite = new TestSuite();
590 +            Constructor c =
591 +                testClass.getDeclaredConstructor(dataClass, String.class);
592 +            for (String methodName : testMethodNames(testClass))
593 +                suite.addTest((Test) c.newInstance(data, methodName));
594 +            return suite;
595 +        } catch (Exception e) {
596 +            throw new Error(e);
597 +        }
598 +    }
599 +
600 +    /**
601 +     * Returns junit-style testSuite for the jdk8 extension of the
602 +     * given test class, but parameterized by passing extra data to
603 +     * each test.  Uses reflection to allow compilation in jdk7.
604 +     */
605 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
606 +        (Class<? extends JSR166TestCase> testClass,
607 +         Class<ExtraData> dataClass,
608 +         ExtraData data) {
609 +        if (atLeastJava8()) {
610 +            String name = testClass.getName();
611 +            String name8 = name.replaceAll("Test$", "8Test");
612 +            if (name.equals(name8)) throw new Error(name);
613 +            try {
614 +                return (Test)
615 +                    Class.forName(name8)
616 +                    .getMethod("testSuite", new Class[] { dataClass })
617 +                    .invoke(null, data);
618 +            } catch (Exception e) {
619 +                throw new Error(e);
620 +            }
621 +        } else {
622 +            return new TestSuite();
623 +        }
624 +    }
625 +
626      // Delays for timing-dependent tests, in milliseconds.
627  
628      public static long SHORT_DELAY_MS;
# Line 363 | Line 631 | public class JSR166TestCase extends Test
631      public static long LONG_DELAY_MS;
632  
633      /**
634 <     * Returns the shortest timed delay. This could
635 <     * be reimplemented to use for example a Property.
634 >     * Returns the shortest timed delay. This can be scaled up for
635 >     * slow machines using the jsr166.delay.factor system property,
636 >     * or via jtreg's -timeoutFactor: flag.
637 >     * http://openjdk.java.net/jtreg/command-help.html
638       */
639      protected long getShortDelay() {
640 <        return 50;
640 >        return (long) (50 * delayFactor);
641      }
642  
643      /**
# Line 389 | Line 659 | public class JSR166TestCase extends Test
659      }
660  
661      /**
662 <     * Returns a new Date instance representing a time delayMillis
663 <     * milliseconds in the future.
662 >     * Returns a new Date instance representing a time at least
663 >     * delayMillis milliseconds in the future.
664       */
665      Date delayedDate(long delayMillis) {
666 <        return new Date(System.currentTimeMillis() + delayMillis);
666 >        // Add 1 because currentTimeMillis is known to round into the past.
667 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
668      }
669  
670      /**
# Line 409 | Line 680 | public class JSR166TestCase extends Test
680       * the same test have no effect.
681       */
682      public void threadRecordFailure(Throwable t) {
683 +        System.err.println(t);
684 +        dumpTestThreads();
685          threadFailure.compareAndSet(null, t);
686      }
687  
# Line 416 | Line 689 | public class JSR166TestCase extends Test
689          setDelays();
690      }
691  
692 +    void tearDownFail(String format, Object... args) {
693 +        String msg = toString() + ": " + String.format(format, args);
694 +        System.err.println(msg);
695 +        dumpTestThreads();
696 +        throw new AssertionFailedError(msg);
697 +    }
698 +
699      /**
700       * Extra checks that get done for all test cases.
701       *
# Line 443 | Line 723 | public class JSR166TestCase extends Test
723          }
724  
725          if (Thread.interrupted())
726 <            throw new AssertionFailedError("interrupt status set in main thread");
726 >            tearDownFail("interrupt status set in main thread");
727  
728          checkForkJoinPoolThreadLeaks();
729      }
730  
731      /**
732 <     * Find missing try { ... } finally { joinPool(e); }
732 >     * Finds missing PoolCleaners
733       */
734      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
735 <        Thread[] survivors = new Thread[5];
735 >        Thread[] survivors = new Thread[7];
736          int count = Thread.enumerate(survivors);
737          for (int i = 0; i < count; i++) {
738              Thread thread = survivors[i];
# Line 460 | Line 740 | public class JSR166TestCase extends Test
740              if (name.startsWith("ForkJoinPool-")) {
741                  // give thread some time to terminate
742                  thread.join(LONG_DELAY_MS);
743 <                if (!thread.isAlive()) continue;
744 <                thread.stop();
745 <                throw new AssertionFailedError
466 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
467 <                                   toString(), name));
743 >                if (thread.isAlive())
744 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
745 >                                 thread);
746              }
747          }
748 +
749 +        if (!ForkJoinPool.commonPool()
750 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
751 +            tearDownFail("ForkJoin common pool thread stuck");
752      }
753  
754      /**
# Line 479 | Line 761 | public class JSR166TestCase extends Test
761              fail(reason);
762          } catch (AssertionFailedError t) {
763              threadRecordFailure(t);
764 <            fail(reason);
764 >            throw t;
765          }
766      }
767  
# Line 547 | Line 829 | public class JSR166TestCase extends Test
829      public void threadAssertEquals(Object x, Object y) {
830          try {
831              assertEquals(x, y);
832 <        } catch (AssertionFailedError t) {
833 <            threadRecordFailure(t);
834 <            throw t;
835 <        } catch (Throwable t) {
836 <            threadUnexpectedException(t);
832 >        } catch (AssertionFailedError fail) {
833 >            threadRecordFailure(fail);
834 >            throw fail;
835 >        } catch (Throwable fail) {
836 >            threadUnexpectedException(fail);
837          }
838      }
839  
# Line 563 | Line 845 | public class JSR166TestCase extends Test
845      public void threadAssertSame(Object x, Object y) {
846          try {
847              assertSame(x, y);
848 <        } catch (AssertionFailedError t) {
849 <            threadRecordFailure(t);
850 <            throw t;
848 >        } catch (AssertionFailedError fail) {
849 >            threadRecordFailure(fail);
850 >            throw fail;
851          }
852      }
853  
# Line 606 | Line 888 | public class JSR166TestCase extends Test
888      /**
889       * Delays, via Thread.sleep, for the given millisecond delay, but
890       * if the sleep is shorter than specified, may re-sleep or yield
891 <     * until time elapses.
891 >     * until time elapses.  Ensures that the given time, as measured
892 >     * by System.nanoTime(), has elapsed.
893       */
894      static void delay(long millis) throws InterruptedException {
895 <        long startTime = System.nanoTime();
896 <        long ns = millis * 1000 * 1000;
897 <        for (;;) {
895 >        long nanos = millis * (1000 * 1000);
896 >        final long wakeupTime = System.nanoTime() + nanos;
897 >        do {
898              if (millis > 0L)
899                  Thread.sleep(millis);
900              else // too short to sleep
901                  Thread.yield();
902 <            long d = ns - (System.nanoTime() - startTime);
903 <            if (d > 0L)
904 <                millis = d / (1000 * 1000);
905 <            else
906 <                break;
902 >            nanos = wakeupTime - System.nanoTime();
903 >            millis = nanos / (1000 * 1000);
904 >        } while (nanos >= 0L);
905 >    }
906 >
907 >    /**
908 >     * Allows use of try-with-resources with per-test thread pools.
909 >     */
910 >    class PoolCleaner implements AutoCloseable {
911 >        private final ExecutorService pool;
912 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
913 >        public void close() { joinPool(pool); }
914 >    }
915 >
916 >    /**
917 >     * An extension of PoolCleaner that has an action to release the pool.
918 >     */
919 >    class PoolCleanerWithReleaser extends PoolCleaner {
920 >        private final Runnable releaser;
921 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
922 >            super(pool);
923 >            this.releaser = releaser;
924          }
925 +        public void close() {
926 +            try {
927 +                releaser.run();
928 +            } finally {
929 +                super.close();
930 +            }
931 +        }
932 +    }
933 +
934 +    PoolCleaner cleaner(ExecutorService pool) {
935 +        return new PoolCleaner(pool);
936 +    }
937 +
938 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
939 +        return new PoolCleanerWithReleaser(pool, releaser);
940 +    }
941 +
942 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
943 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
944 +    }
945 +
946 +    Runnable releaser(final CountDownLatch latch) {
947 +        return new Runnable() { public void run() {
948 +            do { latch.countDown(); }
949 +            while (latch.getCount() > 0);
950 +        }};
951 +    }
952 +
953 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
954 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
955 +    }
956 +
957 +    Runnable releaser(final AtomicBoolean flag) {
958 +        return new Runnable() { public void run() { flag.set(true); }};
959      }
960  
961      /**
962       * Waits out termination of a thread pool or fails doing so.
963       */
964 <    void joinPool(ExecutorService exec) {
964 >    void joinPool(ExecutorService pool) {
965          try {
966 <            exec.shutdown();
967 <            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
968 <                fail("ExecutorService " + exec +
969 <                     " did not terminate in a timely manner");
966 >            pool.shutdown();
967 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
968 >                try {
969 >                    threadFail("ExecutorService " + pool +
970 >                               " did not terminate in a timely manner");
971 >                } finally {
972 >                    // last resort, for the benefit of subsequent tests
973 >                    pool.shutdownNow();
974 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
975 >                }
976 >            }
977          } catch (SecurityException ok) {
978              // Allowed in case test doesn't have privs
979 <        } catch (InterruptedException ie) {
980 <            fail("Unexpected InterruptedException");
979 >        } catch (InterruptedException fail) {
980 >            threadFail("Unexpected InterruptedException");
981          }
982      }
983  
984      /**
985 <     * A debugging tool to print all stack traces, as jstack does.
985 >     * Like Runnable, but with the freedom to throw anything.
986 >     * junit folks had the same idea:
987 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
988       */
989 <    static void printAllStackTraces() {
990 <        for (ThreadInfo info :
991 <                 ManagementFactory.getThreadMXBean()
992 <                 .dumpAllThreads(true, true))
989 >    interface Action { public void run() throws Throwable; }
990 >
991 >    /**
992 >     * Runs all the given actions in parallel, failing if any fail.
993 >     * Useful for running multiple variants of tests that are
994 >     * necessarily individually slow because they must block.
995 >     */
996 >    void testInParallel(Action ... actions) {
997 >        ExecutorService pool = Executors.newCachedThreadPool();
998 >        try (PoolCleaner cleaner = cleaner(pool)) {
999 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1000 >            for (final Action action : actions)
1001 >                futures.add(pool.submit(new CheckedRunnable() {
1002 >                    public void realRun() throws Throwable { action.run();}}));
1003 >            for (Future<?> future : futures)
1004 >                try {
1005 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1006 >                } catch (ExecutionException ex) {
1007 >                    threadUnexpectedException(ex.getCause());
1008 >                } catch (Exception ex) {
1009 >                    threadUnexpectedException(ex);
1010 >                }
1011 >        }
1012 >    }
1013 >
1014 >    /**
1015 >     * A debugging tool to print stack traces of most threads, as jstack does.
1016 >     * Uninteresting threads are filtered out.
1017 >     */
1018 >    static void dumpTestThreads() {
1019 >        SecurityManager sm = System.getSecurityManager();
1020 >        if (sm != null) {
1021 >            try {
1022 >                System.setSecurityManager(null);
1023 >            } catch (SecurityException giveUp) {
1024 >                return;
1025 >            }
1026 >        }
1027 >
1028 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1029 >        System.err.println("------ stacktrace dump start ------");
1030 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1031 >            final String name = info.getThreadName();
1032 >            String lockName;
1033 >            if ("Signal Dispatcher".equals(name))
1034 >                continue;
1035 >            if ("Reference Handler".equals(name)
1036 >                && (lockName = info.getLockName()) != null
1037 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1038 >                continue;
1039 >            if ("Finalizer".equals(name)
1040 >                && (lockName = info.getLockName()) != null
1041 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1042 >                continue;
1043 >            if ("checkForWedgedTest".equals(name))
1044 >                continue;
1045              System.err.print(info);
1046 +        }
1047 +        System.err.println("------ stacktrace dump end ------");
1048 +
1049 +        if (sm != null) System.setSecurityManager(sm);
1050      }
1051  
1052      /**
# Line 666 | Line 1065 | public class JSR166TestCase extends Test
1065              // No need to optimize the failing case via Thread.join.
1066              delay(millis);
1067              assertTrue(thread.isAlive());
1068 <        } catch (InterruptedException ie) {
1069 <            fail("Unexpected InterruptedException");
1068 >        } catch (InterruptedException fail) {
1069 >            threadFail("Unexpected InterruptedException");
1070          }
1071      }
1072  
# Line 688 | Line 1087 | public class JSR166TestCase extends Test
1087              delay(millis);
1088              for (Thread thread : threads)
1089                  assertTrue(thread.isAlive());
1090 <        } catch (InterruptedException ie) {
1091 <            fail("Unexpected InterruptedException");
1090 >        } catch (InterruptedException fail) {
1091 >            threadFail("Unexpected InterruptedException");
1092          }
1093      }
1094  
# Line 710 | Line 1109 | public class JSR166TestCase extends Test
1109              future.get(timeoutMillis, MILLISECONDS);
1110              shouldThrow();
1111          } catch (TimeoutException success) {
1112 <        } catch (Exception e) {
1113 <            threadUnexpectedException(e);
1112 >        } catch (Exception fail) {
1113 >            threadUnexpectedException(fail);
1114          } finally { future.cancel(true); }
1115          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1116      }
# Line 864 | Line 1263 | public class JSR166TestCase extends Test
1263       * Sleeps until the given time has elapsed.
1264       * Throws AssertionFailedError if interrupted.
1265       */
1266 <    void sleep(long millis) {
1266 >    static void sleep(long millis) {
1267          try {
1268              delay(millis);
1269 <        } catch (InterruptedException ie) {
1269 >        } catch (InterruptedException fail) {
1270              AssertionFailedError afe =
1271                  new AssertionFailedError("Unexpected InterruptedException");
1272 <            afe.initCause(ie);
1272 >            afe.initCause(fail);
1273              throw afe;
1274          }
1275      }
# Line 880 | Line 1279 | public class JSR166TestCase extends Test
1279       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1280       */
1281      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1282 <        long startTime = System.nanoTime();
1282 >        long startTime = 0L;
1283          for (;;) {
1284              Thread.State s = thread.getState();
1285              if (s == Thread.State.BLOCKED ||
# Line 889 | Line 1288 | public class JSR166TestCase extends Test
1288                  return;
1289              else if (s == Thread.State.TERMINATED)
1290                  fail("Unexpected thread termination");
1291 +            else if (startTime == 0L)
1292 +                startTime = System.nanoTime();
1293              else if (millisElapsedSince(startTime) > timeoutMillis) {
1294                  threadAssertTrue(thread.isAlive());
1295                  return;
# Line 908 | Line 1309 | public class JSR166TestCase extends Test
1309      /**
1310       * Returns the number of milliseconds since time given by
1311       * startNanoTime, which must have been previously returned from a
1312 <     * call to {@link System.nanoTime()}.
1312 >     * call to {@link System#nanoTime()}.
1313       */
1314      static long millisElapsedSince(long startNanoTime) {
1315          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
# Line 962 | Line 1363 | public class JSR166TestCase extends Test
1363      void awaitTermination(Thread t, long timeoutMillis) {
1364          try {
1365              t.join(timeoutMillis);
1366 <        } catch (InterruptedException ie) {
1367 <            threadUnexpectedException(ie);
1366 >        } catch (InterruptedException fail) {
1367 >            threadUnexpectedException(fail);
1368          } finally {
1369              if (t.getState() != Thread.State.TERMINATED) {
1370                  t.interrupt();
1371 <                fail("Test timed out");
1371 >                threadFail("timed out waiting for thread to terminate");
1372              }
1373          }
1374      }
# Line 989 | Line 1390 | public class JSR166TestCase extends Test
1390          public final void run() {
1391              try {
1392                  realRun();
1393 <            } catch (Throwable t) {
1394 <                threadUnexpectedException(t);
1393 >            } catch (Throwable fail) {
1394 >                threadUnexpectedException(fail);
1395              }
1396          }
1397      }
# Line 1044 | Line 1445 | public class JSR166TestCase extends Test
1445                  threadShouldThrow("InterruptedException");
1446              } catch (InterruptedException success) {
1447                  threadAssertFalse(Thread.interrupted());
1448 <            } catch (Throwable t) {
1449 <                threadUnexpectedException(t);
1448 >            } catch (Throwable fail) {
1449 >                threadUnexpectedException(fail);
1450              }
1451          }
1452      }
# Line 1056 | Line 1457 | public class JSR166TestCase extends Test
1457          public final T call() {
1458              try {
1459                  return realCall();
1460 <            } catch (Throwable t) {
1461 <                threadUnexpectedException(t);
1460 >            } catch (Throwable fail) {
1461 >                threadUnexpectedException(fail);
1462                  return null;
1463              }
1464          }
# Line 1074 | Line 1475 | public class JSR166TestCase extends Test
1475                  return result;
1476              } catch (InterruptedException success) {
1477                  threadAssertFalse(Thread.interrupted());
1478 <            } catch (Throwable t) {
1479 <                threadUnexpectedException(t);
1478 >            } catch (Throwable fail) {
1479 >                threadUnexpectedException(fail);
1480              }
1481              return null;
1482          }
# Line 1092 | Line 1493 | public class JSR166TestCase extends Test
1493      public static final String TEST_STRING = "a test string";
1494  
1495      public static class StringTask implements Callable<String> {
1496 <        public String call() { return TEST_STRING; }
1496 >        final String value;
1497 >        public StringTask() { this(TEST_STRING); }
1498 >        public StringTask(String value) { this.value = value; }
1499 >        public String call() { return value; }
1500      }
1501  
1502      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1105 | Line 1509 | public class JSR166TestCase extends Test
1509              }};
1510      }
1511  
1512 <    public Runnable awaiter(final CountDownLatch latch) {
1512 >    public Runnable countDowner(final CountDownLatch latch) {
1513          return new CheckedRunnable() {
1514              public void realRun() throws InterruptedException {
1515 <                await(latch);
1515 >                latch.countDown();
1516              }};
1517      }
1518  
1519 <    public void await(CountDownLatch latch) {
1520 <        try {
1521 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1522 <        } catch (Throwable t) {
1523 <            threadUnexpectedException(t);
1519 >    class LatchAwaiter extends CheckedRunnable {
1520 >        static final int NEW = 0;
1521 >        static final int RUNNING = 1;
1522 >        static final int DONE = 2;
1523 >        final CountDownLatch latch;
1524 >        int state = NEW;
1525 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1526 >        public void realRun() throws InterruptedException {
1527 >            state = 1;
1528 >            await(latch);
1529 >            state = 2;
1530 >        }
1531 >    }
1532 >
1533 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1534 >        return new LatchAwaiter(latch);
1535 >    }
1536 >
1537 >    public void await(CountDownLatch latch, long timeoutMillis) {
1538 >        try {
1539 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1540 >                fail("timed out waiting for CountDownLatch for "
1541 >                     + (timeoutMillis/1000) + " sec");
1542 >        } catch (Throwable fail) {
1543 >            threadUnexpectedException(fail);
1544          }
1545      }
1546  
1547 +    public void await(CountDownLatch latch) {
1548 +        await(latch, LONG_DELAY_MS);
1549 +    }
1550 +
1551      public void await(Semaphore semaphore) {
1552          try {
1553 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1554 <        } catch (Throwable t) {
1555 <            threadUnexpectedException(t);
1553 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1554 >                fail("timed out waiting for Semaphore for "
1555 >                     + (LONG_DELAY_MS/1000) + " sec");
1556 >        } catch (Throwable fail) {
1557 >            threadUnexpectedException(fail);
1558          }
1559      }
1560  
# Line 1318 | Line 1748 | public class JSR166TestCase extends Test
1748          @Override protected final void compute() {
1749              try {
1750                  realCompute();
1751 <            } catch (Throwable t) {
1752 <                threadUnexpectedException(t);
1751 >            } catch (Throwable fail) {
1752 >                threadUnexpectedException(fail);
1753              }
1754          }
1755      }
# Line 1333 | Line 1763 | public class JSR166TestCase extends Test
1763          @Override protected final T compute() {
1764              try {
1765                  return realCompute();
1766 <            } catch (Throwable t) {
1767 <                threadUnexpectedException(t);
1766 >            } catch (Throwable fail) {
1767 >                threadUnexpectedException(fail);
1768                  return null;
1769              }
1770          }
# Line 1352 | Line 1782 | public class JSR166TestCase extends Test
1782       * A CyclicBarrier that uses timed await and fails with
1783       * AssertionFailedErrors instead of throwing checked exceptions.
1784       */
1785 <    public class CheckedBarrier extends CyclicBarrier {
1785 >    public static class CheckedBarrier extends CyclicBarrier {
1786          public CheckedBarrier(int parties) { super(parties); }
1787  
1788          public int await() {
1789              try {
1790                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1791 <            } catch (TimeoutException e) {
1791 >            } catch (TimeoutException timedOut) {
1792                  throw new AssertionFailedError("timed out");
1793 <            } catch (Exception e) {
1793 >            } catch (Exception fail) {
1794                  AssertionFailedError afe =
1795 <                    new AssertionFailedError("Unexpected exception: " + e);
1796 <                afe.initCause(e);
1795 >                    new AssertionFailedError("Unexpected exception: " + fail);
1796 >                afe.initCause(fail);
1797                  throw afe;
1798              }
1799          }
# Line 1391 | Line 1821 | public class JSR166TestCase extends Test
1821                  q.remove();
1822                  shouldThrow();
1823              } catch (NoSuchElementException success) {}
1824 <        } catch (InterruptedException ie) {
1395 <            threadUnexpectedException(ie);
1396 <        }
1824 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1825      }
1826  
1827      void assertSerialEquals(Object x, Object y) {
# Line 1412 | Line 1840 | public class JSR166TestCase extends Test
1840              oos.flush();
1841              oos.close();
1842              return bos.toByteArray();
1843 <        } catch (Throwable t) {
1844 <            threadUnexpectedException(t);
1843 >        } catch (Throwable fail) {
1844 >            threadUnexpectedException(fail);
1845              return new byte[0];
1846          }
1847      }
1848  
1849 +    void assertImmutable(final Object o) {
1850 +        if (o instanceof Collection) {
1851 +            assertThrows(
1852 +                UnsupportedOperationException.class,
1853 +                new Runnable() { public void run() {
1854 +                        ((Collection) o).add(null);}});
1855 +        }
1856 +    }
1857 +
1858      @SuppressWarnings("unchecked")
1859      <T> T serialClone(T o) {
1860          try {
1861              ObjectInputStream ois = new ObjectInputStream
1862                  (new ByteArrayInputStream(serialBytes(o)));
1863              T clone = (T) ois.readObject();
1864 +            if (o == clone) assertImmutable(o);
1865              assertSame(o.getClass(), clone.getClass());
1866              return clone;
1867 <        } catch (Throwable t) {
1868 <            threadUnexpectedException(t);
1867 >        } catch (Throwable fail) {
1868 >            threadUnexpectedException(fail);
1869              return null;
1870          }
1871      }
1872  
1873 +    /**
1874 +     * A version of serialClone that leaves error handling (for
1875 +     * e.g. NotSerializableException) up to the caller.
1876 +     */
1877 +    @SuppressWarnings("unchecked")
1878 +    <T> T serialClonePossiblyFailing(T o)
1879 +        throws ReflectiveOperationException, java.io.IOException {
1880 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1881 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1882 +        oos.writeObject(o);
1883 +        oos.flush();
1884 +        oos.close();
1885 +        ObjectInputStream ois = new ObjectInputStream
1886 +            (new ByteArrayInputStream(bos.toByteArray()));
1887 +        T clone = (T) ois.readObject();
1888 +        if (o == clone) assertImmutable(o);
1889 +        assertSame(o.getClass(), clone.getClass());
1890 +        return clone;
1891 +    }
1892 +
1893 +    /**
1894 +     * If o implements Cloneable and has a public clone method,
1895 +     * returns a clone of o, else null.
1896 +     */
1897 +    @SuppressWarnings("unchecked")
1898 +    <T> T cloneableClone(T o) {
1899 +        if (!(o instanceof Cloneable)) return null;
1900 +        final T clone;
1901 +        try {
1902 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1903 +        } catch (NoSuchMethodException ok) {
1904 +            return null;
1905 +        } catch (ReflectiveOperationException unexpected) {
1906 +            throw new Error(unexpected);
1907 +        }
1908 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1909 +        assertSame(o.getClass(), clone.getClass());
1910 +        return clone;
1911 +    }
1912 +
1913      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1914                               Runnable... throwingActions) {
1915          for (Runnable throwingAction : throwingActions) {
# Line 1452 | Line 1930 | public class JSR166TestCase extends Test
1930                  shouldThrow(expectedExceptionClass.getName());
1931          }
1932      }
1933 +
1934 +    public void assertIteratorExhausted(Iterator<?> it) {
1935 +        try {
1936 +            it.next();
1937 +            shouldThrow();
1938 +        } catch (NoSuchElementException success) {}
1939 +        assertFalse(it.hasNext());
1940 +    }
1941 +
1942 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1943 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1944 +    }
1945 +
1946 +    public Runnable runnableThrowing(final RuntimeException ex) {
1947 +        return new Runnable() { public void run() { throw ex; }};
1948 +    }
1949 +
1950 +    /** A reusable thread pool to be shared by tests. */
1951 +    static final ExecutorService cachedThreadPool =
1952 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1953 +                               1000L, MILLISECONDS,
1954 +                               new SynchronousQueue<Runnable>());
1955 +
1956 +    static <T> void shuffle(T[] array) {
1957 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1958 +    }
1959   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines