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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines