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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines