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.112 by jsr166, Fri Aug 16 07:07:01 2013 UTC vs.
Revision 1.217 by jsr166, Tue Jan 24 22:57:02 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines