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.139 by jsr166, Sun Sep 6 21:14:12 2015 UTC vs.
Revision 1.232 by jsr166, Mon May 29 19:15:02 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
8   */
9  
10 + /*
11 + * @test
12 + * @summary JSR-166 tck tests, in a number of variations.
13 + *          The first is the conformance testing variant,
14 + *          while others also test implementation details.
15 + * @build *
16 + * @modules java.management
17 + * @run junit/othervm/timeout=1000 JSR166TestCase
18 + * @run junit/othervm/timeout=1000
19 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 + *      --add-opens java.base/java.lang=ALL-UNNAMED
21 + *      -Djsr166.testImplementationDetails=true
22 + *      JSR166TestCase
23 + * @run junit/othervm/timeout=1000
24 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 + *      --add-opens java.base/java.lang=ALL-UNNAMED
26 + *      -Djsr166.testImplementationDetails=true
27 + *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28 + *      JSR166TestCase
29 + * @run junit/othervm/timeout=1000
30 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 + *      --add-opens java.base/java.lang=ALL-UNNAMED
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 + *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 + *      --add-opens java.base/java.lang=ALL-UNNAMED
39 + *      -Djsr166.testImplementationDetails=true
40 + *      JSR166TestCase
41 + */
42 +
43   import static java.util.concurrent.TimeUnit.MILLISECONDS;
44 + import static java.util.concurrent.TimeUnit.MINUTES;
45   import static java.util.concurrent.TimeUnit.NANOSECONDS;
46  
47   import java.io.ByteArrayInputStream;
# Line 15 | Line 50 | import java.io.ObjectInputStream;
50   import java.io.ObjectOutputStream;
51   import java.lang.management.ManagementFactory;
52   import java.lang.management.ThreadInfo;
53 + import java.lang.management.ThreadMXBean;
54   import java.lang.reflect.Constructor;
55   import java.lang.reflect.Method;
56   import java.lang.reflect.Modifier;
# Line 27 | Line 63 | 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;
# Line 40 | Line 78 | import java.util.concurrent.CyclicBarrie
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.TimeUnit;
92   import java.util.concurrent.TimeoutException;
93 + import java.util.concurrent.atomic.AtomicBoolean;
94   import java.util.concurrent.atomic.AtomicReference;
95   import java.util.regex.Pattern;
96  
# Line 67 | Line 110 | import junit.framework.TestSuite;
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 89 | Line 132 | import junit.framework.TestSuite;
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
110 < * 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 170 | Line 212 | public class JSR166TestCase extends Test
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  
# Line 185 | Line 265 | public class JSR166TestCase extends Test
265          return (regex == null) ? null : Pattern.compile(regex);
266      }
267  
268 <    protected void runTest() throws Throwable {
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 > //             java.util.regex.Matcher matcher
305 > //               = Pattern.compile("model name\\s*: (.*)")
306 > //                 .matcher(new String(
307 > //                     java.nio.file.Files.readAllBytes(
308 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
309 > //             matcher.find();
310 > //             return matcher.group(1);
311 > //         } catch (Exception ex) { return null; }
312 > //     }
313 >
314 >    public void runBare() throws Throwable {
315 >        currentTestCase = this;
316          if (methodFilter == null
317 <            || methodFilter.matcher(toString()).find()) {
318 <            for (int i = 0; i < runsPerTest; i++) {
319 <                if (profileTests)
320 <                    runTestProfiled();
321 <                else
322 <                    super.runTest();
323 <            }
317 >            || methodFilter.matcher(toString()).find())
318 >            super.runBare();
319 >    }
320 >
321 >    protected void runTest() throws Throwable {
322 >        for (int i = 0; i < runsPerTest; i++) {
323 >            // currentRun = i;
324 >            if (profileTests)
325 >                runTestProfiled();
326 >            else
327 >                super.runTest();
328          }
329      }
330  
331      protected void runTestProfiled() throws Throwable {
332 <        // Warmup run, notably to trigger all needed classloading.
333 <        super.runTest();
203 <        long t0 = System.nanoTime();
204 <        try {
332 >        for (int i = 0; i < 2; i++) {
333 >            long startTime = System.nanoTime();
334              super.runTest();
335 <        } finally {
336 <            long elapsedMillis = millisElapsedSince(t0);
337 <            if (elapsedMillis >= profileThreshold)
335 >            long elapsedMillis = millisElapsedSince(startTime);
336 >            if (elapsedMillis < profileThreshold)
337 >                break;
338 >            // Never report first run of any test; treat it as a
339 >            // warmup run, notably to trigger all needed classloading,
340 >            if (i > 0)
341                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
342          }
343      }
# Line 217 | Line 349 | public class JSR166TestCase extends Test
349          main(suite(), args);
350      }
351  
352 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
353 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
354 +        long runTime;
355 +        public void startTest(Test test) {}
356 +        protected void printHeader(long runTime) {
357 +            this.runTime = runTime; // defer printing for later
358 +        }
359 +        protected void printFooter(TestResult result) {
360 +            if (result.wasSuccessful()) {
361 +                getWriter().println("OK (" + result.runCount() + " tests)"
362 +                    + "  Time: " + elapsedTimeAsString(runTime));
363 +            } else {
364 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
365 +                super.printFooter(result);
366 +            }
367 +        }
368 +    }
369 +
370 +    /**
371 +     * Returns a TestRunner that doesn't bother with unnecessary
372 +     * fluff, like printing a "." for each test case.
373 +     */
374 +    static junit.textui.TestRunner newPithyTestRunner() {
375 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
376 +        runner.setPrinter(new PithyResultPrinter(System.out));
377 +        return runner;
378 +    }
379 +
380      /**
381       * Runs all unit tests in the given test suite.
382       * Actual behavior influenced by jsr166.* system properties.
# Line 228 | Line 388 | public class JSR166TestCase extends Test
388              System.setSecurityManager(new SecurityManager());
389          }
390          for (int i = 0; i < suiteRuns; i++) {
391 <            TestResult result = junit.textui.TestRunner.run(suite);
391 >            TestResult result = newPithyTestRunner().doRun(suite);
392              if (!result.wasSuccessful())
393                  System.exit(1);
394              System.gc();
# Line 312 | Line 472 | public class JSR166TestCase extends Test
472              AbstractQueuedLongSynchronizerTest.suite(),
473              ArrayBlockingQueueTest.suite(),
474              ArrayDequeTest.suite(),
475 +            ArrayListTest.suite(),
476              AtomicBooleanTest.suite(),
477              AtomicIntegerArrayTest.suite(),
478              AtomicIntegerFieldUpdaterTest.suite(),
# Line 334 | Line 495 | public class JSR166TestCase extends Test
495              CopyOnWriteArrayListTest.suite(),
496              CopyOnWriteArraySetTest.suite(),
497              CountDownLatchTest.suite(),
498 +            CountedCompleterTest.suite(),
499              CyclicBarrierTest.suite(),
500              DelayQueueTest.suite(),
501              EntryTest.suite(),
# Line 362 | Line 524 | public class JSR166TestCase extends Test
524              TreeMapTest.suite(),
525              TreeSetTest.suite(),
526              TreeSubMapTest.suite(),
527 <            TreeSubSetTest.suite());
527 >            TreeSubSetTest.suite(),
528 >            VectorTest.suite());
529  
530          // Java8+ test classes
531          if (atLeastJava8()) {
532              String[] java8TestClassNames = {
533 +                "ArrayDeque8Test",
534                  "Atomic8Test",
535                  "CompletableFutureTest",
536                  "ConcurrentHashMap8Test",
537 <                "CountedCompleterTest",
537 >                "CountedCompleter8Test",
538                  "DoubleAccumulatorTest",
539                  "DoubleAdderTest",
540                  "ForkJoinPool8Test",
541                  "ForkJoinTask8Test",
542 +                "LinkedBlockingDeque8Test",
543 +                "LinkedBlockingQueue8Test",
544                  "LongAccumulatorTest",
545                  "LongAdderTest",
546                  "SplittableRandomTest",
547                  "StampedLockTest",
548 +                "SubmissionPublisherTest",
549                  "ThreadLocalRandom8Test",
550 +                "TimeUnit8Test",
551              };
552              addNamedTestClasses(suite, java8TestClassNames);
553          }
# Line 387 | Line 555 | public class JSR166TestCase extends Test
555          // Java9+ test classes
556          if (atLeastJava9()) {
557              String[] java9TestClassNames = {
558 <                // Currently empty
558 >                "AtomicBoolean9Test",
559 >                "AtomicInteger9Test",
560 >                "AtomicIntegerArray9Test",
561 >                "AtomicLong9Test",
562 >                "AtomicLongArray9Test",
563 >                "AtomicReference9Test",
564 >                "AtomicReferenceArray9Test",
565 >                "ExecutorCompletionService9Test",
566 >                "ForkJoinPool9Test",
567              };
568              addNamedTestClasses(suite, java9TestClassNames);
569          }
# Line 398 | Line 574 | public class JSR166TestCase extends Test
574      /** Returns list of junit-style test method names in given class. */
575      public static ArrayList<String> testMethodNames(Class<?> testClass) {
576          Method[] methods = testClass.getDeclaredMethods();
577 <        ArrayList<String> names = new ArrayList<String>(methods.length);
577 >        ArrayList<String> names = new ArrayList<>(methods.length);
578          for (Method method : methods) {
579              if (method.getName().startsWith("test")
580                  && Modifier.isPublic(method.getModifiers())
# Line 454 | Line 630 | public class JSR166TestCase extends Test
630          } else {
631              return new TestSuite();
632          }
457
633      }
634  
635      // Delays for timing-dependent tests, in milliseconds.
# Line 464 | Line 639 | public class JSR166TestCase extends Test
639      public static long MEDIUM_DELAY_MS;
640      public static long LONG_DELAY_MS;
641  
642 +    private static final long RANDOM_TIMEOUT;
643 +    private static final long RANDOM_EXPIRED_TIMEOUT;
644 +    private static final TimeUnit RANDOM_TIMEUNIT;
645 +    static {
646 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
647 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
648 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
649 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
650 +        TimeUnit[] timeUnits = TimeUnit.values();
651 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
652 +    }
653 +
654 +    /**
655 +     * Returns a timeout for use when any value at all will do.
656 +     */
657 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
658 +
659 +    /**
660 +     * Returns a timeout that means "no waiting", i.e. not positive.
661 +     */
662 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
663 +
664 +    /**
665 +     * Returns a random non-null TimeUnit.
666 +     */
667 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
668 +
669      /**
670 <     * Returns the shortest timed delay. This could
671 <     * be reimplemented to use for example a Property.
670 >     * Returns the shortest timed delay. This can be scaled up for
671 >     * slow machines using the jsr166.delay.factor system property,
672 >     * or via jtreg's -timeoutFactor: flag.
673 >     * http://openjdk.java.net/jtreg/command-help.html
674       */
675      protected long getShortDelay() {
676 <        return 50;
676 >        return (long) (50 * delayFactor);
677      }
678  
679      /**
# Line 482 | Line 686 | public class JSR166TestCase extends Test
686          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
687      }
688  
689 +    private static final long TIMEOUT_DELAY_MS
690 +        = (long) (12.0 * Math.cbrt(delayFactor));
691 +
692      /**
693 <     * Returns a timeout in milliseconds to be used in tests that
694 <     * verify that operations block or time out.
693 >     * Returns a timeout in milliseconds to be used in tests that verify
694 >     * that operations block or time out.  We want this to be longer
695 >     * than the OS scheduling quantum, but not too long, so don't scale
696 >     * linearly with delayFactor; we use "crazy" cube root instead.
697       */
698 <    long timeoutMillis() {
699 <        return SHORT_DELAY_MS / 4;
698 >    static long timeoutMillis() {
699 >        return TIMEOUT_DELAY_MS;
700      }
701  
702      /**
# Line 503 | Line 712 | public class JSR166TestCase extends Test
712       * The first exception encountered if any threadAssertXXX method fails.
713       */
714      private final AtomicReference<Throwable> threadFailure
715 <        = new AtomicReference<Throwable>(null);
715 >        = new AtomicReference<>(null);
716  
717      /**
718       * Records an exception so that it can be rethrown later in the test
# Line 512 | Line 721 | public class JSR166TestCase extends Test
721       * the same test have no effect.
722       */
723      public void threadRecordFailure(Throwable t) {
724 +        System.err.println(t);
725 +        dumpTestThreads();
726          threadFailure.compareAndSet(null, t);
727      }
728  
# Line 519 | Line 730 | public class JSR166TestCase extends Test
730          setDelays();
731      }
732  
733 +    void tearDownFail(String format, Object... args) {
734 +        String msg = toString() + ": " + String.format(format, args);
735 +        System.err.println(msg);
736 +        dumpTestThreads();
737 +        throw new AssertionFailedError(msg);
738 +    }
739 +
740      /**
741       * Extra checks that get done for all test cases.
742       *
# Line 546 | Line 764 | public class JSR166TestCase extends Test
764          }
765  
766          if (Thread.interrupted())
767 <            throw new AssertionFailedError("interrupt status set in main thread");
767 >            tearDownFail("interrupt status set in main thread");
768  
769          checkForkJoinPoolThreadLeaks();
770      }
771  
772      /**
773 <     * Finds missing try { ... } finally { joinPool(e); }
773 >     * Finds missing PoolCleaners
774       */
775      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
776 <        Thread[] survivors = new Thread[5];
776 >        Thread[] survivors = new Thread[7];
777          int count = Thread.enumerate(survivors);
778          for (int i = 0; i < count; i++) {
779              Thread thread = survivors[i];
# Line 563 | Line 781 | public class JSR166TestCase extends Test
781              if (name.startsWith("ForkJoinPool-")) {
782                  // give thread some time to terminate
783                  thread.join(LONG_DELAY_MS);
784 <                if (!thread.isAlive()) continue;
785 <                throw new AssertionFailedError
786 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
569 <                                   toString(), name));
784 >                if (thread.isAlive())
785 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
786 >                                 thread);
787              }
788          }
789 +
790 +        if (!ForkJoinPool.commonPool()
791 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
792 +            tearDownFail("ForkJoin common pool thread stuck");
793      }
794  
795      /**
# Line 581 | Line 802 | public class JSR166TestCase extends Test
802              fail(reason);
803          } catch (AssertionFailedError t) {
804              threadRecordFailure(t);
805 <            fail(reason);
805 >            throw t;
806          }
807      }
808  
# Line 708 | Line 929 | public class JSR166TestCase extends Test
929      /**
930       * Delays, via Thread.sleep, for the given millisecond delay, but
931       * if the sleep is shorter than specified, may re-sleep or yield
932 <     * until time elapses.
932 >     * until time elapses.  Ensures that the given time, as measured
933 >     * by System.nanoTime(), has elapsed.
934       */
935      static void delay(long millis) throws InterruptedException {
936 <        long startTime = System.nanoTime();
937 <        long ns = millis * 1000 * 1000;
938 <        for (;;) {
936 >        long nanos = millis * (1000 * 1000);
937 >        final long wakeupTime = System.nanoTime() + nanos;
938 >        do {
939              if (millis > 0L)
940                  Thread.sleep(millis);
941              else // too short to sleep
942                  Thread.yield();
943 <            long d = ns - (System.nanoTime() - startTime);
944 <            if (d > 0L)
945 <                millis = d / (1000 * 1000);
946 <            else
947 <                break;
943 >            nanos = wakeupTime - System.nanoTime();
944 >            millis = nanos / (1000 * 1000);
945 >        } while (nanos >= 0L);
946 >    }
947 >
948 >    /**
949 >     * Allows use of try-with-resources with per-test thread pools.
950 >     */
951 >    class PoolCleaner implements AutoCloseable {
952 >        private final ExecutorService pool;
953 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
954 >        public void close() { joinPool(pool); }
955 >    }
956 >
957 >    /**
958 >     * An extension of PoolCleaner that has an action to release the pool.
959 >     */
960 >    class PoolCleanerWithReleaser extends PoolCleaner {
961 >        private final Runnable releaser;
962 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
963 >            super(pool);
964 >            this.releaser = releaser;
965 >        }
966 >        public void close() {
967 >            try {
968 >                releaser.run();
969 >            } finally {
970 >                super.close();
971 >            }
972          }
973      }
974  
975 +    PoolCleaner cleaner(ExecutorService pool) {
976 +        return new PoolCleaner(pool);
977 +    }
978 +
979 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
980 +        return new PoolCleanerWithReleaser(pool, releaser);
981 +    }
982 +
983 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
984 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
985 +    }
986 +
987 +    Runnable releaser(final CountDownLatch latch) {
988 +        return new Runnable() { public void run() {
989 +            do { latch.countDown(); }
990 +            while (latch.getCount() > 0);
991 +        }};
992 +    }
993 +
994 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
995 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
996 +    }
997 +
998 +    Runnable releaser(final AtomicBoolean flag) {
999 +        return new Runnable() { public void run() { flag.set(true); }};
1000 +    }
1001 +
1002      /**
1003       * Waits out termination of a thread pool or fails doing so.
1004       */
1005      void joinPool(ExecutorService pool) {
1006          try {
1007              pool.shutdown();
1008 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
1009 <                fail("ExecutorService " + pool +
1010 <                     " did not terminate in a timely manner");
1008 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1009 >                try {
1010 >                    threadFail("ExecutorService " + pool +
1011 >                               " did not terminate in a timely manner");
1012 >                } finally {
1013 >                    // last resort, for the benefit of subsequent tests
1014 >                    pool.shutdownNow();
1015 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1016 >                }
1017 >            }
1018          } catch (SecurityException ok) {
1019              // Allowed in case test doesn't have privs
1020          } catch (InterruptedException fail) {
1021 <            fail("Unexpected InterruptedException");
1021 >            threadFail("Unexpected InterruptedException");
1022          }
1023      }
1024  
1025 <    /** Like Runnable, but with the freedom to throw anything */
1026 <    interface Thunk { public void run() throws Throwable; }
1025 >    /**
1026 >     * Like Runnable, but with the freedom to throw anything.
1027 >     * junit folks had the same idea:
1028 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1029 >     */
1030 >    interface Action { public void run() throws Throwable; }
1031  
1032      /**
1033 <     * Runs all the given tasks in parallel, failing if any fail.
1033 >     * Runs all the given actions in parallel, failing if any fail.
1034       * Useful for running multiple variants of tests that are
1035       * necessarily individually slow because they must block.
1036       */
1037 <    void testInParallel(Thunk ... thunks) {
1037 >    void testInParallel(Action ... actions) {
1038          ExecutorService pool = Executors.newCachedThreadPool();
1039 <        try {
1040 <            ArrayList<Future<?>> futures = new ArrayList<>(thunks.length);
1041 <            for (final Thunk thunk : thunks)
1039 >        try (PoolCleaner cleaner = cleaner(pool)) {
1040 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1041 >            for (final Action action : actions)
1042                  futures.add(pool.submit(new CheckedRunnable() {
1043 <                    public void realRun() throws Throwable { thunk.run();}}));
1043 >                    public void realRun() throws Throwable { action.run();}}));
1044              for (Future<?> future : futures)
1045                  try {
1046                      assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
# Line 765 | Line 1049 | public class JSR166TestCase extends Test
1049                  } catch (Exception ex) {
1050                      threadUnexpectedException(ex);
1051                  }
768        } finally {
769            joinPool(pool);
1052          }
1053      }
1054  
1055      /**
1056 <     * A debugging tool to print all stack traces, as jstack does.
1056 >     * A debugging tool to print stack traces of most threads, as jstack does.
1057 >     * Uninteresting threads are filtered out.
1058       */
1059 <    static void printAllStackTraces() {
1060 <        for (ThreadInfo info :
1061 <                 ManagementFactory.getThreadMXBean()
1062 <                 .dumpAllThreads(true, true))
1059 >    static void dumpTestThreads() {
1060 >        SecurityManager sm = System.getSecurityManager();
1061 >        if (sm != null) {
1062 >            try {
1063 >                System.setSecurityManager(null);
1064 >            } catch (SecurityException giveUp) {
1065 >                return;
1066 >            }
1067 >        }
1068 >
1069 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1070 >        System.err.println("------ stacktrace dump start ------");
1071 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1072 >            final String name = info.getThreadName();
1073 >            String lockName;
1074 >            if ("Signal Dispatcher".equals(name))
1075 >                continue;
1076 >            if ("Reference Handler".equals(name)
1077 >                && (lockName = info.getLockName()) != null
1078 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1079 >                continue;
1080 >            if ("Finalizer".equals(name)
1081 >                && (lockName = info.getLockName()) != null
1082 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1083 >                continue;
1084 >            if ("checkForWedgedTest".equals(name))
1085 >                continue;
1086              System.err.print(info);
1087 +        }
1088 +        System.err.println("------ stacktrace dump end ------");
1089 +
1090 +        if (sm != null) System.setSecurityManager(sm);
1091 +    }
1092 +
1093 +    /**
1094 +     * Checks that thread eventually enters the expected blocked thread state.
1095 +     */
1096 +    void assertThreadBlocks(Thread thread, Thread.State expected) {
1097 +        // always sleep at least 1 ms, with high probability avoiding
1098 +        // transitory states
1099 +        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1100 +            try { delay(1); }
1101 +            catch (InterruptedException fail) {
1102 +                fail("Unexpected InterruptedException");
1103 +            }
1104 +            Thread.State s = thread.getState();
1105 +            if (s == expected)
1106 +                return;
1107 +            else if (s == Thread.State.TERMINATED)
1108 +                fail("Unexpected thread termination");
1109 +        }
1110 +        fail("timed out waiting for thread to enter thread state " + expected);
1111      }
1112  
1113      /**
1114       * Checks that thread does not terminate within the default
1115       * millisecond delay of {@code timeoutMillis()}.
1116 +     * TODO: REMOVEME
1117       */
1118      void assertThreadStaysAlive(Thread thread) {
1119          assertThreadStaysAlive(thread, timeoutMillis());
# Line 790 | Line 1121 | public class JSR166TestCase extends Test
1121  
1122      /**
1123       * Checks that thread does not terminate within the given millisecond delay.
1124 +     * TODO: REMOVEME
1125       */
1126      void assertThreadStaysAlive(Thread thread, long millis) {
1127          try {
# Line 797 | Line 1129 | public class JSR166TestCase extends Test
1129              delay(millis);
1130              assertTrue(thread.isAlive());
1131          } catch (InterruptedException fail) {
1132 <            fail("Unexpected InterruptedException");
1132 >            threadFail("Unexpected InterruptedException");
1133          }
1134      }
1135  
1136      /**
1137       * Checks that the threads do not terminate within the default
1138       * millisecond delay of {@code timeoutMillis()}.
1139 +     * TODO: REMOVEME
1140       */
1141      void assertThreadsStayAlive(Thread... threads) {
1142          assertThreadsStayAlive(timeoutMillis(), threads);
# Line 811 | Line 1144 | public class JSR166TestCase extends Test
1144  
1145      /**
1146       * Checks that the threads do not terminate within the given millisecond delay.
1147 +     * TODO: REMOVEME
1148       */
1149      void assertThreadsStayAlive(long millis, Thread... threads) {
1150          try {
# Line 819 | Line 1153 | public class JSR166TestCase extends Test
1153              for (Thread thread : threads)
1154                  assertTrue(thread.isAlive());
1155          } catch (InterruptedException fail) {
1156 <            fail("Unexpected InterruptedException");
1156 >            threadFail("Unexpected InterruptedException");
1157          }
1158      }
1159  
# Line 861 | Line 1195 | public class JSR166TestCase extends Test
1195      }
1196  
1197      /**
1198 +     * The maximum number of consecutive spurious wakeups we should
1199 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1200 +     */
1201 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1202 +
1203 +    /**
1204       * The number of elements to place in collections, arrays, etc.
1205       */
1206      public static final int SIZE = 20;
# Line 964 | Line 1304 | public class JSR166TestCase extends Test
1304          }
1305          public void refresh() {}
1306          public String toString() {
1307 <            List<Permission> ps = new ArrayList<Permission>();
1307 >            List<Permission> ps = new ArrayList<>();
1308              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1309                  ps.add(e.nextElement());
1310              return "AdjustablePolicy with permissions " + ps;
# Line 994 | Line 1334 | public class JSR166TestCase extends Test
1334       * Sleeps until the given time has elapsed.
1335       * Throws AssertionFailedError if interrupted.
1336       */
1337 <    void sleep(long millis) {
1337 >    static void sleep(long millis) {
1338          try {
1339              delay(millis);
1340          } catch (InterruptedException fail) {
# Line 1010 | Line 1350 | public class JSR166TestCase extends Test
1350       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1351       */
1352      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1353 <        long startTime = System.nanoTime();
1353 >        long startTime = 0L;
1354          for (;;) {
1355              Thread.State s = thread.getState();
1356              if (s == Thread.State.BLOCKED ||
# Line 1019 | Line 1359 | public class JSR166TestCase extends Test
1359                  return;
1360              else if (s == Thread.State.TERMINATED)
1361                  fail("Unexpected thread termination");
1362 +            else if (startTime == 0L)
1363 +                startTime = System.nanoTime();
1364              else if (millisElapsedSince(startTime) > timeoutMillis) {
1365                  threadAssertTrue(thread.isAlive());
1366 <                return;
1366 >                fail("timed out waiting for thread to enter wait state");
1367 >            }
1368 >            Thread.yield();
1369 >        }
1370 >    }
1371 >
1372 >    /**
1373 >     * Spin-waits up to the specified number of milliseconds for the given
1374 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1375 >     * and additionally satisfy the given condition.
1376 >     */
1377 >    void waitForThreadToEnterWaitState(
1378 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1379 >        long startTime = 0L;
1380 >        for (;;) {
1381 >            Thread.State s = thread.getState();
1382 >            if (s == Thread.State.BLOCKED ||
1383 >                s == Thread.State.WAITING ||
1384 >                s == Thread.State.TIMED_WAITING) {
1385 >                try {
1386 >                    if (waitingForGodot.call())
1387 >                        return;
1388 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1389 >            }
1390 >            else if (s == Thread.State.TERMINATED)
1391 >                fail("Unexpected thread termination");
1392 >            else if (startTime == 0L)
1393 >                startTime = System.nanoTime();
1394 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1395 >                threadAssertTrue(thread.isAlive());
1396 >                fail("timed out waiting for thread to enter wait state");
1397              }
1398              Thread.yield();
1399          }
1400      }
1401  
1402      /**
1403 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1404 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1403 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1404 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1405       */
1406      void waitForThreadToEnterWaitState(Thread thread) {
1407          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1408      }
1409  
1410      /**
1411 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1412 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1413 +     * and additionally satisfy the given condition.
1414 +     */
1415 +    void waitForThreadToEnterWaitState(
1416 +        Thread thread, Callable<Boolean> waitingForGodot) {
1417 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1418 +    }
1419 +
1420 +    /**
1421       * Returns the number of milliseconds since time given by
1422       * startNanoTime, which must have been previously returned from a
1423       * call to {@link System#nanoTime()}.
# Line 1097 | Line 1479 | public class JSR166TestCase extends Test
1479          } finally {
1480              if (t.getState() != Thread.State.TERMINATED) {
1481                  t.interrupt();
1482 <                fail("Test timed out");
1482 >                threadFail("timed out waiting for thread to terminate");
1483              }
1484          }
1485      }
# Line 1222 | Line 1604 | public class JSR166TestCase extends Test
1604      public static final String TEST_STRING = "a test string";
1605  
1606      public static class StringTask implements Callable<String> {
1607 <        public String call() { return TEST_STRING; }
1607 >        final String value;
1608 >        public StringTask() { this(TEST_STRING); }
1609 >        public StringTask(String value) { this.value = value; }
1610 >        public String call() { return value; }
1611      }
1612  
1613      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1235 | Line 1620 | public class JSR166TestCase extends Test
1620              }};
1621      }
1622  
1623 <    public Runnable awaiter(final CountDownLatch latch) {
1623 >    public Runnable countDowner(final CountDownLatch latch) {
1624          return new CheckedRunnable() {
1625              public void realRun() throws InterruptedException {
1626 <                await(latch);
1626 >                latch.countDown();
1627              }};
1628      }
1629  
1630 <    public void await(CountDownLatch latch) {
1630 >    class LatchAwaiter extends CheckedRunnable {
1631 >        static final int NEW = 0;
1632 >        static final int RUNNING = 1;
1633 >        static final int DONE = 2;
1634 >        final CountDownLatch latch;
1635 >        int state = NEW;
1636 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1637 >        public void realRun() throws InterruptedException {
1638 >            state = 1;
1639 >            await(latch);
1640 >            state = 2;
1641 >        }
1642 >    }
1643 >
1644 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1645 >        return new LatchAwaiter(latch);
1646 >    }
1647 >
1648 >    public void await(CountDownLatch latch, long timeoutMillis) {
1649          try {
1650 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1650 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1651 >                fail("timed out waiting for CountDownLatch for "
1652 >                     + (timeoutMillis/1000) + " sec");
1653          } catch (Throwable fail) {
1654              threadUnexpectedException(fail);
1655          }
1656      }
1657  
1658 +    public void await(CountDownLatch latch) {
1659 +        await(latch, LONG_DELAY_MS);
1660 +    }
1661 +
1662      public void await(Semaphore semaphore) {
1663          try {
1664 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1664 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1665 >                fail("timed out waiting for Semaphore for "
1666 >                     + (LONG_DELAY_MS/1000) + " sec");
1667 >        } catch (Throwable fail) {
1668 >            threadUnexpectedException(fail);
1669 >        }
1670 >    }
1671 >
1672 >    public void await(CyclicBarrier barrier) {
1673 >        try {
1674 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1675          } catch (Throwable fail) {
1676              threadUnexpectedException(fail);
1677          }
# Line 1281 | Line 1700 | public class JSR166TestCase extends Test
1700          public String call() { throw new NullPointerException(); }
1701      }
1702  
1284    public static class CallableOne implements Callable<Integer> {
1285        public Integer call() { return one; }
1286    }
1287
1288    public class ShortRunnable extends CheckedRunnable {
1289        protected void realRun() throws Throwable {
1290            delay(SHORT_DELAY_MS);
1291        }
1292    }
1293
1294    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1295        protected void realRun() throws InterruptedException {
1296            delay(SHORT_DELAY_MS);
1297        }
1298    }
1299
1300    public class SmallRunnable extends CheckedRunnable {
1301        protected void realRun() throws Throwable {
1302            delay(SMALL_DELAY_MS);
1303        }
1304    }
1305
1703      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1704          protected void realRun() {
1705              try {
# Line 1311 | Line 1708 | public class JSR166TestCase extends Test
1708          }
1709      }
1710  
1314    public class SmallCallable extends CheckedCallable {
1315        protected Object realCall() throws InterruptedException {
1316            delay(SMALL_DELAY_MS);
1317            return Boolean.TRUE;
1318        }
1319    }
1320
1321    public class MediumRunnable extends CheckedRunnable {
1322        protected void realRun() throws Throwable {
1323            delay(MEDIUM_DELAY_MS);
1324        }
1325    }
1326
1327    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1328        protected void realRun() throws InterruptedException {
1329            delay(MEDIUM_DELAY_MS);
1330        }
1331    }
1332
1711      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1712          return new CheckedRunnable() {
1713              protected void realRun() {
# Line 1339 | Line 1717 | public class JSR166TestCase extends Test
1717              }};
1718      }
1719  
1342    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1343        protected void realRun() {
1344            try {
1345                delay(MEDIUM_DELAY_MS);
1346            } catch (InterruptedException ok) {}
1347        }
1348    }
1349
1350    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1351        protected void realRun() {
1352            try {
1353                delay(LONG_DELAY_MS);
1354            } catch (InterruptedException ok) {}
1355        }
1356    }
1357
1720      /**
1721       * For use as ThreadFactory in constructors
1722       */
# Line 1368 | Line 1730 | public class JSR166TestCase extends Test
1730          boolean isDone();
1731      }
1732  
1371    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1372        return new TrackedRunnable() {
1373                private volatile boolean done = false;
1374                public boolean isDone() { return done; }
1375                public void run() {
1376                    try {
1377                        delay(timeoutMillis);
1378                        done = true;
1379                    } catch (InterruptedException ok) {}
1380                }
1381            };
1382    }
1383
1384    public static class TrackedShortRunnable implements Runnable {
1385        public volatile boolean done = false;
1386        public void run() {
1387            try {
1388                delay(SHORT_DELAY_MS);
1389                done = true;
1390            } catch (InterruptedException ok) {}
1391        }
1392    }
1393
1394    public static class TrackedSmallRunnable implements Runnable {
1395        public volatile boolean done = false;
1396        public void run() {
1397            try {
1398                delay(SMALL_DELAY_MS);
1399                done = true;
1400            } catch (InterruptedException ok) {}
1401        }
1402    }
1403
1404    public static class TrackedMediumRunnable implements Runnable {
1405        public volatile boolean done = false;
1406        public void run() {
1407            try {
1408                delay(MEDIUM_DELAY_MS);
1409                done = true;
1410            } catch (InterruptedException ok) {}
1411        }
1412    }
1413
1414    public static class TrackedLongRunnable implements Runnable {
1415        public volatile boolean done = false;
1416        public void run() {
1417            try {
1418                delay(LONG_DELAY_MS);
1419                done = true;
1420            } catch (InterruptedException ok) {}
1421        }
1422    }
1423
1733      public static class TrackedNoOpRunnable implements Runnable {
1734          public volatile boolean done = false;
1735          public void run() {
# Line 1428 | Line 1737 | public class JSR166TestCase extends Test
1737          }
1738      }
1739  
1431    public static class TrackedCallable implements Callable {
1432        public volatile boolean done = false;
1433        public Object call() {
1434            try {
1435                delay(SMALL_DELAY_MS);
1436                done = true;
1437            } catch (InterruptedException ok) {}
1438            return Boolean.TRUE;
1439        }
1440    }
1441
1740      /**
1741       * Analog of CheckedRunnable for RecursiveAction
1742       */
# Line 1482 | Line 1780 | public class JSR166TestCase extends Test
1780       * A CyclicBarrier that uses timed await and fails with
1781       * AssertionFailedErrors instead of throwing checked exceptions.
1782       */
1783 <    public class CheckedBarrier extends CyclicBarrier {
1783 >    public static class CheckedBarrier extends CyclicBarrier {
1784          public CheckedBarrier(int parties) { super(parties); }
1785  
1786          public int await() {
# Line 1505 | Line 1803 | public class JSR166TestCase extends Test
1803              assertEquals(0, q.size());
1804              assertNull(q.peek());
1805              assertNull(q.poll());
1806 <            assertNull(q.poll(0, MILLISECONDS));
1806 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1807              assertEquals(q.toString(), "[]");
1808              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1809              assertFalse(q.iterator().hasNext());
# Line 1546 | Line 1844 | public class JSR166TestCase extends Test
1844          }
1845      }
1846  
1847 +    void assertImmutable(final Object o) {
1848 +        if (o instanceof Collection) {
1849 +            assertThrows(
1850 +                UnsupportedOperationException.class,
1851 +                new Runnable() { public void run() {
1852 +                        ((Collection) o).add(null);}});
1853 +        }
1854 +    }
1855 +
1856      @SuppressWarnings("unchecked")
1857      <T> T serialClone(T o) {
1858          try {
1859              ObjectInputStream ois = new ObjectInputStream
1860                  (new ByteArrayInputStream(serialBytes(o)));
1861              T clone = (T) ois.readObject();
1862 +            if (o == clone) assertImmutable(o);
1863              assertSame(o.getClass(), clone.getClass());
1864              return clone;
1865          } catch (Throwable fail) {
# Line 1560 | Line 1868 | public class JSR166TestCase extends Test
1868          }
1869      }
1870  
1871 +    /**
1872 +     * A version of serialClone that leaves error handling (for
1873 +     * e.g. NotSerializableException) up to the caller.
1874 +     */
1875 +    @SuppressWarnings("unchecked")
1876 +    <T> T serialClonePossiblyFailing(T o)
1877 +        throws ReflectiveOperationException, java.io.IOException {
1878 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1879 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1880 +        oos.writeObject(o);
1881 +        oos.flush();
1882 +        oos.close();
1883 +        ObjectInputStream ois = new ObjectInputStream
1884 +            (new ByteArrayInputStream(bos.toByteArray()));
1885 +        T clone = (T) ois.readObject();
1886 +        if (o == clone) assertImmutable(o);
1887 +        assertSame(o.getClass(), clone.getClass());
1888 +        return clone;
1889 +    }
1890 +
1891 +    /**
1892 +     * If o implements Cloneable and has a public clone method,
1893 +     * returns a clone of o, else null.
1894 +     */
1895 +    @SuppressWarnings("unchecked")
1896 +    <T> T cloneableClone(T o) {
1897 +        if (!(o instanceof Cloneable)) return null;
1898 +        final T clone;
1899 +        try {
1900 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1901 +        } catch (NoSuchMethodException ok) {
1902 +            return null;
1903 +        } catch (ReflectiveOperationException unexpected) {
1904 +            throw new Error(unexpected);
1905 +        }
1906 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1907 +        assertSame(o.getClass(), clone.getClass());
1908 +        return clone;
1909 +    }
1910 +
1911      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1912                               Runnable... throwingActions) {
1913          for (Runnable throwingAction : throwingActions) {
# Line 1588 | Line 1936 | public class JSR166TestCase extends Test
1936          } catch (NoSuchElementException success) {}
1937          assertFalse(it.hasNext());
1938      }
1939 +
1940 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1941 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1942 +    }
1943 +
1944 +    public Runnable runnableThrowing(final RuntimeException ex) {
1945 +        return new Runnable() { public void run() { throw ex; }};
1946 +    }
1947 +
1948 +    /** A reusable thread pool to be shared by tests. */
1949 +    static final ExecutorService cachedThreadPool =
1950 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1951 +                               1000L, MILLISECONDS,
1952 +                               new SynchronousQueue<Runnable>());
1953 +
1954 +    static <T> void shuffle(T[] array) {
1955 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1956 +    }
1957   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines