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.117 by jsr166, Mon Jun 9 18:17:37 2014 UTC vs.
Revision 1.212 by jsr166, Fri Dec 9 04:24:07 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
12 > * @modules java.base/java.util.concurrent:open
13 > *          java.management
14 > * @build *
15 > * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
16 > * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
17 > * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -Djava.util.secureRandomSeed=true JSR166TestCase
18 > */
19 >
20 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
21 > import static java.util.concurrent.TimeUnit.MINUTES;
22 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
23 >
24   import java.io.ByteArrayInputStream;
25   import java.io.ByteArrayOutputStream;
26   import java.io.ObjectInputStream;
27   import java.io.ObjectOutputStream;
28   import java.lang.management.ManagementFactory;
29   import java.lang.management.ThreadInfo;
30 + import java.lang.management.ThreadMXBean;
31 + import java.lang.reflect.Constructor;
32   import java.lang.reflect.Method;
33 + import java.lang.reflect.Modifier;
34 + import java.nio.file.Files;
35 + import java.nio.file.Paths;
36 + import java.security.CodeSource;
37 + import java.security.Permission;
38 + import java.security.PermissionCollection;
39 + import java.security.Permissions;
40 + import java.security.Policy;
41 + import java.security.ProtectionDomain;
42 + import java.security.SecurityPermission;
43   import java.util.ArrayList;
44   import java.util.Arrays;
45 + import java.util.Collection;
46 + import java.util.Collections;
47   import java.util.Date;
48   import java.util.Enumeration;
49 + import java.util.Iterator;
50   import java.util.List;
51   import java.util.NoSuchElementException;
52   import java.util.PropertyPermission;
53 < import java.util.concurrent.*;
53 > import java.util.concurrent.BlockingQueue;
54 > import java.util.concurrent.Callable;
55 > import java.util.concurrent.CountDownLatch;
56 > import java.util.concurrent.CyclicBarrier;
57 > import java.util.concurrent.ExecutionException;
58 > import java.util.concurrent.Executors;
59 > import java.util.concurrent.ExecutorService;
60 > import java.util.concurrent.ForkJoinPool;
61 > import java.util.concurrent.Future;
62 > import java.util.concurrent.RecursiveAction;
63 > import java.util.concurrent.RecursiveTask;
64 > import java.util.concurrent.RejectedExecutionHandler;
65 > import java.util.concurrent.Semaphore;
66 > import java.util.concurrent.SynchronousQueue;
67 > import java.util.concurrent.ThreadFactory;
68 > import java.util.concurrent.ThreadLocalRandom;
69 > import java.util.concurrent.ThreadPoolExecutor;
70 > import java.util.concurrent.TimeoutException;
71   import java.util.concurrent.atomic.AtomicBoolean;
72   import java.util.concurrent.atomic.AtomicReference;
73 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
73 > import java.util.regex.Matcher;
74   import java.util.regex.Pattern;
75 < import java.security.CodeSource;
76 < import java.security.Permission;
77 < import java.security.PermissionCollection;
78 < import java.security.Permissions;
79 < import java.security.Policy;
80 < import java.security.ProtectionDomain;
36 < import java.security.SecurityPermission;
75 >
76 > import junit.framework.AssertionFailedError;
77 > import junit.framework.Test;
78 > import junit.framework.TestCase;
79 > import junit.framework.TestResult;
80 > import junit.framework.TestSuite;
81  
82   /**
83   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 45 | Line 89 | import java.security.SecurityPermission;
89   *
90   * <ol>
91   *
92 < * <li> All assertions in code running in generated threads must use
92 > * <li>All assertions in code running in generated threads must use
93   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
94   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
95   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
96   * particularly recommended) for other code to use these forms too.
97   * Only the most typically used JUnit assertion methods are defined
98 < * this way, but enough to live with.</li>
98 > * this way, but enough to live with.
99   *
100 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
100 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
101   * to invoke {@code super.setUp} and {@code super.tearDown} within
102   * them. These methods are used to clear and check for thread
103 < * assertion failures.</li>
103 > * assertion failures.
104   *
105   * <li>All delays and timeouts must use one of the constants {@code
106   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 67 | Line 111 | import java.security.SecurityPermission;
111   * is always discriminable as larger than SHORT and smaller than
112   * MEDIUM.  And so on. These constants are set to conservative values,
113   * but even so, if there is ever any doubt, they can all be increased
114 < * in one spot to rerun tests on slower platforms.</li>
114 > * in one spot to rerun tests on slower platforms.
115   *
116 < * <li> All threads generated must be joined inside each test case
116 > * <li>All threads generated must be joined inside each test case
117   * method (or {@code fail} to do so) before returning from the
118   * method. The {@code joinPool} method can be used to do this when
119 < * using Executors.</li>
119 > * using Executors.
120   *
121   * </ol>
122   *
123   * <p><b>Other notes</b>
124   * <ul>
125   *
126 < * <li> Usually, there is one testcase method per JSR166 method
126 > * <li>Usually, there is one testcase method per JSR166 method
127   * covering "normal" operation, and then as many exception-testing
128   * methods as there are exceptions the method can throw. Sometimes
129   * there are multiple tests per JSR166 method when the different
130   * "normal" behaviors differ significantly. And sometimes testcases
131 < * cover multiple methods when they cannot be tested in
88 < * isolation.</li>
131 > * cover multiple methods when they cannot be tested in isolation.
132   *
133 < * <li> The documentation style for testcases is to provide as javadoc
133 > * <li>The documentation style for testcases is to provide as javadoc
134   * a simple sentence or two describing the property that the testcase
135   * method purports to test. The javadocs do not say anything about how
136 < * the property is tested. To find out, read the code.</li>
136 > * the property is tested. To find out, read the code.
137   *
138 < * <li> These tests are "conformance tests", and do not attempt to
138 > * <li>These tests are "conformance tests", and do not attempt to
139   * test throughput, latency, scalability or other performance factors
140   * (see the separate "jtreg" tests for a set intended to check these
141   * for the most central aspects of functionality.) So, most tests use
142   * the smallest sensible numbers of threads, collection sizes, etc
143 < * needed to check basic conformance.</li>
143 > * needed to check basic conformance.
144   *
145   * <li>The test classes currently do not declare inclusion in
146   * any particular package to simplify things for people integrating
147 < * them in TCK test suites.</li>
147 > * them in TCK test suites.
148   *
149 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
150 < * runs all JSR166 unit tests.</li>
149 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
150 > * runs all JSR166 unit tests.
151   *
152   * </ul>
153   */
# Line 116 | Line 159 | public class JSR166TestCase extends Test
159          Boolean.getBoolean("jsr166.expensiveTests");
160  
161      /**
162 +     * If true, also run tests that are not part of the official tck
163 +     * because they test unspecified implementation details.
164 +     */
165 +    protected static final boolean testImplementationDetails =
166 +        Boolean.getBoolean("jsr166.testImplementationDetails");
167 +
168 +    /**
169       * If true, report on stdout all "slow" tests, that is, ones that
170       * take more than profileThreshold milliseconds to execute.
171       */
# Line 136 | Line 186 | public class JSR166TestCase extends Test
186          Integer.getInteger("jsr166.runsPerTest", 1);
187  
188      /**
189 +     * The number of repetitions of the test suite (for finding leaks?).
190 +     */
191 +    private static final int suiteRuns =
192 +        Integer.getInteger("jsr166.suiteRuns", 1);
193 +
194 +    /**
195 +     * Returns the value of the system property, or NaN if not defined.
196 +     */
197 +    private static float systemPropertyValue(String name) {
198 +        String floatString = System.getProperty(name);
199 +        if (floatString == null)
200 +            return Float.NaN;
201 +        try {
202 +            return Float.parseFloat(floatString);
203 +        } catch (NumberFormatException ex) {
204 +            throw new IllegalArgumentException(
205 +                String.format("Bad float value in system property %s=%s",
206 +                              name, floatString));
207 +        }
208 +    }
209 +
210 +    /**
211 +     * The scaling factor to apply to standard delays used in tests.
212 +     * May be initialized from any of:
213 +     * - the "jsr166.delay.factor" system property
214 +     * - the "test.timeout.factor" system property (as used by jtreg)
215 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
216 +     * - hard-coded fuzz factor when using a known slowpoke VM
217 +     */
218 +    private static final float delayFactor = delayFactor();
219 +
220 +    private static float delayFactor() {
221 +        float x;
222 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
223 +            return x;
224 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
225 +            return x;
226 +        String prop = System.getProperty("java.vm.version");
227 +        if (prop != null && prop.matches(".*debug.*"))
228 +            return 4.0f; // How much slower is fastdebug than product?!
229 +        return 1.0f;
230 +    }
231 +
232 +    public JSR166TestCase() { super(); }
233 +    public JSR166TestCase(String name) { super(name); }
234 +
235 +    /**
236       * A filter for tests to run, matching strings of the form
237       * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
238       * Usefully combined with jsr166.runsPerTest.
# Line 147 | Line 244 | public class JSR166TestCase extends Test
244          return (regex == null) ? null : Pattern.compile(regex);
245      }
246  
247 <    protected void runTest() throws Throwable {
247 >    // Instrumentation to debug very rare, but very annoying hung test runs.
248 >    static volatile TestCase currentTestCase;
249 >    // static volatile int currentRun = 0;
250 >    static {
251 >        Runnable checkForWedgedTest = new Runnable() { public void run() {
252 >            // Avoid spurious reports with enormous runsPerTest.
253 >            // A single test case run should never take more than 1 second.
254 >            // But let's cap it at the high end too ...
255 >            final int timeoutMinutes =
256 >                Math.min(15, Math.max(runsPerTest / 60, 1));
257 >            for (TestCase lastTestCase = currentTestCase;;) {
258 >                try { MINUTES.sleep(timeoutMinutes); }
259 >                catch (InterruptedException unexpected) { break; }
260 >                if (lastTestCase == currentTestCase) {
261 >                    System.err.printf(
262 >                        "Looks like we're stuck running test: %s%n",
263 >                        lastTestCase);
264 > //                     System.err.printf(
265 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
266 > //                         lastTestCase, currentRun, runsPerTest);
267 > //                     System.err.println("availableProcessors=" +
268 > //                         Runtime.getRuntime().availableProcessors());
269 > //                     System.err.printf("cpu model = %s%n", cpuModel());
270 >                    dumpTestThreads();
271 >                    // one stack dump is probably enough; more would be spam
272 >                    break;
273 >                }
274 >                lastTestCase = currentTestCase;
275 >            }}};
276 >        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
277 >        thread.setDaemon(true);
278 >        thread.start();
279 >    }
280 >
281 > //     public static String cpuModel() {
282 > //         try {
283 > //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
284 > //                 .matcher(new String(
285 > //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
286 > //             matcher.find();
287 > //             return matcher.group(1);
288 > //         } catch (Exception ex) { return null; }
289 > //     }
290 >
291 >    public void runBare() throws Throwable {
292 >        currentTestCase = this;
293          if (methodFilter == null
294 <            || methodFilter.matcher(toString()).find()) {
295 <            for (int i = 0; i < runsPerTest; i++) {
296 <                if (profileTests)
297 <                    runTestProfiled();
298 <                else
299 <                    super.runTest();
300 <            }
294 >            || methodFilter.matcher(toString()).find())
295 >            super.runBare();
296 >    }
297 >
298 >    protected void runTest() throws Throwable {
299 >        for (int i = 0; i < runsPerTest; i++) {
300 >            // currentRun = i;
301 >            if (profileTests)
302 >                runTestProfiled();
303 >            else
304 >                super.runTest();
305          }
306      }
307  
308      protected void runTestProfiled() throws Throwable {
309 <        // Warmup run, notably to trigger all needed classloading.
310 <        super.runTest();
165 <        long t0 = System.nanoTime();
166 <        try {
309 >        for (int i = 0; i < 2; i++) {
310 >            long startTime = System.nanoTime();
311              super.runTest();
312 <        } finally {
313 <            long elapsedMillis = millisElapsedSince(t0);
314 <            if (elapsedMillis >= profileThreshold)
312 >            long elapsedMillis = millisElapsedSince(startTime);
313 >            if (elapsedMillis < profileThreshold)
314 >                break;
315 >            // Never report first run of any test; treat it as a
316 >            // warmup run, notably to trigger all needed classloading,
317 >            if (i > 0)
318                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
319          }
320      }
321  
322      /**
323       * Runs all JSR166 unit tests using junit.textui.TestRunner.
177     * Optional command line arg provides the number of iterations to
178     * repeat running the tests.
324       */
325      public static void main(String[] args) {
326 +        main(suite(), args);
327 +    }
328 +
329 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
330 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
331 +        long runTime;
332 +        public void startTest(Test test) {}
333 +        protected void printHeader(long runTime) {
334 +            this.runTime = runTime; // defer printing for later
335 +        }
336 +        protected void printFooter(TestResult result) {
337 +            if (result.wasSuccessful()) {
338 +                getWriter().println("OK (" + result.runCount() + " tests)"
339 +                    + "  Time: " + elapsedTimeAsString(runTime));
340 +            } else {
341 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
342 +                super.printFooter(result);
343 +            }
344 +        }
345 +    }
346 +
347 +    /**
348 +     * Returns a TestRunner that doesn't bother with unnecessary
349 +     * fluff, like printing a "." for each test case.
350 +     */
351 +    static junit.textui.TestRunner newPithyTestRunner() {
352 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
353 +        runner.setPrinter(new PithyResultPrinter(System.out));
354 +        return runner;
355 +    }
356 +
357 +    /**
358 +     * Runs all unit tests in the given test suite.
359 +     * Actual behavior influenced by jsr166.* system properties.
360 +     */
361 +    static void main(Test suite, String[] args) {
362          if (useSecurityManager) {
363              System.err.println("Setting a permissive security manager");
364              Policy.setPolicy(permissivePolicy());
365              System.setSecurityManager(new SecurityManager());
366          }
367 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
368 <
369 <        Test s = suite();
370 <        for (int i = 0; i < iters; ++i) {
190 <            junit.textui.TestRunner.run(s);
367 >        for (int i = 0; i < suiteRuns; i++) {
368 >            TestResult result = newPithyTestRunner().doRun(suite);
369 >            if (!result.wasSuccessful())
370 >                System.exit(1);
371              System.gc();
372              System.runFinalization();
373          }
194        System.exit(0);
374      }
375  
376      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 242 | Line 421 | public class JSR166TestCase extends Test
421      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
422      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
423      public static boolean atLeastJava9() {
424 <        // As of 2014-05, java9 still uses 52.0 class file version
425 <        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
424 >        return JAVA_CLASS_VERSION >= 53.0
425 >            // As of 2015-09, java9 still uses 52.0 class file version
426 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
427 >    }
428 >    public static boolean atLeastJava10() {
429 >        return JAVA_CLASS_VERSION >= 54.0
430 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
431      }
432  
433      /**
# Line 265 | Line 449 | public class JSR166TestCase extends Test
449              AbstractQueuedLongSynchronizerTest.suite(),
450              ArrayBlockingQueueTest.suite(),
451              ArrayDequeTest.suite(),
452 +            ArrayListTest.suite(),
453              AtomicBooleanTest.suite(),
454              AtomicIntegerArrayTest.suite(),
455              AtomicIntegerFieldUpdaterTest.suite(),
# Line 287 | Line 472 | public class JSR166TestCase extends Test
472              CopyOnWriteArrayListTest.suite(),
473              CopyOnWriteArraySetTest.suite(),
474              CountDownLatchTest.suite(),
475 +            CountedCompleterTest.suite(),
476              CyclicBarrierTest.suite(),
477              DelayQueueTest.suite(),
478              EntryTest.suite(),
# Line 315 | Line 501 | public class JSR166TestCase extends Test
501              TreeMapTest.suite(),
502              TreeSetTest.suite(),
503              TreeSubMapTest.suite(),
504 <            TreeSubSetTest.suite());
504 >            TreeSubSetTest.suite(),
505 >            VectorTest.suite());
506  
507          // Java8+ test classes
508          if (atLeastJava8()) {
509              String[] java8TestClassNames = {
510 +                "ArrayDeque8Test",
511                  "Atomic8Test",
512                  "CompletableFutureTest",
513                  "ConcurrentHashMap8Test",
514 <                "CountedCompleterTest",
514 >                "CountedCompleter8Test",
515                  "DoubleAccumulatorTest",
516                  "DoubleAdderTest",
517                  "ForkJoinPool8Test",
# Line 332 | Line 520 | public class JSR166TestCase extends Test
520                  "LongAdderTest",
521                  "SplittableRandomTest",
522                  "StampedLockTest",
523 +                "SubmissionPublisherTest",
524                  "ThreadLocalRandom8Test",
525 +                "TimeUnit8Test",
526              };
527              addNamedTestClasses(suite, java8TestClassNames);
528          }
# Line 340 | Line 530 | public class JSR166TestCase extends Test
530          // Java9+ test classes
531          if (atLeastJava9()) {
532              String[] java9TestClassNames = {
533 <                "ThreadPoolExecutor9Test",
533 >                "AtomicBoolean9Test",
534 >                "AtomicInteger9Test",
535 >                "AtomicIntegerArray9Test",
536 >                "AtomicLong9Test",
537 >                "AtomicLongArray9Test",
538 >                "AtomicReference9Test",
539 >                "AtomicReferenceArray9Test",
540 >                "ExecutorCompletionService9Test",
541              };
542              addNamedTestClasses(suite, java9TestClassNames);
543          }
# Line 348 | Line 545 | public class JSR166TestCase extends Test
545          return suite;
546      }
547  
548 +    /** Returns list of junit-style test method names in given class. */
549 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
550 +        Method[] methods = testClass.getDeclaredMethods();
551 +        ArrayList<String> names = new ArrayList<String>(methods.length);
552 +        for (Method method : methods) {
553 +            if (method.getName().startsWith("test")
554 +                && Modifier.isPublic(method.getModifiers())
555 +                // method.getParameterCount() requires jdk8+
556 +                && method.getParameterTypes().length == 0) {
557 +                names.add(method.getName());
558 +            }
559 +        }
560 +        return names;
561 +    }
562 +
563 +    /**
564 +     * Returns junit-style testSuite for the given test class, but
565 +     * parameterized by passing extra data to each test.
566 +     */
567 +    public static <ExtraData> Test parameterizedTestSuite
568 +        (Class<? extends JSR166TestCase> testClass,
569 +         Class<ExtraData> dataClass,
570 +         ExtraData data) {
571 +        try {
572 +            TestSuite suite = new TestSuite();
573 +            Constructor c =
574 +                testClass.getDeclaredConstructor(dataClass, String.class);
575 +            for (String methodName : testMethodNames(testClass))
576 +                suite.addTest((Test) c.newInstance(data, methodName));
577 +            return suite;
578 +        } catch (Exception e) {
579 +            throw new Error(e);
580 +        }
581 +    }
582 +
583 +    /**
584 +     * Returns junit-style testSuite for the jdk8 extension of the
585 +     * given test class, but parameterized by passing extra data to
586 +     * each test.  Uses reflection to allow compilation in jdk7.
587 +     */
588 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
589 +        (Class<? extends JSR166TestCase> testClass,
590 +         Class<ExtraData> dataClass,
591 +         ExtraData data) {
592 +        if (atLeastJava8()) {
593 +            String name = testClass.getName();
594 +            String name8 = name.replaceAll("Test$", "8Test");
595 +            if (name.equals(name8)) throw new Error(name);
596 +            try {
597 +                return (Test)
598 +                    Class.forName(name8)
599 +                    .getMethod("testSuite", new Class[] { dataClass })
600 +                    .invoke(null, data);
601 +            } catch (Exception e) {
602 +                throw new Error(e);
603 +            }
604 +        } else {
605 +            return new TestSuite();
606 +        }
607 +    }
608 +
609      // Delays for timing-dependent tests, in milliseconds.
610  
611      public static long SHORT_DELAY_MS;
# Line 356 | Line 614 | public class JSR166TestCase extends Test
614      public static long LONG_DELAY_MS;
615  
616      /**
617 <     * Returns the shortest timed delay. This could
618 <     * be reimplemented to use for example a Property.
617 >     * Returns the shortest timed delay. This can be scaled up for
618 >     * slow machines using the jsr166.delay.factor system property,
619 >     * or via jtreg's -timeoutFactor: flag.
620 >     * http://openjdk.java.net/jtreg/command-help.html
621       */
622      protected long getShortDelay() {
623 <        return 50;
623 >        return (long) (50 * delayFactor);
624      }
625  
626      /**
# Line 382 | Line 642 | public class JSR166TestCase extends Test
642      }
643  
644      /**
645 <     * Returns a new Date instance representing a time delayMillis
646 <     * milliseconds in the future.
645 >     * Returns a new Date instance representing a time at least
646 >     * delayMillis milliseconds in the future.
647       */
648      Date delayedDate(long delayMillis) {
649 <        return new Date(System.currentTimeMillis() + delayMillis);
649 >        // Add 1 because currentTimeMillis is known to round into the past.
650 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
651      }
652  
653      /**
# Line 402 | Line 663 | public class JSR166TestCase extends Test
663       * the same test have no effect.
664       */
665      public void threadRecordFailure(Throwable t) {
666 +        System.err.println(t);
667 +        dumpTestThreads();
668          threadFailure.compareAndSet(null, t);
669      }
670  
# Line 409 | Line 672 | public class JSR166TestCase extends Test
672          setDelays();
673      }
674  
675 +    void tearDownFail(String format, Object... args) {
676 +        String msg = toString() + ": " + String.format(format, args);
677 +        System.err.println(msg);
678 +        dumpTestThreads();
679 +        throw new AssertionFailedError(msg);
680 +    }
681 +
682      /**
683       * Extra checks that get done for all test cases.
684       *
# Line 436 | Line 706 | public class JSR166TestCase extends Test
706          }
707  
708          if (Thread.interrupted())
709 <            throw new AssertionFailedError("interrupt status set in main thread");
709 >            tearDownFail("interrupt status set in main thread");
710  
711          checkForkJoinPoolThreadLeaks();
712      }
713  
714      /**
715 <     * Find missing try { ... } finally { joinPool(e); }
715 >     * Finds missing PoolCleaners
716       */
717      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
718 <        Thread[] survivors = new Thread[5];
718 >        Thread[] survivors = new Thread[7];
719          int count = Thread.enumerate(survivors);
720          for (int i = 0; i < count; i++) {
721              Thread thread = survivors[i];
# Line 453 | Line 723 | public class JSR166TestCase extends Test
723              if (name.startsWith("ForkJoinPool-")) {
724                  // give thread some time to terminate
725                  thread.join(LONG_DELAY_MS);
726 <                if (!thread.isAlive()) continue;
727 <                thread.stop();
728 <                throw new AssertionFailedError
459 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
460 <                                   toString(), name));
726 >                if (thread.isAlive())
727 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
728 >                                 thread);
729              }
730          }
731 +
732 +        if (!ForkJoinPool.commonPool()
733 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
734 +            tearDownFail("ForkJoin common pool thread stuck");
735      }
736  
737      /**
# Line 472 | Line 744 | public class JSR166TestCase extends Test
744              fail(reason);
745          } catch (AssertionFailedError t) {
746              threadRecordFailure(t);
747 <            fail(reason);
747 >            throw t;
748          }
749      }
750  
# Line 540 | Line 812 | public class JSR166TestCase extends Test
812      public void threadAssertEquals(Object x, Object y) {
813          try {
814              assertEquals(x, y);
815 <        } catch (AssertionFailedError t) {
816 <            threadRecordFailure(t);
817 <            throw t;
818 <        } catch (Throwable t) {
819 <            threadUnexpectedException(t);
815 >        } catch (AssertionFailedError fail) {
816 >            threadRecordFailure(fail);
817 >            throw fail;
818 >        } catch (Throwable fail) {
819 >            threadUnexpectedException(fail);
820          }
821      }
822  
# Line 556 | Line 828 | public class JSR166TestCase extends Test
828      public void threadAssertSame(Object x, Object y) {
829          try {
830              assertSame(x, y);
831 <        } catch (AssertionFailedError t) {
832 <            threadRecordFailure(t);
833 <            throw t;
831 >        } catch (AssertionFailedError fail) {
832 >            threadRecordFailure(fail);
833 >            throw fail;
834          }
835      }
836  
# Line 599 | Line 871 | public class JSR166TestCase extends Test
871      /**
872       * Delays, via Thread.sleep, for the given millisecond delay, but
873       * if the sleep is shorter than specified, may re-sleep or yield
874 <     * until time elapses.
874 >     * until time elapses.  Ensures that the given time, as measured
875 >     * by System.nanoTime(), has elapsed.
876       */
877      static void delay(long millis) throws InterruptedException {
878 <        long startTime = System.nanoTime();
879 <        long ns = millis * 1000 * 1000;
880 <        for (;;) {
878 >        long nanos = millis * (1000 * 1000);
879 >        final long wakeupTime = System.nanoTime() + nanos;
880 >        do {
881              if (millis > 0L)
882                  Thread.sleep(millis);
883              else // too short to sleep
884                  Thread.yield();
885 <            long d = ns - (System.nanoTime() - startTime);
886 <            if (d > 0L)
887 <                millis = d / (1000 * 1000);
888 <            else
889 <                break;
885 >            nanos = wakeupTime - System.nanoTime();
886 >            millis = nanos / (1000 * 1000);
887 >        } while (nanos >= 0L);
888 >    }
889 >
890 >    /**
891 >     * Allows use of try-with-resources with per-test thread pools.
892 >     */
893 >    class PoolCleaner implements AutoCloseable {
894 >        private final ExecutorService pool;
895 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
896 >        public void close() { joinPool(pool); }
897 >    }
898 >
899 >    /**
900 >     * An extension of PoolCleaner that has an action to release the pool.
901 >     */
902 >    class PoolCleanerWithReleaser extends PoolCleaner {
903 >        private final Runnable releaser;
904 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
905 >            super(pool);
906 >            this.releaser = releaser;
907 >        }
908 >        public void close() {
909 >            try {
910 >                releaser.run();
911 >            } finally {
912 >                super.close();
913 >            }
914          }
915      }
916  
917 +    PoolCleaner cleaner(ExecutorService pool) {
918 +        return new PoolCleaner(pool);
919 +    }
920 +
921 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
922 +        return new PoolCleanerWithReleaser(pool, releaser);
923 +    }
924 +
925 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
926 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
927 +    }
928 +
929 +    Runnable releaser(final CountDownLatch latch) {
930 +        return new Runnable() { public void run() {
931 +            do { latch.countDown(); }
932 +            while (latch.getCount() > 0);
933 +        }};
934 +    }
935 +
936 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
937 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
938 +    }
939 +
940 +    Runnable releaser(final AtomicBoolean flag) {
941 +        return new Runnable() { public void run() { flag.set(true); }};
942 +    }
943 +
944      /**
945       * Waits out termination of a thread pool or fails doing so.
946       */
947 <    void joinPool(ExecutorService exec) {
947 >    void joinPool(ExecutorService pool) {
948          try {
949 <            exec.shutdown();
950 <            assertTrue("ExecutorService did not terminate in a timely manner",
951 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
949 >            pool.shutdown();
950 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
951 >                try {
952 >                    threadFail("ExecutorService " + pool +
953 >                               " did not terminate in a timely manner");
954 >                } finally {
955 >                    // last resort, for the benefit of subsequent tests
956 >                    pool.shutdownNow();
957 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
958 >                }
959 >            }
960          } catch (SecurityException ok) {
961              // Allowed in case test doesn't have privs
962 <        } catch (InterruptedException ie) {
963 <            fail("Unexpected InterruptedException");
962 >        } catch (InterruptedException fail) {
963 >            threadFail("Unexpected InterruptedException");
964          }
965      }
966  
967      /**
968 <     * A debugging tool to print all stack traces, as jstack does.
968 >     * Like Runnable, but with the freedom to throw anything.
969 >     * junit folks had the same idea:
970 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
971 >     */
972 >    interface Action { public void run() throws Throwable; }
973 >
974 >    /**
975 >     * Runs all the given actions in parallel, failing if any fail.
976 >     * Useful for running multiple variants of tests that are
977 >     * necessarily individually slow because they must block.
978       */
979 <    static void printAllStackTraces() {
980 <        for (ThreadInfo info :
981 <                 ManagementFactory.getThreadMXBean()
982 <                 .dumpAllThreads(true, true))
979 >    void testInParallel(Action ... actions) {
980 >        ExecutorService pool = Executors.newCachedThreadPool();
981 >        try (PoolCleaner cleaner = cleaner(pool)) {
982 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
983 >            for (final Action action : actions)
984 >                futures.add(pool.submit(new CheckedRunnable() {
985 >                    public void realRun() throws Throwable { action.run();}}));
986 >            for (Future<?> future : futures)
987 >                try {
988 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
989 >                } catch (ExecutionException ex) {
990 >                    threadUnexpectedException(ex.getCause());
991 >                } catch (Exception ex) {
992 >                    threadUnexpectedException(ex);
993 >                }
994 >        }
995 >    }
996 >
997 >    /**
998 >     * A debugging tool to print stack traces of most threads, as jstack does.
999 >     * Uninteresting threads are filtered out.
1000 >     */
1001 >    static void dumpTestThreads() {
1002 >        SecurityManager sm = System.getSecurityManager();
1003 >        if (sm != null) {
1004 >            try {
1005 >                System.setSecurityManager(null);
1006 >            } catch (SecurityException giveUp) {
1007 >                return;
1008 >            }
1009 >        }
1010 >
1011 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1012 >        System.err.println("------ stacktrace dump start ------");
1013 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1014 >            final String name = info.getThreadName();
1015 >            String lockName;
1016 >            if ("Signal Dispatcher".equals(name))
1017 >                continue;
1018 >            if ("Reference Handler".equals(name)
1019 >                && (lockName = info.getLockName()) != null
1020 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1021 >                continue;
1022 >            if ("Finalizer".equals(name)
1023 >                && (lockName = info.getLockName()) != null
1024 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1025 >                continue;
1026 >            if ("checkForWedgedTest".equals(name))
1027 >                continue;
1028              System.err.print(info);
1029 +        }
1030 +        System.err.println("------ stacktrace dump end ------");
1031 +
1032 +        if (sm != null) System.setSecurityManager(sm);
1033      }
1034  
1035      /**
# Line 658 | Line 1048 | public class JSR166TestCase extends Test
1048              // No need to optimize the failing case via Thread.join.
1049              delay(millis);
1050              assertTrue(thread.isAlive());
1051 <        } catch (InterruptedException ie) {
1052 <            fail("Unexpected InterruptedException");
1051 >        } catch (InterruptedException fail) {
1052 >            threadFail("Unexpected InterruptedException");
1053          }
1054      }
1055  
# Line 680 | Line 1070 | public class JSR166TestCase extends Test
1070              delay(millis);
1071              for (Thread thread : threads)
1072                  assertTrue(thread.isAlive());
1073 <        } catch (InterruptedException ie) {
1074 <            fail("Unexpected InterruptedException");
1073 >        } catch (InterruptedException fail) {
1074 >            threadFail("Unexpected InterruptedException");
1075          }
1076      }
1077  
# Line 702 | Line 1092 | public class JSR166TestCase extends Test
1092              future.get(timeoutMillis, MILLISECONDS);
1093              shouldThrow();
1094          } catch (TimeoutException success) {
1095 <        } catch (Exception e) {
1096 <            threadUnexpectedException(e);
1095 >        } catch (Exception fail) {
1096 >            threadUnexpectedException(fail);
1097          } finally { future.cancel(true); }
1098          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1099      }
# Line 856 | Line 1246 | public class JSR166TestCase extends Test
1246       * Sleeps until the given time has elapsed.
1247       * Throws AssertionFailedError if interrupted.
1248       */
1249 <    void sleep(long millis) {
1249 >    static void sleep(long millis) {
1250          try {
1251              delay(millis);
1252 <        } catch (InterruptedException ie) {
1252 >        } catch (InterruptedException fail) {
1253              AssertionFailedError afe =
1254                  new AssertionFailedError("Unexpected InterruptedException");
1255 <            afe.initCause(ie);
1255 >            afe.initCause(fail);
1256              throw afe;
1257          }
1258      }
# Line 872 | Line 1262 | public class JSR166TestCase extends Test
1262       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1263       */
1264      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1265 <        long startTime = System.nanoTime();
1265 >        long startTime = 0L;
1266          for (;;) {
1267              Thread.State s = thread.getState();
1268              if (s == Thread.State.BLOCKED ||
# Line 881 | Line 1271 | public class JSR166TestCase extends Test
1271                  return;
1272              else if (s == Thread.State.TERMINATED)
1273                  fail("Unexpected thread termination");
1274 +            else if (startTime == 0L)
1275 +                startTime = System.nanoTime();
1276              else if (millisElapsedSince(startTime) > timeoutMillis) {
1277                  threadAssertTrue(thread.isAlive());
1278                  return;
# Line 900 | Line 1292 | public class JSR166TestCase extends Test
1292      /**
1293       * Returns the number of milliseconds since time given by
1294       * startNanoTime, which must have been previously returned from a
1295 <     * call to {@link System.nanoTime()}.
1295 >     * call to {@link System#nanoTime()}.
1296       */
1297      static long millisElapsedSince(long startNanoTime) {
1298          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1299      }
1300  
1301 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1302 + //         long startTime = System.nanoTime();
1303 + //         try {
1304 + //             r.run();
1305 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1306 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1307 + //             throw new AssertionFailedError("did not return promptly");
1308 + //     }
1309 +
1310 + //     void assertTerminatesPromptly(Runnable r) {
1311 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1312 + //     }
1313 +
1314 +    /**
1315 +     * Checks that timed f.get() returns the expected value, and does not
1316 +     * wait for the timeout to elapse before returning.
1317 +     */
1318 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1319 +        long startTime = System.nanoTime();
1320 +        try {
1321 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1322 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1323 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1324 +            throw new AssertionFailedError("timed get did not return promptly");
1325 +    }
1326 +
1327 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1328 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1329 +    }
1330 +
1331      /**
1332       * Returns a new started daemon Thread running the given runnable.
1333       */
# Line 924 | Line 1346 | public class JSR166TestCase extends Test
1346      void awaitTermination(Thread t, long timeoutMillis) {
1347          try {
1348              t.join(timeoutMillis);
1349 <        } catch (InterruptedException ie) {
1350 <            threadUnexpectedException(ie);
1349 >        } catch (InterruptedException fail) {
1350 >            threadUnexpectedException(fail);
1351          } finally {
1352              if (t.getState() != Thread.State.TERMINATED) {
1353                  t.interrupt();
1354 <                fail("Test timed out");
1354 >                threadFail("timed out waiting for thread to terminate");
1355              }
1356          }
1357      }
# Line 951 | Line 1373 | public class JSR166TestCase extends Test
1373          public final void run() {
1374              try {
1375                  realRun();
1376 <            } catch (Throwable t) {
1377 <                threadUnexpectedException(t);
1376 >            } catch (Throwable fail) {
1377 >                threadUnexpectedException(fail);
1378              }
1379          }
1380      }
# Line 1006 | Line 1428 | public class JSR166TestCase extends Test
1428                  threadShouldThrow("InterruptedException");
1429              } catch (InterruptedException success) {
1430                  threadAssertFalse(Thread.interrupted());
1431 <            } catch (Throwable t) {
1432 <                threadUnexpectedException(t);
1431 >            } catch (Throwable fail) {
1432 >                threadUnexpectedException(fail);
1433              }
1434          }
1435      }
# Line 1018 | Line 1440 | public class JSR166TestCase extends Test
1440          public final T call() {
1441              try {
1442                  return realCall();
1443 <            } catch (Throwable t) {
1444 <                threadUnexpectedException(t);
1443 >            } catch (Throwable fail) {
1444 >                threadUnexpectedException(fail);
1445                  return null;
1446              }
1447          }
# Line 1036 | Line 1458 | public class JSR166TestCase extends Test
1458                  return result;
1459              } catch (InterruptedException success) {
1460                  threadAssertFalse(Thread.interrupted());
1461 <            } catch (Throwable t) {
1462 <                threadUnexpectedException(t);
1461 >            } catch (Throwable fail) {
1462 >                threadUnexpectedException(fail);
1463              }
1464              return null;
1465          }
# Line 1054 | Line 1476 | public class JSR166TestCase extends Test
1476      public static final String TEST_STRING = "a test string";
1477  
1478      public static class StringTask implements Callable<String> {
1479 <        public String call() { return TEST_STRING; }
1479 >        final String value;
1480 >        public StringTask() { this(TEST_STRING); }
1481 >        public StringTask(String value) { this.value = value; }
1482 >        public String call() { return value; }
1483      }
1484  
1485      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1067 | Line 1492 | public class JSR166TestCase extends Test
1492              }};
1493      }
1494  
1495 <    public Runnable awaiter(final CountDownLatch latch) {
1495 >    public Runnable countDowner(final CountDownLatch latch) {
1496          return new CheckedRunnable() {
1497              public void realRun() throws InterruptedException {
1498 <                await(latch);
1498 >                latch.countDown();
1499              }};
1500      }
1501  
1502 <    public void await(CountDownLatch latch) {
1502 >    class LatchAwaiter extends CheckedRunnable {
1503 >        static final int NEW = 0;
1504 >        static final int RUNNING = 1;
1505 >        static final int DONE = 2;
1506 >        final CountDownLatch latch;
1507 >        int state = NEW;
1508 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1509 >        public void realRun() throws InterruptedException {
1510 >            state = 1;
1511 >            await(latch);
1512 >            state = 2;
1513 >        }
1514 >    }
1515 >
1516 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1517 >        return new LatchAwaiter(latch);
1518 >    }
1519 >
1520 >    public void await(CountDownLatch latch, long timeoutMillis) {
1521          try {
1522 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1523 <        } catch (Throwable t) {
1524 <            threadUnexpectedException(t);
1522 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1523 >                fail("timed out waiting for CountDownLatch for "
1524 >                     + (timeoutMillis/1000) + " sec");
1525 >        } catch (Throwable fail) {
1526 >            threadUnexpectedException(fail);
1527          }
1528      }
1529  
1530 +    public void await(CountDownLatch latch) {
1531 +        await(latch, LONG_DELAY_MS);
1532 +    }
1533 +
1534      public void await(Semaphore semaphore) {
1535          try {
1536 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1537 <        } catch (Throwable t) {
1538 <            threadUnexpectedException(t);
1536 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1537 >                fail("timed out waiting for Semaphore for "
1538 >                     + (LONG_DELAY_MS/1000) + " sec");
1539 >        } catch (Throwable fail) {
1540 >            threadUnexpectedException(fail);
1541          }
1542      }
1543  
# Line 1280 | Line 1731 | public class JSR166TestCase extends Test
1731          @Override protected final void compute() {
1732              try {
1733                  realCompute();
1734 <            } catch (Throwable t) {
1735 <                threadUnexpectedException(t);
1734 >            } catch (Throwable fail) {
1735 >                threadUnexpectedException(fail);
1736              }
1737          }
1738      }
# Line 1295 | Line 1746 | public class JSR166TestCase extends Test
1746          @Override protected final T compute() {
1747              try {
1748                  return realCompute();
1749 <            } catch (Throwable t) {
1750 <                threadUnexpectedException(t);
1749 >            } catch (Throwable fail) {
1750 >                threadUnexpectedException(fail);
1751                  return null;
1752              }
1753          }
# Line 1314 | Line 1765 | public class JSR166TestCase extends Test
1765       * A CyclicBarrier that uses timed await and fails with
1766       * AssertionFailedErrors instead of throwing checked exceptions.
1767       */
1768 <    public class CheckedBarrier extends CyclicBarrier {
1768 >    public static class CheckedBarrier extends CyclicBarrier {
1769          public CheckedBarrier(int parties) { super(parties); }
1770  
1771          public int await() {
1772              try {
1773                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1774 <            } catch (TimeoutException e) {
1774 >            } catch (TimeoutException timedOut) {
1775                  throw new AssertionFailedError("timed out");
1776 <            } catch (Exception e) {
1776 >            } catch (Exception fail) {
1777                  AssertionFailedError afe =
1778 <                    new AssertionFailedError("Unexpected exception: " + e);
1779 <                afe.initCause(e);
1778 >                    new AssertionFailedError("Unexpected exception: " + fail);
1779 >                afe.initCause(fail);
1780                  throw afe;
1781              }
1782          }
# Line 1353 | Line 1804 | public class JSR166TestCase extends Test
1804                  q.remove();
1805                  shouldThrow();
1806              } catch (NoSuchElementException success) {}
1807 <        } catch (InterruptedException ie) {
1357 <            threadUnexpectedException(ie);
1358 <        }
1807 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1808      }
1809  
1810      void assertSerialEquals(Object x, Object y) {
# Line 1374 | Line 1823 | public class JSR166TestCase extends Test
1823              oos.flush();
1824              oos.close();
1825              return bos.toByteArray();
1826 <        } catch (Throwable t) {
1827 <            threadUnexpectedException(t);
1826 >        } catch (Throwable fail) {
1827 >            threadUnexpectedException(fail);
1828              return new byte[0];
1829          }
1830      }
1831  
1832 +    void assertImmutable(final Object o) {
1833 +        if (o instanceof Collection) {
1834 +            assertThrows(
1835 +                UnsupportedOperationException.class,
1836 +                new Runnable() { public void run() {
1837 +                        ((Collection) o).add(null);}});
1838 +        }
1839 +    }
1840 +
1841      @SuppressWarnings("unchecked")
1842      <T> T serialClone(T o) {
1843          try {
1844              ObjectInputStream ois = new ObjectInputStream
1845                  (new ByteArrayInputStream(serialBytes(o)));
1846              T clone = (T) ois.readObject();
1847 +            if (o == clone) assertImmutable(o);
1848              assertSame(o.getClass(), clone.getClass());
1849              return clone;
1850 <        } catch (Throwable t) {
1851 <            threadUnexpectedException(t);
1850 >        } catch (Throwable fail) {
1851 >            threadUnexpectedException(fail);
1852 >            return null;
1853 >        }
1854 >    }
1855 >
1856 >    /**
1857 >     * A version of serialClone that leaves error handling (for
1858 >     * e.g. NotSerializableException) up to the caller.
1859 >     */
1860 >    @SuppressWarnings("unchecked")
1861 >    <T> T serialClonePossiblyFailing(T o)
1862 >        throws ReflectiveOperationException, java.io.IOException {
1863 >        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1864 >        ObjectOutputStream oos = new ObjectOutputStream(bos);
1865 >        oos.writeObject(o);
1866 >        oos.flush();
1867 >        oos.close();
1868 >        ObjectInputStream ois = new ObjectInputStream
1869 >            (new ByteArrayInputStream(bos.toByteArray()));
1870 >        T clone = (T) ois.readObject();
1871 >        if (o == clone) assertImmutable(o);
1872 >        assertSame(o.getClass(), clone.getClass());
1873 >        return clone;
1874 >    }
1875 >
1876 >    /**
1877 >     * If o implements Cloneable and has a public clone method,
1878 >     * returns a clone of o, else null.
1879 >     */
1880 >    @SuppressWarnings("unchecked")
1881 >    <T> T cloneableClone(T o) {
1882 >        if (!(o instanceof Cloneable)) return null;
1883 >        final T clone;
1884 >        try {
1885 >            clone = (T) o.getClass().getMethod("clone").invoke(o);
1886 >        } catch (NoSuchMethodException ok) {
1887              return null;
1888 +        } catch (ReflectiveOperationException unexpected) {
1889 +            throw new Error(unexpected);
1890          }
1891 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1892 +        assertSame(o.getClass(), clone.getClass());
1893 +        return clone;
1894      }
1895  
1896      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
# Line 1414 | Line 1913 | public class JSR166TestCase extends Test
1913                  shouldThrow(expectedExceptionClass.getName());
1914          }
1915      }
1916 +
1917 +    public void assertIteratorExhausted(Iterator<?> it) {
1918 +        try {
1919 +            it.next();
1920 +            shouldThrow();
1921 +        } catch (NoSuchElementException success) {}
1922 +        assertFalse(it.hasNext());
1923 +    }
1924 +
1925 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1926 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1927 +    }
1928 +
1929 +    public Runnable runnableThrowing(final RuntimeException ex) {
1930 +        return new Runnable() { public void run() { throw ex; }};
1931 +    }
1932 +
1933 +    /** A reusable thread pool to be shared by tests. */
1934 +    static final ExecutorService cachedThreadPool =
1935 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1936 +                               1000L, MILLISECONDS,
1937 +                               new SynchronousQueue<Runnable>());
1938 +
1939 +    static <T> void shuffle(T[] array) {
1940 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1941 +    }
1942   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines