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.86 by jsr166, Mon May 30 22:42:22 2011 UTC vs.
Revision 1.213 by jsr166, Fri Dec 9 06:58:57 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > /*
10 > * @test
11 > * @summary JSR-166 tck tests (conformance testing mode)
12 > * @build *
13 > * @modules java.management
14 > * @run junit/othervm/timeout=1000 JSR166TestCase
15 > */
16 >
17 > /*
18 > * @test
19 > * @summary JSR-166 tck tests (whitebox tests allowed)
20 > * @build *
21 > * @modules java.base/java.util.concurrent:open
22 > *          java.management
23 > * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
24 > * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 JSR166TestCase
25 > */
26 >
27 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
28 > import static java.util.concurrent.TimeUnit.MINUTES;
29 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
30 >
31   import java.io.ByteArrayInputStream;
32   import java.io.ByteArrayOutputStream;
33   import java.io.ObjectInputStream;
34   import java.io.ObjectOutputStream;
35 < import java.util.Arrays;
36 < import java.util.Date;
37 < import java.util.NoSuchElementException;
38 < import java.util.PropertyPermission;
39 < import java.util.concurrent.*;
40 < import java.util.concurrent.atomic.AtomicBoolean;
41 < import java.util.concurrent.atomic.AtomicReference;
42 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
35 > import java.lang.management.ManagementFactory;
36 > import java.lang.management.ThreadInfo;
37 > import java.lang.management.ThreadMXBean;
38 > import java.lang.reflect.Constructor;
39 > import java.lang.reflect.Method;
40 > import java.lang.reflect.Modifier;
41 > import java.nio.file.Files;
42 > import java.nio.file.Paths;
43   import java.security.CodeSource;
44   import java.security.Permission;
45   import java.security.PermissionCollection;
# Line 27 | Line 47 | import java.security.Permissions;
47   import java.security.Policy;
48   import java.security.ProtectionDomain;
49   import java.security.SecurityPermission;
50 + import java.util.ArrayList;
51 + import java.util.Arrays;
52 + import java.util.Collection;
53 + import java.util.Collections;
54 + import java.util.Date;
55 + import java.util.Enumeration;
56 + import java.util.Iterator;
57 + import java.util.List;
58 + import java.util.NoSuchElementException;
59 + import java.util.PropertyPermission;
60 + import java.util.concurrent.BlockingQueue;
61 + import java.util.concurrent.Callable;
62 + import java.util.concurrent.CountDownLatch;
63 + import java.util.concurrent.CyclicBarrier;
64 + import java.util.concurrent.ExecutionException;
65 + import java.util.concurrent.Executors;
66 + import java.util.concurrent.ExecutorService;
67 + import java.util.concurrent.ForkJoinPool;
68 + import java.util.concurrent.Future;
69 + import java.util.concurrent.RecursiveAction;
70 + import java.util.concurrent.RecursiveTask;
71 + import java.util.concurrent.RejectedExecutionHandler;
72 + import java.util.concurrent.Semaphore;
73 + import java.util.concurrent.SynchronousQueue;
74 + import java.util.concurrent.ThreadFactory;
75 + import java.util.concurrent.ThreadLocalRandom;
76 + import java.util.concurrent.ThreadPoolExecutor;
77 + import java.util.concurrent.TimeoutException;
78 + import java.util.concurrent.atomic.AtomicBoolean;
79 + import java.util.concurrent.atomic.AtomicReference;
80 + import java.util.regex.Matcher;
81 + import java.util.regex.Pattern;
82 +
83 + import junit.framework.AssertionFailedError;
84 + import junit.framework.Test;
85 + import junit.framework.TestCase;
86 + import junit.framework.TestResult;
87 + import junit.framework.TestSuite;
88  
89   /**
90   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 38 | Line 96 | import java.security.SecurityPermission;
96   *
97   * <ol>
98   *
99 < * <li> All assertions in code running in generated threads must use
99 > * <li>All assertions in code running in generated threads must use
100   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
101   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
102   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
103   * particularly recommended) for other code to use these forms too.
104   * Only the most typically used JUnit assertion methods are defined
105 < * this way, but enough to live with.</li>
105 > * this way, but enough to live with.
106   *
107 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
107 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
108   * to invoke {@code super.setUp} and {@code super.tearDown} within
109   * them. These methods are used to clear and check for thread
110 < * assertion failures.</li>
110 > * assertion failures.
111   *
112   * <li>All delays and timeouts must use one of the constants {@code
113   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 60 | Line 118 | import java.security.SecurityPermission;
118   * is always discriminable as larger than SHORT and smaller than
119   * MEDIUM.  And so on. These constants are set to conservative values,
120   * but even so, if there is ever any doubt, they can all be increased
121 < * in one spot to rerun tests on slower platforms.</li>
121 > * in one spot to rerun tests on slower platforms.
122   *
123 < * <li> All threads generated must be joined inside each test case
123 > * <li>All threads generated must be joined inside each test case
124   * method (or {@code fail} to do so) before returning from the
125   * method. The {@code joinPool} method can be used to do this when
126 < * using Executors.</li>
126 > * using Executors.
127   *
128   * </ol>
129   *
130 < * <p> <b>Other notes</b>
130 > * <p><b>Other notes</b>
131   * <ul>
132   *
133 < * <li> Usually, there is one testcase method per JSR166 method
133 > * <li>Usually, there is one testcase method per JSR166 method
134   * covering "normal" operation, and then as many exception-testing
135   * methods as there are exceptions the method can throw. Sometimes
136   * there are multiple tests per JSR166 method when the different
137   * "normal" behaviors differ significantly. And sometimes testcases
138 < * cover multiple methods when they cannot be tested in
81 < * isolation.</li>
138 > * cover multiple methods when they cannot be tested in isolation.
139   *
140 < * <li> The documentation style for testcases is to provide as javadoc
140 > * <li>The documentation style for testcases is to provide as javadoc
141   * a simple sentence or two describing the property that the testcase
142   * method purports to test. The javadocs do not say anything about how
143 < * the property is tested. To find out, read the code.</li>
143 > * the property is tested. To find out, read the code.
144   *
145 < * <li> These tests are "conformance tests", and do not attempt to
145 > * <li>These tests are "conformance tests", and do not attempt to
146   * test throughput, latency, scalability or other performance factors
147   * (see the separate "jtreg" tests for a set intended to check these
148   * for the most central aspects of functionality.) So, most tests use
149   * the smallest sensible numbers of threads, collection sizes, etc
150 < * needed to check basic conformance.</li>
150 > * needed to check basic conformance.
151   *
152   * <li>The test classes currently do not declare inclusion in
153   * any particular package to simplify things for people integrating
154 < * them in TCK test suites.</li>
154 > * them in TCK test suites.
155   *
156 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
157 < * runs all JSR166 unit tests.</li>
156 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
157 > * runs all JSR166 unit tests.
158   *
159   * </ul>
160   */
# Line 109 | Line 166 | public class JSR166TestCase extends Test
166          Boolean.getBoolean("jsr166.expensiveTests");
167  
168      /**
169 +     * If true, also run tests that are not part of the official tck
170 +     * because they test unspecified implementation details.
171 +     */
172 +    protected static final boolean testImplementationDetails =
173 +        Boolean.getBoolean("jsr166.testImplementationDetails");
174 +
175 +    /**
176       * If true, report on stdout all "slow" tests, that is, ones that
177       * take more than profileThreshold milliseconds to execute.
178       */
# Line 122 | Line 186 | public class JSR166TestCase extends Test
186      private static final long profileThreshold =
187          Long.getLong("jsr166.profileThreshold", 100);
188  
189 +    /**
190 +     * The number of repetitions per test (for tickling rare bugs).
191 +     */
192 +    private static final int runsPerTest =
193 +        Integer.getInteger("jsr166.runsPerTest", 1);
194 +
195 +    /**
196 +     * The number of repetitions of the test suite (for finding leaks?).
197 +     */
198 +    private static final int suiteRuns =
199 +        Integer.getInteger("jsr166.suiteRuns", 1);
200 +
201 +    /**
202 +     * Returns the value of the system property, or NaN if not defined.
203 +     */
204 +    private static float systemPropertyValue(String name) {
205 +        String floatString = System.getProperty(name);
206 +        if (floatString == null)
207 +            return Float.NaN;
208 +        try {
209 +            return Float.parseFloat(floatString);
210 +        } catch (NumberFormatException ex) {
211 +            throw new IllegalArgumentException(
212 +                String.format("Bad float value in system property %s=%s",
213 +                              name, floatString));
214 +        }
215 +    }
216 +
217 +    /**
218 +     * The scaling factor to apply to standard delays used in tests.
219 +     * May be initialized from any of:
220 +     * - the "jsr166.delay.factor" system property
221 +     * - the "test.timeout.factor" system property (as used by jtreg)
222 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
223 +     * - hard-coded fuzz factor when using a known slowpoke VM
224 +     */
225 +    private static final float delayFactor = delayFactor();
226 +
227 +    private static float delayFactor() {
228 +        float x;
229 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
230 +            return x;
231 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
232 +            return x;
233 +        String prop = System.getProperty("java.vm.version");
234 +        if (prop != null && prop.matches(".*debug.*"))
235 +            return 4.0f; // How much slower is fastdebug than product?!
236 +        return 1.0f;
237 +    }
238 +
239 +    public JSR166TestCase() { super(); }
240 +    public JSR166TestCase(String name) { super(name); }
241 +
242 +    /**
243 +     * A filter for tests to run, matching strings of the form
244 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
245 +     * Usefully combined with jsr166.runsPerTest.
246 +     */
247 +    private static final Pattern methodFilter = methodFilter();
248 +
249 +    private static Pattern methodFilter() {
250 +        String regex = System.getProperty("jsr166.methodFilter");
251 +        return (regex == null) ? null : Pattern.compile(regex);
252 +    }
253 +
254 +    // Instrumentation to debug very rare, but very annoying hung test runs.
255 +    static volatile TestCase currentTestCase;
256 +    // static volatile int currentRun = 0;
257 +    static {
258 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
259 +            // Avoid spurious reports with enormous runsPerTest.
260 +            // A single test case run should never take more than 1 second.
261 +            // But let's cap it at the high end too ...
262 +            final int timeoutMinutes =
263 +                Math.min(15, Math.max(runsPerTest / 60, 1));
264 +            for (TestCase lastTestCase = currentTestCase;;) {
265 +                try { MINUTES.sleep(timeoutMinutes); }
266 +                catch (InterruptedException unexpected) { break; }
267 +                if (lastTestCase == currentTestCase) {
268 +                    System.err.printf(
269 +                        "Looks like we're stuck running test: %s%n",
270 +                        lastTestCase);
271 + //                     System.err.printf(
272 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
273 + //                         lastTestCase, currentRun, runsPerTest);
274 + //                     System.err.println("availableProcessors=" +
275 + //                         Runtime.getRuntime().availableProcessors());
276 + //                     System.err.printf("cpu model = %s%n", cpuModel());
277 +                    dumpTestThreads();
278 +                    // one stack dump is probably enough; more would be spam
279 +                    break;
280 +                }
281 +                lastTestCase = currentTestCase;
282 +            }}};
283 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
284 +        thread.setDaemon(true);
285 +        thread.start();
286 +    }
287 +
288 + //     public static String cpuModel() {
289 + //         try {
290 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
291 + //                 .matcher(new String(
292 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
293 + //             matcher.find();
294 + //             return matcher.group(1);
295 + //         } catch (Exception ex) { return null; }
296 + //     }
297 +
298 +    public void runBare() throws Throwable {
299 +        currentTestCase = this;
300 +        if (methodFilter == null
301 +            || methodFilter.matcher(toString()).find())
302 +            super.runBare();
303 +    }
304 +
305      protected void runTest() throws Throwable {
306 <        if (profileTests)
307 <            runTestProfiled();
308 <        else
309 <            super.runTest();
306 >        for (int i = 0; i < runsPerTest; i++) {
307 >            // currentRun = i;
308 >            if (profileTests)
309 >                runTestProfiled();
310 >            else
311 >                super.runTest();
312 >        }
313      }
314  
315      protected void runTestProfiled() throws Throwable {
316 <        long t0 = System.nanoTime();
317 <        try {
316 >        for (int i = 0; i < 2; i++) {
317 >            long startTime = System.nanoTime();
318              super.runTest();
319 <        } finally {
320 <            long elapsedMillis =
321 <                (System.nanoTime() - t0) / (1000L * 1000L);
322 <            if (elapsedMillis >= profileThreshold)
319 >            long elapsedMillis = millisElapsedSince(startTime);
320 >            if (elapsedMillis < profileThreshold)
321 >                break;
322 >            // Never report first run of any test; treat it as a
323 >            // warmup run, notably to trigger all needed classloading,
324 >            if (i > 0)
325                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
326          }
327      }
328  
329      /**
330 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
330 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
331       */
332      public static void main(String[] args) {
333 +        main(suite(), args);
334 +    }
335 +
336 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
337 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
338 +        long runTime;
339 +        public void startTest(Test test) {}
340 +        protected void printHeader(long runTime) {
341 +            this.runTime = runTime; // defer printing for later
342 +        }
343 +        protected void printFooter(TestResult result) {
344 +            if (result.wasSuccessful()) {
345 +                getWriter().println("OK (" + result.runCount() + " tests)"
346 +                    + "  Time: " + elapsedTimeAsString(runTime));
347 +            } else {
348 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
349 +                super.printFooter(result);
350 +            }
351 +        }
352 +    }
353 +
354 +    /**
355 +     * Returns a TestRunner that doesn't bother with unnecessary
356 +     * fluff, like printing a "." for each test case.
357 +     */
358 +    static junit.textui.TestRunner newPithyTestRunner() {
359 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
360 +        runner.setPrinter(new PithyResultPrinter(System.out));
361 +        return runner;
362 +    }
363 +
364 +    /**
365 +     * Runs all unit tests in the given test suite.
366 +     * Actual behavior influenced by jsr166.* system properties.
367 +     */
368 +    static void main(Test suite, String[] args) {
369          if (useSecurityManager) {
370              System.err.println("Setting a permissive security manager");
371              Policy.setPolicy(permissivePolicy());
372              System.setSecurityManager(new SecurityManager());
373          }
374 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
375 <
376 <        Test s = suite();
377 <        for (int i = 0; i < iters; ++i) {
157 <            junit.textui.TestRunner.run(s);
374 >        for (int i = 0; i < suiteRuns; i++) {
375 >            TestResult result = newPithyTestRunner().doRun(suite);
376 >            if (!result.wasSuccessful())
377 >                System.exit(1);
378              System.gc();
379              System.runFinalization();
380          }
161        System.exit(0);
381      }
382  
383      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 174 | Line 393 | public class JSR166TestCase extends Test
393          return suite;
394      }
395  
396 +    public static void addNamedTestClasses(TestSuite suite,
397 +                                           String... testClassNames) {
398 +        for (String testClassName : testClassNames) {
399 +            try {
400 +                Class<?> testClass = Class.forName(testClassName);
401 +                Method m = testClass.getDeclaredMethod("suite",
402 +                                                       new Class<?>[0]);
403 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
404 +            } catch (Exception e) {
405 +                throw new Error("Missing test class", e);
406 +            }
407 +        }
408 +    }
409 +
410 +    public static final double JAVA_CLASS_VERSION;
411 +    public static final String JAVA_SPECIFICATION_VERSION;
412 +    static {
413 +        try {
414 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
415 +                new java.security.PrivilegedAction<Double>() {
416 +                public Double run() {
417 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
418 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
419 +                new java.security.PrivilegedAction<String>() {
420 +                public String run() {
421 +                    return System.getProperty("java.specification.version");}});
422 +        } catch (Throwable t) {
423 +            throw new Error(t);
424 +        }
425 +    }
426 +
427 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
428 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
429 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
430 +    public static boolean atLeastJava9() {
431 +        return JAVA_CLASS_VERSION >= 53.0
432 +            // As of 2015-09, java9 still uses 52.0 class file version
433 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
434 +    }
435 +    public static boolean atLeastJava10() {
436 +        return JAVA_CLASS_VERSION >= 54.0
437 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
438 +    }
439 +
440      /**
441       * Collects all JSR166 unit tests as one suite.
442       */
443      public static Test suite() {
444 <        return newTestSuite(
444 >        // Java7+ test classes
445 >        TestSuite suite = newTestSuite(
446              ForkJoinPoolTest.suite(),
447              ForkJoinTaskTest.suite(),
448              RecursiveActionTest.suite(),
# Line 192 | Line 456 | public class JSR166TestCase extends Test
456              AbstractQueuedLongSynchronizerTest.suite(),
457              ArrayBlockingQueueTest.suite(),
458              ArrayDequeTest.suite(),
459 +            ArrayListTest.suite(),
460              AtomicBooleanTest.suite(),
461              AtomicIntegerArrayTest.suite(),
462              AtomicIntegerFieldUpdaterTest.suite(),
# Line 214 | Line 479 | public class JSR166TestCase extends Test
479              CopyOnWriteArrayListTest.suite(),
480              CopyOnWriteArraySetTest.suite(),
481              CountDownLatchTest.suite(),
482 +            CountedCompleterTest.suite(),
483              CyclicBarrierTest.suite(),
484              DelayQueueTest.suite(),
485              EntryTest.suite(),
# Line 242 | Line 508 | public class JSR166TestCase extends Test
508              TreeMapTest.suite(),
509              TreeSetTest.suite(),
510              TreeSubMapTest.suite(),
511 <            TreeSubSetTest.suite());
511 >            TreeSubSetTest.suite(),
512 >            VectorTest.suite());
513 >
514 >        // Java8+ test classes
515 >        if (atLeastJava8()) {
516 >            String[] java8TestClassNames = {
517 >                "ArrayDeque8Test",
518 >                "Atomic8Test",
519 >                "CompletableFutureTest",
520 >                "ConcurrentHashMap8Test",
521 >                "CountedCompleter8Test",
522 >                "DoubleAccumulatorTest",
523 >                "DoubleAdderTest",
524 >                "ForkJoinPool8Test",
525 >                "ForkJoinTask8Test",
526 >                "LongAccumulatorTest",
527 >                "LongAdderTest",
528 >                "SplittableRandomTest",
529 >                "StampedLockTest",
530 >                "SubmissionPublisherTest",
531 >                "ThreadLocalRandom8Test",
532 >                "TimeUnit8Test",
533 >            };
534 >            addNamedTestClasses(suite, java8TestClassNames);
535 >        }
536 >
537 >        // Java9+ test classes
538 >        if (atLeastJava9()) {
539 >            String[] java9TestClassNames = {
540 >                "AtomicBoolean9Test",
541 >                "AtomicInteger9Test",
542 >                "AtomicIntegerArray9Test",
543 >                "AtomicLong9Test",
544 >                "AtomicLongArray9Test",
545 >                "AtomicReference9Test",
546 >                "AtomicReferenceArray9Test",
547 >                "ExecutorCompletionService9Test",
548 >            };
549 >            addNamedTestClasses(suite, java9TestClassNames);
550 >        }
551 >
552 >        return suite;
553      }
554  
555 +    /** Returns list of junit-style test method names in given class. */
556 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
557 +        Method[] methods = testClass.getDeclaredMethods();
558 +        ArrayList<String> names = new ArrayList<String>(methods.length);
559 +        for (Method method : methods) {
560 +            if (method.getName().startsWith("test")
561 +                && Modifier.isPublic(method.getModifiers())
562 +                // method.getParameterCount() requires jdk8+
563 +                && method.getParameterTypes().length == 0) {
564 +                names.add(method.getName());
565 +            }
566 +        }
567 +        return names;
568 +    }
569 +
570 +    /**
571 +     * Returns junit-style testSuite for the given test class, but
572 +     * parameterized by passing extra data to each test.
573 +     */
574 +    public static <ExtraData> Test parameterizedTestSuite
575 +        (Class<? extends JSR166TestCase> testClass,
576 +         Class<ExtraData> dataClass,
577 +         ExtraData data) {
578 +        try {
579 +            TestSuite suite = new TestSuite();
580 +            Constructor c =
581 +                testClass.getDeclaredConstructor(dataClass, String.class);
582 +            for (String methodName : testMethodNames(testClass))
583 +                suite.addTest((Test) c.newInstance(data, methodName));
584 +            return suite;
585 +        } catch (Exception e) {
586 +            throw new Error(e);
587 +        }
588 +    }
589 +
590 +    /**
591 +     * Returns junit-style testSuite for the jdk8 extension of the
592 +     * given test class, but parameterized by passing extra data to
593 +     * each test.  Uses reflection to allow compilation in jdk7.
594 +     */
595 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
596 +        (Class<? extends JSR166TestCase> testClass,
597 +         Class<ExtraData> dataClass,
598 +         ExtraData data) {
599 +        if (atLeastJava8()) {
600 +            String name = testClass.getName();
601 +            String name8 = name.replaceAll("Test$", "8Test");
602 +            if (name.equals(name8)) throw new Error(name);
603 +            try {
604 +                return (Test)
605 +                    Class.forName(name8)
606 +                    .getMethod("testSuite", new Class[] { dataClass })
607 +                    .invoke(null, data);
608 +            } catch (Exception e) {
609 +                throw new Error(e);
610 +            }
611 +        } else {
612 +            return new TestSuite();
613 +        }
614 +    }
615 +
616 +    // Delays for timing-dependent tests, in milliseconds.
617  
618      public static long SHORT_DELAY_MS;
619      public static long SMALL_DELAY_MS;
620      public static long MEDIUM_DELAY_MS;
621      public static long LONG_DELAY_MS;
622  
254
623      /**
624 <     * Returns the shortest timed delay. This could
625 <     * be reimplemented to use for example a Property.
624 >     * Returns the shortest timed delay. This can be scaled up for
625 >     * slow machines using the jsr166.delay.factor system property,
626 >     * or via jtreg's -timeoutFactor: flag.
627 >     * http://openjdk.java.net/jtreg/command-help.html
628       */
629      protected long getShortDelay() {
630 <        return 50;
630 >        return (long) (50 * delayFactor);
631      }
632  
633      /**
# Line 279 | Line 649 | public class JSR166TestCase extends Test
649      }
650  
651      /**
652 <     * Returns a new Date instance representing a time delayMillis
653 <     * milliseconds in the future.
652 >     * Returns a new Date instance representing a time at least
653 >     * delayMillis milliseconds in the future.
654       */
655      Date delayedDate(long delayMillis) {
656 <        return new Date(System.currentTimeMillis() + delayMillis);
656 >        // Add 1 because currentTimeMillis is known to round into the past.
657 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
658      }
659  
660      /**
# Line 299 | Line 670 | public class JSR166TestCase extends Test
670       * the same test have no effect.
671       */
672      public void threadRecordFailure(Throwable t) {
673 +        System.err.println(t);
674 +        dumpTestThreads();
675          threadFailure.compareAndSet(null, t);
676      }
677  
# Line 306 | Line 679 | public class JSR166TestCase extends Test
679          setDelays();
680      }
681  
682 +    void tearDownFail(String format, Object... args) {
683 +        String msg = toString() + ": " + String.format(format, args);
684 +        System.err.println(msg);
685 +        dumpTestThreads();
686 +        throw new AssertionFailedError(msg);
687 +    }
688 +
689      /**
690       * Extra checks that get done for all test cases.
691       *
# Line 333 | Line 713 | public class JSR166TestCase extends Test
713          }
714  
715          if (Thread.interrupted())
716 <            throw new AssertionFailedError("interrupt status set in main thread");
716 >            tearDownFail("interrupt status set in main thread");
717 >
718 >        checkForkJoinPoolThreadLeaks();
719 >    }
720 >
721 >    /**
722 >     * Finds missing PoolCleaners
723 >     */
724 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
725 >        Thread[] survivors = new Thread[7];
726 >        int count = Thread.enumerate(survivors);
727 >        for (int i = 0; i < count; i++) {
728 >            Thread thread = survivors[i];
729 >            String name = thread.getName();
730 >            if (name.startsWith("ForkJoinPool-")) {
731 >                // give thread some time to terminate
732 >                thread.join(LONG_DELAY_MS);
733 >                if (thread.isAlive())
734 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
735 >                                 thread);
736 >            }
737 >        }
738 >
739 >        if (!ForkJoinPool.commonPool()
740 >            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
741 >            tearDownFail("ForkJoin common pool thread stuck");
742      }
743  
744      /**
# Line 346 | Line 751 | public class JSR166TestCase extends Test
751              fail(reason);
752          } catch (AssertionFailedError t) {
753              threadRecordFailure(t);
754 <            fail(reason);
754 >            throw t;
755          }
756      }
757  
# Line 414 | Line 819 | public class JSR166TestCase extends Test
819      public void threadAssertEquals(Object x, Object y) {
820          try {
821              assertEquals(x, y);
822 <        } catch (AssertionFailedError t) {
823 <            threadRecordFailure(t);
824 <            throw t;
825 <        } catch (Throwable t) {
826 <            threadUnexpectedException(t);
822 >        } catch (AssertionFailedError fail) {
823 >            threadRecordFailure(fail);
824 >            throw fail;
825 >        } catch (Throwable fail) {
826 >            threadUnexpectedException(fail);
827          }
828      }
829  
# Line 430 | Line 835 | public class JSR166TestCase extends Test
835      public void threadAssertSame(Object x, Object y) {
836          try {
837              assertSame(x, y);
838 <        } catch (AssertionFailedError t) {
839 <            threadRecordFailure(t);
840 <            throw t;
838 >        } catch (AssertionFailedError fail) {
839 >            threadRecordFailure(fail);
840 >            throw fail;
841          }
842      }
843  
# Line 473 | Line 878 | public class JSR166TestCase extends Test
878      /**
879       * Delays, via Thread.sleep, for the given millisecond delay, but
880       * if the sleep is shorter than specified, may re-sleep or yield
881 <     * until time elapses.
881 >     * until time elapses.  Ensures that the given time, as measured
882 >     * by System.nanoTime(), has elapsed.
883       */
884      static void delay(long millis) throws InterruptedException {
885 <        long startTime = System.nanoTime();
886 <        long ns = millis * 1000 * 1000;
887 <        for (;;) {
885 >        long nanos = millis * (1000 * 1000);
886 >        final long wakeupTime = System.nanoTime() + nanos;
887 >        do {
888              if (millis > 0L)
889                  Thread.sleep(millis);
890              else // too short to sleep
891                  Thread.yield();
892 <            long d = ns - (System.nanoTime() - startTime);
893 <            if (d > 0L)
894 <                millis = d / (1000 * 1000);
895 <            else
896 <                break;
892 >            nanos = wakeupTime - System.nanoTime();
893 >            millis = nanos / (1000 * 1000);
894 >        } while (nanos >= 0L);
895 >    }
896 >
897 >    /**
898 >     * Allows use of try-with-resources with per-test thread pools.
899 >     */
900 >    class PoolCleaner implements AutoCloseable {
901 >        private final ExecutorService pool;
902 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
903 >        public void close() { joinPool(pool); }
904 >    }
905 >
906 >    /**
907 >     * An extension of PoolCleaner that has an action to release the pool.
908 >     */
909 >    class PoolCleanerWithReleaser extends PoolCleaner {
910 >        private final Runnable releaser;
911 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
912 >            super(pool);
913 >            this.releaser = releaser;
914 >        }
915 >        public void close() {
916 >            try {
917 >                releaser.run();
918 >            } finally {
919 >                super.close();
920 >            }
921          }
922      }
923  
924 +    PoolCleaner cleaner(ExecutorService pool) {
925 +        return new PoolCleaner(pool);
926 +    }
927 +
928 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
929 +        return new PoolCleanerWithReleaser(pool, releaser);
930 +    }
931 +
932 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
933 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
934 +    }
935 +
936 +    Runnable releaser(final CountDownLatch latch) {
937 +        return new Runnable() { public void run() {
938 +            do { latch.countDown(); }
939 +            while (latch.getCount() > 0);
940 +        }};
941 +    }
942 +
943 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
944 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
945 +    }
946 +
947 +    Runnable releaser(final AtomicBoolean flag) {
948 +        return new Runnable() { public void run() { flag.set(true); }};
949 +    }
950 +
951      /**
952       * Waits out termination of a thread pool or fails doing so.
953       */
954 <    void joinPool(ExecutorService exec) {
954 >    void joinPool(ExecutorService pool) {
955          try {
956 <            exec.shutdown();
957 <            assertTrue("ExecutorService did not terminate in a timely manner",
958 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
956 >            pool.shutdown();
957 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
958 >                try {
959 >                    threadFail("ExecutorService " + pool +
960 >                               " did not terminate in a timely manner");
961 >                } finally {
962 >                    // last resort, for the benefit of subsequent tests
963 >                    pool.shutdownNow();
964 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
965 >                }
966 >            }
967          } catch (SecurityException ok) {
968              // Allowed in case test doesn't have privs
969 <        } catch (InterruptedException ie) {
970 <            fail("Unexpected InterruptedException");
969 >        } catch (InterruptedException fail) {
970 >            threadFail("Unexpected InterruptedException");
971          }
972      }
973  
974      /**
975 +     * Like Runnable, but with the freedom to throw anything.
976 +     * junit folks had the same idea:
977 +     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
978 +     */
979 +    interface Action { public void run() throws Throwable; }
980 +
981 +    /**
982 +     * Runs all the given actions in parallel, failing if any fail.
983 +     * Useful for running multiple variants of tests that are
984 +     * necessarily individually slow because they must block.
985 +     */
986 +    void testInParallel(Action ... actions) {
987 +        ExecutorService pool = Executors.newCachedThreadPool();
988 +        try (PoolCleaner cleaner = cleaner(pool)) {
989 +            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
990 +            for (final Action action : actions)
991 +                futures.add(pool.submit(new CheckedRunnable() {
992 +                    public void realRun() throws Throwable { action.run();}}));
993 +            for (Future<?> future : futures)
994 +                try {
995 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
996 +                } catch (ExecutionException ex) {
997 +                    threadUnexpectedException(ex.getCause());
998 +                } catch (Exception ex) {
999 +                    threadUnexpectedException(ex);
1000 +                }
1001 +        }
1002 +    }
1003 +
1004 +    /**
1005 +     * A debugging tool to print stack traces of most threads, as jstack does.
1006 +     * Uninteresting threads are filtered out.
1007 +     */
1008 +    static void dumpTestThreads() {
1009 +        SecurityManager sm = System.getSecurityManager();
1010 +        if (sm != null) {
1011 +            try {
1012 +                System.setSecurityManager(null);
1013 +            } catch (SecurityException giveUp) {
1014 +                return;
1015 +            }
1016 +        }
1017 +
1018 +        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1019 +        System.err.println("------ stacktrace dump start ------");
1020 +        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1021 +            final String name = info.getThreadName();
1022 +            String lockName;
1023 +            if ("Signal Dispatcher".equals(name))
1024 +                continue;
1025 +            if ("Reference Handler".equals(name)
1026 +                && (lockName = info.getLockName()) != null
1027 +                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1028 +                continue;
1029 +            if ("Finalizer".equals(name)
1030 +                && (lockName = info.getLockName()) != null
1031 +                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1032 +                continue;
1033 +            if ("checkForWedgedTest".equals(name))
1034 +                continue;
1035 +            System.err.print(info);
1036 +        }
1037 +        System.err.println("------ stacktrace dump end ------");
1038 +
1039 +        if (sm != null) System.setSecurityManager(sm);
1040 +    }
1041 +
1042 +    /**
1043       * Checks that thread does not terminate within the default
1044       * millisecond delay of {@code timeoutMillis()}.
1045       */
# Line 522 | Line 1055 | public class JSR166TestCase extends Test
1055              // No need to optimize the failing case via Thread.join.
1056              delay(millis);
1057              assertTrue(thread.isAlive());
1058 <        } catch (InterruptedException ie) {
1059 <            fail("Unexpected InterruptedException");
1058 >        } catch (InterruptedException fail) {
1059 >            threadFail("Unexpected InterruptedException");
1060 >        }
1061 >    }
1062 >
1063 >    /**
1064 >     * Checks that the threads do not terminate within the default
1065 >     * millisecond delay of {@code timeoutMillis()}.
1066 >     */
1067 >    void assertThreadsStayAlive(Thread... threads) {
1068 >        assertThreadsStayAlive(timeoutMillis(), threads);
1069 >    }
1070 >
1071 >    /**
1072 >     * Checks that the threads do not terminate within the given millisecond delay.
1073 >     */
1074 >    void assertThreadsStayAlive(long millis, Thread... threads) {
1075 >        try {
1076 >            // No need to optimize the failing case via Thread.join.
1077 >            delay(millis);
1078 >            for (Thread thread : threads)
1079 >                assertTrue(thread.isAlive());
1080 >        } catch (InterruptedException fail) {
1081 >            threadFail("Unexpected InterruptedException");
1082          }
1083      }
1084  
# Line 544 | Line 1099 | public class JSR166TestCase extends Test
1099              future.get(timeoutMillis, MILLISECONDS);
1100              shouldThrow();
1101          } catch (TimeoutException success) {
1102 <        } catch (Exception e) {
1103 <            threadUnexpectedException(e);
1102 >        } catch (Exception fail) {
1103 >            threadUnexpectedException(fail);
1104          } finally { future.cancel(true); }
1105          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1106      }
# Line 589 | Line 1144 | public class JSR166TestCase extends Test
1144      public static final Integer m6  = new Integer(-6);
1145      public static final Integer m10 = new Integer(-10);
1146  
592
1147      /**
1148       * Runs Runnable r with a security policy that permits precisely
1149       * the specified permissions.  If there is no current security
# Line 601 | Line 1155 | public class JSR166TestCase extends Test
1155          SecurityManager sm = System.getSecurityManager();
1156          if (sm == null) {
1157              r.run();
1158 +        }
1159 +        runWithSecurityManagerWithPermissions(r, permissions);
1160 +    }
1161 +
1162 +    /**
1163 +     * Runs Runnable r with a security policy that permits precisely
1164 +     * the specified permissions.  If there is no current security
1165 +     * manager, a temporary one is set for the duration of the
1166 +     * Runnable.  We require that any security manager permit
1167 +     * getPolicy/setPolicy.
1168 +     */
1169 +    public void runWithSecurityManagerWithPermissions(Runnable r,
1170 +                                                      Permission... permissions) {
1171 +        SecurityManager sm = System.getSecurityManager();
1172 +        if (sm == null) {
1173              Policy savedPolicy = Policy.getPolicy();
1174              try {
1175                  Policy.setPolicy(permissivePolicy());
1176                  System.setSecurityManager(new SecurityManager());
1177 <                runWithPermissions(r, permissions);
1177 >                runWithSecurityManagerWithPermissions(r, permissions);
1178              } finally {
1179                  System.setSecurityManager(null);
1180                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 1222 | public class JSR166TestCase extends Test
1222              return perms.implies(p);
1223          }
1224          public void refresh() {}
1225 +        public String toString() {
1226 +            List<Permission> ps = new ArrayList<Permission>();
1227 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1228 +                ps.add(e.nextElement());
1229 +            return "AdjustablePolicy with permissions " + ps;
1230 +        }
1231      }
1232  
1233      /**
# Line 678 | Line 1253 | public class JSR166TestCase extends Test
1253       * Sleeps until the given time has elapsed.
1254       * Throws AssertionFailedError if interrupted.
1255       */
1256 <    void sleep(long millis) {
1256 >    static void sleep(long millis) {
1257          try {
1258              delay(millis);
1259 <        } catch (InterruptedException ie) {
1259 >        } catch (InterruptedException fail) {
1260              AssertionFailedError afe =
1261                  new AssertionFailedError("Unexpected InterruptedException");
1262 <            afe.initCause(ie);
1262 >            afe.initCause(fail);
1263              throw afe;
1264          }
1265      }
1266  
1267      /**
1268 <     * Waits up to the specified number of milliseconds for the given
1268 >     * Spin-waits up to the specified number of milliseconds for the given
1269       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1270       */
1271      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1272 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
1272 >        long startTime = 0L;
1273          for (;;) {
1274              Thread.State s = thread.getState();
1275              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 1278 | public class JSR166TestCase extends Test
1278                  return;
1279              else if (s == Thread.State.TERMINATED)
1280                  fail("Unexpected thread termination");
1281 <            else if (System.nanoTime() - t0 > timeoutNanos) {
1281 >            else if (startTime == 0L)
1282 >                startTime = System.nanoTime();
1283 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1284                  threadAssertTrue(thread.isAlive());
1285                  return;
1286              }
# Line 723 | Line 1299 | public class JSR166TestCase extends Test
1299      /**
1300       * Returns the number of milliseconds since time given by
1301       * startNanoTime, which must have been previously returned from a
1302 <     * call to {@link System.nanoTime()}.
1302 >     * call to {@link System#nanoTime()}.
1303       */
1304 <    long millisElapsedSince(long startNanoTime) {
1304 >    static long millisElapsedSince(long startNanoTime) {
1305          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1306      }
1307  
1308 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1309 + //         long startTime = System.nanoTime();
1310 + //         try {
1311 + //             r.run();
1312 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1313 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1314 + //             throw new AssertionFailedError("did not return promptly");
1315 + //     }
1316 +
1317 + //     void assertTerminatesPromptly(Runnable r) {
1318 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1319 + //     }
1320 +
1321 +    /**
1322 +     * Checks that timed f.get() returns the expected value, and does not
1323 +     * wait for the timeout to elapse before returning.
1324 +     */
1325 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1326 +        long startTime = System.nanoTime();
1327 +        try {
1328 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1329 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1330 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1331 +            throw new AssertionFailedError("timed get did not return promptly");
1332 +    }
1333 +
1334 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1335 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1336 +    }
1337 +
1338      /**
1339       * Returns a new started daemon Thread running the given runnable.
1340       */
# Line 747 | Line 1353 | public class JSR166TestCase extends Test
1353      void awaitTermination(Thread t, long timeoutMillis) {
1354          try {
1355              t.join(timeoutMillis);
1356 <        } catch (InterruptedException ie) {
1357 <            threadUnexpectedException(ie);
1356 >        } catch (InterruptedException fail) {
1357 >            threadUnexpectedException(fail);
1358          } finally {
1359              if (t.getState() != Thread.State.TERMINATED) {
1360                  t.interrupt();
1361 <                fail("Test timed out");
1361 >                threadFail("timed out waiting for thread to terminate");
1362              }
1363          }
1364      }
# Line 774 | Line 1380 | public class JSR166TestCase extends Test
1380          public final void run() {
1381              try {
1382                  realRun();
1383 <            } catch (Throwable t) {
1384 <                threadUnexpectedException(t);
1383 >            } catch (Throwable fail) {
1384 >                threadUnexpectedException(fail);
1385              }
1386          }
1387      }
# Line 829 | Line 1435 | public class JSR166TestCase extends Test
1435                  threadShouldThrow("InterruptedException");
1436              } catch (InterruptedException success) {
1437                  threadAssertFalse(Thread.interrupted());
1438 <            } catch (Throwable t) {
1439 <                threadUnexpectedException(t);
1438 >            } catch (Throwable fail) {
1439 >                threadUnexpectedException(fail);
1440              }
1441          }
1442      }
# Line 841 | Line 1447 | public class JSR166TestCase extends Test
1447          public final T call() {
1448              try {
1449                  return realCall();
1450 <            } catch (Throwable t) {
1451 <                threadUnexpectedException(t);
1450 >            } catch (Throwable fail) {
1451 >                threadUnexpectedException(fail);
1452                  return null;
1453              }
1454          }
# Line 859 | Line 1465 | public class JSR166TestCase extends Test
1465                  return result;
1466              } catch (InterruptedException success) {
1467                  threadAssertFalse(Thread.interrupted());
1468 <            } catch (Throwable t) {
1469 <                threadUnexpectedException(t);
1468 >            } catch (Throwable fail) {
1469 >                threadUnexpectedException(fail);
1470              }
1471              return null;
1472          }
# Line 877 | Line 1483 | public class JSR166TestCase extends Test
1483      public static final String TEST_STRING = "a test string";
1484  
1485      public static class StringTask implements Callable<String> {
1486 <        public String call() { return TEST_STRING; }
1486 >        final String value;
1487 >        public StringTask() { this(TEST_STRING); }
1488 >        public StringTask(String value) { this.value = value; }
1489 >        public String call() { return value; }
1490      }
1491  
1492      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 890 | Line 1499 | public class JSR166TestCase extends Test
1499              }};
1500      }
1501  
1502 <    public Runnable awaiter(final CountDownLatch latch) {
1502 >    public Runnable countDowner(final CountDownLatch latch) {
1503          return new CheckedRunnable() {
1504              public void realRun() throws InterruptedException {
1505 <                await(latch);
1505 >                latch.countDown();
1506              }};
1507      }
1508  
1509 +    class LatchAwaiter extends CheckedRunnable {
1510 +        static final int NEW = 0;
1511 +        static final int RUNNING = 1;
1512 +        static final int DONE = 2;
1513 +        final CountDownLatch latch;
1514 +        int state = NEW;
1515 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1516 +        public void realRun() throws InterruptedException {
1517 +            state = 1;
1518 +            await(latch);
1519 +            state = 2;
1520 +        }
1521 +    }
1522 +
1523 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1524 +        return new LatchAwaiter(latch);
1525 +    }
1526 +
1527 +    public void await(CountDownLatch latch, long timeoutMillis) {
1528 +        try {
1529 +            if (!latch.await(timeoutMillis, MILLISECONDS))
1530 +                fail("timed out waiting for CountDownLatch for "
1531 +                     + (timeoutMillis/1000) + " sec");
1532 +        } catch (Throwable fail) {
1533 +            threadUnexpectedException(fail);
1534 +        }
1535 +    }
1536 +
1537      public void await(CountDownLatch latch) {
1538 +        await(latch, LONG_DELAY_MS);
1539 +    }
1540 +
1541 +    public void await(Semaphore semaphore) {
1542          try {
1543 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1544 <        } catch (Throwable t) {
1545 <            threadUnexpectedException(t);
1543 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1544 >                fail("timed out waiting for Semaphore for "
1545 >                     + (LONG_DELAY_MS/1000) + " sec");
1546 >        } catch (Throwable fail) {
1547 >            threadUnexpectedException(fail);
1548          }
1549      }
1550  
# Line 1092 | Line 1735 | public class JSR166TestCase extends Test
1735      public abstract class CheckedRecursiveAction extends RecursiveAction {
1736          protected abstract void realCompute() throws Throwable;
1737  
1738 <        public final void compute() {
1738 >        @Override protected final void compute() {
1739              try {
1740                  realCompute();
1741 <            } catch (Throwable t) {
1742 <                threadUnexpectedException(t);
1741 >            } catch (Throwable fail) {
1742 >                threadUnexpectedException(fail);
1743              }
1744          }
1745      }
# Line 1107 | Line 1750 | public class JSR166TestCase extends Test
1750      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1751          protected abstract T realCompute() throws Throwable;
1752  
1753 <        public final T compute() {
1753 >        @Override protected final T compute() {
1754              try {
1755                  return realCompute();
1756 <            } catch (Throwable t) {
1757 <                threadUnexpectedException(t);
1756 >            } catch (Throwable fail) {
1757 >                threadUnexpectedException(fail);
1758                  return null;
1759              }
1760          }
# Line 1129 | Line 1772 | public class JSR166TestCase extends Test
1772       * A CyclicBarrier that uses timed await and fails with
1773       * AssertionFailedErrors instead of throwing checked exceptions.
1774       */
1775 <    public class CheckedBarrier extends CyclicBarrier {
1775 >    public static class CheckedBarrier extends CyclicBarrier {
1776          public CheckedBarrier(int parties) { super(parties); }
1777  
1778          public int await() {
1779              try {
1780                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1781 <            } catch (TimeoutException e) {
1781 >            } catch (TimeoutException timedOut) {
1782                  throw new AssertionFailedError("timed out");
1783 <            } catch (Exception e) {
1783 >            } catch (Exception fail) {
1784                  AssertionFailedError afe =
1785 <                    new AssertionFailedError("Unexpected exception: " + e);
1786 <                afe.initCause(e);
1785 >                    new AssertionFailedError("Unexpected exception: " + fail);
1786 >                afe.initCause(fail);
1787                  throw afe;
1788              }
1789          }
# Line 1168 | Line 1811 | public class JSR166TestCase extends Test
1811                  q.remove();
1812                  shouldThrow();
1813              } catch (NoSuchElementException success) {}
1814 <        } catch (InterruptedException ie) {
1172 <            threadUnexpectedException(ie);
1173 <        }
1814 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1815      }
1816  
1817 <    @SuppressWarnings("unchecked")
1818 <    <T> T serialClone(T o) {
1817 >    void assertSerialEquals(Object x, Object y) {
1818 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1819 >    }
1820 >
1821 >    void assertNotSerialEquals(Object x, Object y) {
1822 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1823 >    }
1824 >
1825 >    byte[] serialBytes(Object o) {
1826          try {
1827              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1828              ObjectOutputStream oos = new ObjectOutputStream(bos);
1829              oos.writeObject(o);
1830              oos.flush();
1831              oos.close();
1832 <            ByteArrayInputStream bin =
1833 <                new ByteArrayInputStream(bos.toByteArray());
1834 <            ObjectInputStream ois = new ObjectInputStream(bin);
1835 <            return (T) ois.readObject();
1836 <        } catch (Throwable t) {
1837 <            threadUnexpectedException(t);
1832 >            return bos.toByteArray();
1833 >        } catch (Throwable fail) {
1834 >            threadUnexpectedException(fail);
1835 >            return new byte[0];
1836 >        }
1837 >    }
1838 >
1839 >    void assertImmutable(final Object o) {
1840 >        if (o instanceof Collection) {
1841 >            assertThrows(
1842 >                UnsupportedOperationException.class,
1843 >                new Runnable() { public void run() {
1844 >                        ((Collection) o).add(null);}});
1845 >        }
1846 >    }
1847 >
1848 >    @SuppressWarnings("unchecked")
1849 >    <T> T serialClone(T o) {
1850 >        try {
1851 >            ObjectInputStream ois = new ObjectInputStream
1852 >                (new ByteArrayInputStream(serialBytes(o)));
1853 >            T clone = (T) ois.readObject();
1854 >            if (o == clone) assertImmutable(o);
1855 >            assertSame(o.getClass(), clone.getClass());
1856 >            return clone;
1857 >        } catch (Throwable fail) {
1858 >            threadUnexpectedException(fail);
1859 >            return null;
1860 >        }
1861 >    }
1862 >
1863 >    /**
1864 >     * A version of serialClone that leaves error handling (for
1865 >     * e.g. NotSerializableException) up to the caller.
1866 >     */
1867 >    @SuppressWarnings("unchecked")
1868 >    <T> T serialClonePossiblyFailing(T o)
1869 >        throws ReflectiveOperationException, java.io.IOException {
1870 >        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1871 >        ObjectOutputStream oos = new ObjectOutputStream(bos);
1872 >        oos.writeObject(o);
1873 >        oos.flush();
1874 >        oos.close();
1875 >        ObjectInputStream ois = new ObjectInputStream
1876 >            (new ByteArrayInputStream(bos.toByteArray()));
1877 >        T clone = (T) ois.readObject();
1878 >        if (o == clone) assertImmutable(o);
1879 >        assertSame(o.getClass(), clone.getClass());
1880 >        return clone;
1881 >    }
1882 >
1883 >    /**
1884 >     * If o implements Cloneable and has a public clone method,
1885 >     * returns a clone of o, else null.
1886 >     */
1887 >    @SuppressWarnings("unchecked")
1888 >    <T> T cloneableClone(T o) {
1889 >        if (!(o instanceof Cloneable)) return null;
1890 >        final T clone;
1891 >        try {
1892 >            clone = (T) o.getClass().getMethod("clone").invoke(o);
1893 >        } catch (NoSuchMethodException ok) {
1894              return null;
1895 +        } catch (ReflectiveOperationException unexpected) {
1896 +            throw new Error(unexpected);
1897          }
1898 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1899 +        assertSame(o.getClass(), clone.getClass());
1900 +        return clone;
1901 +    }
1902 +
1903 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1904 +                             Runnable... throwingActions) {
1905 +        for (Runnable throwingAction : throwingActions) {
1906 +            boolean threw = false;
1907 +            try { throwingAction.run(); }
1908 +            catch (Throwable t) {
1909 +                threw = true;
1910 +                if (!expectedExceptionClass.isInstance(t)) {
1911 +                    AssertionFailedError afe =
1912 +                        new AssertionFailedError
1913 +                        ("Expected " + expectedExceptionClass.getName() +
1914 +                         ", got " + t.getClass().getName());
1915 +                    afe.initCause(t);
1916 +                    threadUnexpectedException(afe);
1917 +                }
1918 +            }
1919 +            if (!threw)
1920 +                shouldThrow(expectedExceptionClass.getName());
1921 +        }
1922 +    }
1923 +
1924 +    public void assertIteratorExhausted(Iterator<?> it) {
1925 +        try {
1926 +            it.next();
1927 +            shouldThrow();
1928 +        } catch (NoSuchElementException success) {}
1929 +        assertFalse(it.hasNext());
1930 +    }
1931 +
1932 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1933 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1934 +    }
1935 +
1936 +    public Runnable runnableThrowing(final RuntimeException ex) {
1937 +        return new Runnable() { public void run() { throw ex; }};
1938 +    }
1939 +
1940 +    /** A reusable thread pool to be shared by tests. */
1941 +    static final ExecutorService cachedThreadPool =
1942 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1943 +                               1000L, MILLISECONDS,
1944 +                               new SynchronousQueue<Runnable>());
1945 +
1946 +    static <T> void shuffle(T[] array) {
1947 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1948      }
1949   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines