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.80 by jsr166, Fri May 13 21:48:58 2011 UTC vs.
Revision 1.182 by jsr166, Sun Jan 17 00:07:51 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > /*
10 > * @test
11 > * @summary JSR-166 tck tests
12 > * @build *
13 > * @run junit/othervm/timeout=1000 JSR166TestCase
14 > */
15 >
16 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
17 > import static java.util.concurrent.TimeUnit.MINUTES;
18 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
19 >
20   import java.io.ByteArrayInputStream;
21   import java.io.ByteArrayOutputStream;
22   import java.io.ObjectInputStream;
23   import java.io.ObjectOutputStream;
24 < import java.util.Arrays;
25 < import java.util.NoSuchElementException;
26 < import java.util.PropertyPermission;
27 < import java.util.concurrent.*;
28 < import java.util.concurrent.atomic.AtomicReference;
29 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
30 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
24 > import java.lang.management.ManagementFactory;
25 > import java.lang.management.ThreadInfo;
26 > import java.lang.management.ThreadMXBean;
27 > import java.lang.reflect.Constructor;
28 > import java.lang.reflect.Method;
29 > import java.lang.reflect.Modifier;
30 > import java.nio.file.Files;
31 > import java.nio.file.Paths;
32   import java.security.CodeSource;
33   import java.security.Permission;
34   import java.security.PermissionCollection;
# Line 25 | Line 36 | import java.security.Permissions;
36   import java.security.Policy;
37   import java.security.ProtectionDomain;
38   import java.security.SecurityPermission;
39 + import java.util.ArrayList;
40 + import java.util.Arrays;
41 + import java.util.Date;
42 + import java.util.Enumeration;
43 + import java.util.Iterator;
44 + import java.util.List;
45 + import java.util.NoSuchElementException;
46 + import java.util.PropertyPermission;
47 + import java.util.concurrent.BlockingQueue;
48 + import java.util.concurrent.Callable;
49 + import java.util.concurrent.CountDownLatch;
50 + import java.util.concurrent.CyclicBarrier;
51 + import java.util.concurrent.ExecutionException;
52 + import java.util.concurrent.Executors;
53 + import java.util.concurrent.ExecutorService;
54 + import java.util.concurrent.ForkJoinPool;
55 + import java.util.concurrent.Future;
56 + import java.util.concurrent.RecursiveAction;
57 + import java.util.concurrent.RecursiveTask;
58 + import java.util.concurrent.RejectedExecutionHandler;
59 + import java.util.concurrent.Semaphore;
60 + import java.util.concurrent.ThreadFactory;
61 + import java.util.concurrent.ThreadPoolExecutor;
62 + import java.util.concurrent.TimeoutException;
63 + import java.util.concurrent.atomic.AtomicReference;
64 + import java.util.regex.Matcher;
65 + import java.util.regex.Pattern;
66 +
67 + import junit.framework.AssertionFailedError;
68 + import junit.framework.Test;
69 + import junit.framework.TestCase;
70 + import junit.framework.TestResult;
71 + import junit.framework.TestSuite;
72  
73   /**
74   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 36 | Line 80 | import java.security.SecurityPermission;
80   *
81   * <ol>
82   *
83 < * <li> All assertions in code running in generated threads must use
83 > * <li>All assertions in code running in generated threads must use
84   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
85   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
86   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
87   * particularly recommended) for other code to use these forms too.
88   * Only the most typically used JUnit assertion methods are defined
89 < * this way, but enough to live with.</li>
89 > * this way, but enough to live with.
90   *
91 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
91 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
92   * to invoke {@code super.setUp} and {@code super.tearDown} within
93   * them. These methods are used to clear and check for thread
94 < * assertion failures.</li>
94 > * assertion failures.
95   *
96   * <li>All delays and timeouts must use one of the constants {@code
97   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 58 | Line 102 | import java.security.SecurityPermission;
102   * is always discriminable as larger than SHORT and smaller than
103   * MEDIUM.  And so on. These constants are set to conservative values,
104   * but even so, if there is ever any doubt, they can all be increased
105 < * in one spot to rerun tests on slower platforms.</li>
105 > * in one spot to rerun tests on slower platforms.
106   *
107 < * <li> All threads generated must be joined inside each test case
107 > * <li>All threads generated must be joined inside each test case
108   * method (or {@code fail} to do so) before returning from the
109   * method. The {@code joinPool} method can be used to do this when
110 < * using Executors.</li>
110 > * using Executors.
111   *
112   * </ol>
113   *
114 < * <p> <b>Other notes</b>
114 > * <p><b>Other notes</b>
115   * <ul>
116   *
117 < * <li> Usually, there is one testcase method per JSR166 method
117 > * <li>Usually, there is one testcase method per JSR166 method
118   * covering "normal" operation, and then as many exception-testing
119   * methods as there are exceptions the method can throw. Sometimes
120   * there are multiple tests per JSR166 method when the different
121   * "normal" behaviors differ significantly. And sometimes testcases
122 < * cover multiple methods when they cannot be tested in
79 < * isolation.</li>
122 > * cover multiple methods when they cannot be tested in isolation.
123   *
124 < * <li> The documentation style for testcases is to provide as javadoc
124 > * <li>The documentation style for testcases is to provide as javadoc
125   * a simple sentence or two describing the property that the testcase
126   * method purports to test. The javadocs do not say anything about how
127 < * the property is tested. To find out, read the code.</li>
127 > * the property is tested. To find out, read the code.
128   *
129 < * <li> These tests are "conformance tests", and do not attempt to
129 > * <li>These tests are "conformance tests", and do not attempt to
130   * test throughput, latency, scalability or other performance factors
131   * (see the separate "jtreg" tests for a set intended to check these
132   * for the most central aspects of functionality.) So, most tests use
133   * the smallest sensible numbers of threads, collection sizes, etc
134 < * needed to check basic conformance.</li>
134 > * needed to check basic conformance.
135   *
136   * <li>The test classes currently do not declare inclusion in
137   * any particular package to simplify things for people integrating
138 < * them in TCK test suites.</li>
138 > * them in TCK test suites.
139   *
140 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
141 < * runs all JSR166 unit tests.</li>
140 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
141 > * runs all JSR166 unit tests.
142   *
143   * </ul>
144   */
# Line 107 | Line 150 | public class JSR166TestCase extends Test
150          Boolean.getBoolean("jsr166.expensiveTests");
151  
152      /**
153 +     * If true, also run tests that are not part of the official tck
154 +     * because they test unspecified implementation details.
155 +     */
156 +    protected static final boolean testImplementationDetails =
157 +        Boolean.getBoolean("jsr166.testImplementationDetails");
158 +
159 +    /**
160       * If true, report on stdout all "slow" tests, that is, ones that
161       * take more than profileThreshold milliseconds to execute.
162       */
# Line 120 | Line 170 | public class JSR166TestCase extends Test
170      private static final long profileThreshold =
171          Long.getLong("jsr166.profileThreshold", 100);
172  
173 +    /**
174 +     * The number of repetitions per test (for tickling rare bugs).
175 +     */
176 +    private static final int runsPerTest =
177 +        Integer.getInteger("jsr166.runsPerTest", 1);
178 +
179 +    /**
180 +     * The number of repetitions of the test suite (for finding leaks?).
181 +     */
182 +    private static final int suiteRuns =
183 +        Integer.getInteger("jsr166.suiteRuns", 1);
184 +
185 +    /**
186 +     * The scaling factor to apply to standard delays used in tests.
187 +     */
188 +    private static final int delayFactor =
189 +        Integer.getInteger("jsr166.delay.factor", 1);
190 +
191 +    public JSR166TestCase() { super(); }
192 +    public JSR166TestCase(String name) { super(name); }
193 +
194 +    /**
195 +     * A filter for tests to run, matching strings of the form
196 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
197 +     * Usefully combined with jsr166.runsPerTest.
198 +     */
199 +    private static final Pattern methodFilter = methodFilter();
200 +
201 +    private static Pattern methodFilter() {
202 +        String regex = System.getProperty("jsr166.methodFilter");
203 +        return (regex == null) ? null : Pattern.compile(regex);
204 +    }
205 +
206 +    // Instrumentation to debug very rare, but very annoying hung test runs.
207 +    static volatile TestCase currentTestCase;
208 +    // static volatile int currentRun = 0;
209 +    static {
210 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
211 +            // Avoid spurious reports with enormous runsPerTest.
212 +            // A single test case run should never take more than 1 second.
213 +            // But let's cap it at the high end too ...
214 +            final int timeoutMinutes =
215 +                Math.min(15, Math.max(runsPerTest / 60, 1));
216 +            for (TestCase lastTestCase = currentTestCase;;) {
217 +                try { MINUTES.sleep(timeoutMinutes); }
218 +                catch (InterruptedException unexpected) { break; }
219 +                if (lastTestCase == currentTestCase) {
220 +                    System.err.printf(
221 +                        "Looks like we're stuck running test: %s%n",
222 +                        lastTestCase);
223 + //                     System.err.printf(
224 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
225 + //                         lastTestCase, currentRun, runsPerTest);
226 + //                     System.err.println("availableProcessors=" +
227 + //                         Runtime.getRuntime().availableProcessors());
228 + //                     System.err.printf("cpu model = %s%n", cpuModel());
229 +                    dumpTestThreads();
230 +                    // one stack dump is probably enough; more would be spam
231 +                    break;
232 +                }
233 +                lastTestCase = currentTestCase;
234 +            }}};
235 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
236 +        thread.setDaemon(true);
237 +        thread.start();
238 +    }
239 +
240 + //     public static String cpuModel() {
241 + //         try {
242 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
243 + //                 .matcher(new String(
244 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
245 + //             matcher.find();
246 + //             return matcher.group(1);
247 + //         } catch (Exception ex) { return null; }
248 + //     }
249 +
250 +    public void runBare() throws Throwable {
251 +        currentTestCase = this;
252 +        if (methodFilter == null
253 +            || methodFilter.matcher(toString()).find())
254 +            super.runBare();
255 +    }
256 +
257      protected void runTest() throws Throwable {
258 <        if (profileTests)
259 <            runTestProfiled();
260 <        else
261 <            super.runTest();
258 >        for (int i = 0; i < runsPerTest; i++) {
259 >            // currentRun = i;
260 >            if (profileTests)
261 >                runTestProfiled();
262 >            else
263 >                super.runTest();
264 >        }
265      }
266  
267      protected void runTestProfiled() throws Throwable {
268 <        long t0 = System.nanoTime();
269 <        try {
268 >        for (int i = 0; i < 2; i++) {
269 >            long startTime = System.nanoTime();
270              super.runTest();
271 <        } finally {
272 <            long elapsedMillis =
273 <                (System.nanoTime() - t0) / (1000L * 1000L);
274 <            if (elapsedMillis >= profileThreshold)
271 >            long elapsedMillis = millisElapsedSince(startTime);
272 >            if (elapsedMillis < profileThreshold)
273 >                break;
274 >            // Never report first run of any test; treat it as a
275 >            // warmup run, notably to trigger all needed classloading,
276 >            if (i > 0)
277                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
278          }
279      }
280  
281      /**
282 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
282 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
283       */
284      public static void main(String[] args) {
285 +        main(suite(), args);
286 +    }
287 +
288 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
289 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
290 +        long runTime;
291 +        public void startTest(Test test) {}
292 +        protected void printHeader(long runTime) {
293 +            this.runTime = runTime; // defer printing for later
294 +        }
295 +        protected void printFooter(TestResult result) {
296 +            if (result.wasSuccessful()) {
297 +                getWriter().println("OK (" + result.runCount() + " tests)"
298 +                    + "  Time: " + elapsedTimeAsString(runTime));
299 +            } else {
300 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
301 +                super.printFooter(result);
302 +            }
303 +        }
304 +    }
305 +
306 +    /**
307 +     * Returns a TestRunner that doesn't bother with unnecessary
308 +     * fluff, like printing a "." for each test case.
309 +     */
310 +    static junit.textui.TestRunner newPithyTestRunner() {
311 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
312 +        runner.setPrinter(new PithyResultPrinter(System.out));
313 +        return runner;
314 +    }
315 +
316 +    /**
317 +     * Runs all unit tests in the given test suite.
318 +     * Actual behavior influenced by jsr166.* system properties.
319 +     */
320 +    static void main(Test suite, String[] args) {
321          if (useSecurityManager) {
322              System.err.println("Setting a permissive security manager");
323              Policy.setPolicy(permissivePolicy());
324              System.setSecurityManager(new SecurityManager());
325          }
326 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
327 <
328 <        Test s = suite();
329 <        for (int i = 0; i < iters; ++i) {
155 <            junit.textui.TestRunner.run(s);
326 >        for (int i = 0; i < suiteRuns; i++) {
327 >            TestResult result = newPithyTestRunner().doRun(suite);
328 >            if (!result.wasSuccessful())
329 >                System.exit(1);
330              System.gc();
331              System.runFinalization();
332          }
159        System.exit(0);
333      }
334  
335      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 172 | Line 345 | public class JSR166TestCase extends Test
345          return suite;
346      }
347  
348 +    public static void addNamedTestClasses(TestSuite suite,
349 +                                           String... testClassNames) {
350 +        for (String testClassName : testClassNames) {
351 +            try {
352 +                Class<?> testClass = Class.forName(testClassName);
353 +                Method m = testClass.getDeclaredMethod("suite",
354 +                                                       new Class<?>[0]);
355 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
356 +            } catch (Exception e) {
357 +                throw new Error("Missing test class", e);
358 +            }
359 +        }
360 +    }
361 +
362 +    public static final double JAVA_CLASS_VERSION;
363 +    public static final String JAVA_SPECIFICATION_VERSION;
364 +    static {
365 +        try {
366 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
367 +                new java.security.PrivilegedAction<Double>() {
368 +                public Double run() {
369 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
370 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
371 +                new java.security.PrivilegedAction<String>() {
372 +                public String run() {
373 +                    return System.getProperty("java.specification.version");}});
374 +        } catch (Throwable t) {
375 +            throw new Error(t);
376 +        }
377 +    }
378 +
379 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
380 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
381 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
382 +    public static boolean atLeastJava9() {
383 +        return JAVA_CLASS_VERSION >= 53.0
384 +            // As of 2015-09, java9 still uses 52.0 class file version
385 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
386 +    }
387 +    public static boolean atLeastJava10() {
388 +        return JAVA_CLASS_VERSION >= 54.0
389 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
390 +    }
391 +
392      /**
393       * Collects all JSR166 unit tests as one suite.
394       */
395      public static Test suite() {
396 <        return newTestSuite(
396 >        // Java7+ test classes
397 >        TestSuite suite = newTestSuite(
398              ForkJoinPoolTest.suite(),
399              ForkJoinTaskTest.suite(),
400              RecursiveActionTest.suite(),
# Line 241 | Line 459 | public class JSR166TestCase extends Test
459              TreeSetTest.suite(),
460              TreeSubMapTest.suite(),
461              TreeSubSetTest.suite());
462 +
463 +        // Java8+ test classes
464 +        if (atLeastJava8()) {
465 +            String[] java8TestClassNames = {
466 +                "Atomic8Test",
467 +                "CompletableFutureTest",
468 +                "ConcurrentHashMap8Test",
469 +                "CountedCompleterTest",
470 +                "DoubleAccumulatorTest",
471 +                "DoubleAdderTest",
472 +                "ForkJoinPool8Test",
473 +                "ForkJoinTask8Test",
474 +                "LongAccumulatorTest",
475 +                "LongAdderTest",
476 +                "SplittableRandomTest",
477 +                "StampedLockTest",
478 +                "SubmissionPublisherTest",
479 +                "ThreadLocalRandom8Test",
480 +            };
481 +            addNamedTestClasses(suite, java8TestClassNames);
482 +        }
483 +
484 +        // Java9+ test classes
485 +        if (atLeastJava9()) {
486 +            String[] java9TestClassNames = {
487 +                // Currently empty, but expecting varhandle tests
488 +            };
489 +            addNamedTestClasses(suite, java9TestClassNames);
490 +        }
491 +
492 +        return suite;
493 +    }
494 +
495 +    /** Returns list of junit-style test method names in given class. */
496 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
497 +        Method[] methods = testClass.getDeclaredMethods();
498 +        ArrayList<String> names = new ArrayList<String>(methods.length);
499 +        for (Method method : methods) {
500 +            if (method.getName().startsWith("test")
501 +                && Modifier.isPublic(method.getModifiers())
502 +                // method.getParameterCount() requires jdk8+
503 +                && method.getParameterTypes().length == 0) {
504 +                names.add(method.getName());
505 +            }
506 +        }
507 +        return names;
508      }
509  
510 +    /**
511 +     * Returns junit-style testSuite for the given test class, but
512 +     * parameterized by passing extra data to each test.
513 +     */
514 +    public static <ExtraData> Test parameterizedTestSuite
515 +        (Class<? extends JSR166TestCase> testClass,
516 +         Class<ExtraData> dataClass,
517 +         ExtraData data) {
518 +        try {
519 +            TestSuite suite = new TestSuite();
520 +            Constructor c =
521 +                testClass.getDeclaredConstructor(dataClass, String.class);
522 +            for (String methodName : testMethodNames(testClass))
523 +                suite.addTest((Test) c.newInstance(data, methodName));
524 +            return suite;
525 +        } catch (Exception e) {
526 +            throw new Error(e);
527 +        }
528 +    }
529 +
530 +    /**
531 +     * Returns junit-style testSuite for the jdk8 extension of the
532 +     * given test class, but parameterized by passing extra data to
533 +     * each test.  Uses reflection to allow compilation in jdk7.
534 +     */
535 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
536 +        (Class<? extends JSR166TestCase> testClass,
537 +         Class<ExtraData> dataClass,
538 +         ExtraData data) {
539 +        if (atLeastJava8()) {
540 +            String name = testClass.getName();
541 +            String name8 = name.replaceAll("Test$", "8Test");
542 +            if (name.equals(name8)) throw new Error(name);
543 +            try {
544 +                return (Test)
545 +                    Class.forName(name8)
546 +                    .getMethod("testSuite", new Class[] { dataClass })
547 +                    .invoke(null, data);
548 +            } catch (Exception e) {
549 +                throw new Error(e);
550 +            }
551 +        } else {
552 +            return new TestSuite();
553 +        }
554 +    }
555 +
556 +    // Delays for timing-dependent tests, in milliseconds.
557  
558      public static long SHORT_DELAY_MS;
559      public static long SMALL_DELAY_MS;
560      public static long MEDIUM_DELAY_MS;
561      public static long LONG_DELAY_MS;
562  
252
563      /**
564 <     * Returns the shortest timed delay. This could
565 <     * be reimplemented to use for example a Property.
564 >     * Returns the shortest timed delay. This can be scaled up for
565 >     * slow machines using the jsr166.delay.factor system property.
566       */
567      protected long getShortDelay() {
568 <        return 50;
568 >        return 50 * delayFactor;
569      }
570  
261
571      /**
572       * Sets delays as multiples of SHORT_DELAY.
573       */
# Line 270 | Line 579 | public class JSR166TestCase extends Test
579      }
580  
581      /**
582 +     * Returns a timeout in milliseconds to be used in tests that
583 +     * verify that operations block or time out.
584 +     */
585 +    long timeoutMillis() {
586 +        return SHORT_DELAY_MS / 4;
587 +    }
588 +
589 +    /**
590 +     * Returns a new Date instance representing a time at least
591 +     * delayMillis milliseconds in the future.
592 +     */
593 +    Date delayedDate(long delayMillis) {
594 +        // Add 1 because currentTimeMillis is known to round into the past.
595 +        return new Date(System.currentTimeMillis() + delayMillis + 1);
596 +    }
597 +
598 +    /**
599       * The first exception encountered if any threadAssertXXX method fails.
600       */
601      private final AtomicReference<Throwable> threadFailure
# Line 282 | Line 608 | public class JSR166TestCase extends Test
608       * the same test have no effect.
609       */
610      public void threadRecordFailure(Throwable t) {
611 +        System.err.println(t);
612 +        dumpTestThreads();
613          threadFailure.compareAndSet(null, t);
614      }
615  
# Line 289 | Line 617 | public class JSR166TestCase extends Test
617          setDelays();
618      }
619  
620 +    void tearDownFail(String format, Object... args) {
621 +        String msg = toString() + ": " + String.format(format, args);
622 +        System.err.println(msg);
623 +        dumpTestThreads();
624 +        throw new AssertionFailedError(msg);
625 +    }
626 +
627      /**
628 +     * Extra checks that get done for all test cases.
629 +     *
630       * Triggers test case failure if any thread assertions have failed,
631       * by rethrowing, in the test harness thread, any exception recorded
632       * earlier by threadRecordFailure.
633 +     *
634 +     * Triggers test case failure if interrupt status is set in the main thread.
635       */
636      public void tearDown() throws Exception {
637          Throwable t = threadFailure.getAndSet(null);
# Line 310 | Line 649 | public class JSR166TestCase extends Test
649                  throw afe;
650              }
651          }
652 +
653 +        if (Thread.interrupted())
654 +            tearDownFail("interrupt status set in main thread");
655 +
656 +        checkForkJoinPoolThreadLeaks();
657 +    }
658 +
659 +    /**
660 +     * Finds missing PoolCleaners
661 +     */
662 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
663 +        Thread[] survivors = new Thread[7];
664 +        int count = Thread.enumerate(survivors);
665 +        for (int i = 0; i < count; i++) {
666 +            Thread thread = survivors[i];
667 +            String name = thread.getName();
668 +            if (name.startsWith("ForkJoinPool-")) {
669 +                // give thread some time to terminate
670 +                thread.join(LONG_DELAY_MS);
671 +                if (thread.isAlive())
672 +                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
673 +                                 thread);
674 +            }
675 +        }
676 +
677 +        if (!ForkJoinPool.commonPool()
678 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
679 +            tearDownFail("ForkJoin common pool thread stuck");
680      }
681  
682      /**
# Line 322 | Line 689 | public class JSR166TestCase extends Test
689              fail(reason);
690          } catch (AssertionFailedError t) {
691              threadRecordFailure(t);
692 <            fail(reason);
692 >            throw t;
693          }
694      }
695  
# Line 390 | Line 757 | public class JSR166TestCase extends Test
757      public void threadAssertEquals(Object x, Object y) {
758          try {
759              assertEquals(x, y);
760 <        } catch (AssertionFailedError t) {
761 <            threadRecordFailure(t);
762 <            throw t;
763 <        } catch (Throwable t) {
764 <            threadUnexpectedException(t);
760 >        } catch (AssertionFailedError fail) {
761 >            threadRecordFailure(fail);
762 >            throw fail;
763 >        } catch (Throwable fail) {
764 >            threadUnexpectedException(fail);
765          }
766      }
767  
# Line 406 | Line 773 | public class JSR166TestCase extends Test
773      public void threadAssertSame(Object x, Object y) {
774          try {
775              assertSame(x, y);
776 <        } catch (AssertionFailedError t) {
777 <            threadRecordFailure(t);
778 <            throw t;
776 >        } catch (AssertionFailedError fail) {
777 >            threadRecordFailure(fail);
778 >            throw fail;
779          }
780      }
781  
# Line 441 | Line 808 | public class JSR166TestCase extends Test
808          else {
809              AssertionFailedError afe =
810                  new AssertionFailedError("unexpected exception: " + t);
811 <            t.initCause(t);
811 >            afe.initCause(t);
812              throw afe;
813          }
814      }
815  
816      /**
817 <     * Delays, via Thread.sleep for the given millisecond delay, but
817 >     * Delays, via Thread.sleep, for the given millisecond delay, but
818       * if the sleep is shorter than specified, may re-sleep or yield
819 <     * until time elapses.
819 >     * until time elapses.  Ensures that the given time, as measured
820 >     * by System.nanoTime(), has elapsed.
821       */
822 <    public static void delay(long millis) throws InterruptedException {
823 <        long startTime = System.nanoTime();
824 <        long ns = millis * 1000 * 1000;
825 <        for (;;) {
822 >    static void delay(long millis) throws InterruptedException {
823 >        long nanos = millis * (1000 * 1000);
824 >        final long wakeupTime = System.nanoTime() + nanos;
825 >        do {
826              if (millis > 0L)
827                  Thread.sleep(millis);
828              else // too short to sleep
829                  Thread.yield();
830 <            long d = ns - (System.nanoTime() - startTime);
831 <            if (d > 0L)
832 <                millis = d / (1000 * 1000);
833 <            else
834 <                break;
830 >            nanos = wakeupTime - System.nanoTime();
831 >            millis = nanos / (1000 * 1000);
832 >        } while (nanos >= 0L);
833 >    }
834 >
835 >    /**
836 >     * Allows use of try-with-resources with per-test thread pools.
837 >     */
838 >    class PoolCleaner implements AutoCloseable {
839 >        private final ExecutorService pool;
840 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
841 >        public void close() { joinPool(pool); }
842 >    }
843 >
844 >    /**
845 >     * An extension of PoolCleaner that has an action to release the pool.
846 >     */
847 >    class PoolCleanerWithReleaser extends PoolCleaner {
848 >        private final Runnable releaser;
849 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
850 >            super(pool);
851 >            this.releaser = releaser;
852 >        }
853 >        public void close() {
854 >            try {
855 >                releaser.run();
856 >            } finally {
857 >                super.close();
858 >            }
859          }
860      }
861  
862 +    PoolCleaner cleaner(ExecutorService pool) {
863 +        return new PoolCleaner(pool);
864 +    }
865 +
866 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
867 +        return new PoolCleanerWithReleaser(pool, releaser);
868 +    }
869 +
870 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
871 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
872 +    }
873 +
874 +    Runnable releaser(final CountDownLatch latch) {
875 +        return new Runnable() { public void run() {
876 +            do { latch.countDown(); }
877 +            while (latch.getCount() > 0);
878 +        }};
879 +    }
880 +
881      /**
882       * Waits out termination of a thread pool or fails doing so.
883       */
884 <    public void joinPool(ExecutorService exec) {
884 >    void joinPool(ExecutorService pool) {
885          try {
886 <            exec.shutdown();
887 <            assertTrue("ExecutorService did not terminate in a timely manner",
888 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
886 >            pool.shutdown();
887 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
888 >                try {
889 >                    threadFail("ExecutorService " + pool +
890 >                               " did not terminate in a timely manner");
891 >                } finally {
892 >                    // last resort, for the benefit of subsequent tests
893 >                    pool.shutdownNow();
894 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
895 >                }
896 >            }
897          } catch (SecurityException ok) {
898              // Allowed in case test doesn't have privs
899 <        } catch (InterruptedException ie) {
900 <            fail("Unexpected InterruptedException");
899 >        } catch (InterruptedException fail) {
900 >            threadFail("Unexpected InterruptedException");
901          }
902      }
903  
904 +    /** Like Runnable, but with the freedom to throw anything */
905 +    interface Action { public void run() throws Throwable; }
906 +
907 +    /**
908 +     * Runs all the given actions in parallel, failing if any fail.
909 +     * Useful for running multiple variants of tests that are
910 +     * necessarily individually slow because they must block.
911 +     */
912 +    void testInParallel(Action ... actions) {
913 +        ExecutorService pool = Executors.newCachedThreadPool();
914 +        try (PoolCleaner cleaner = cleaner(pool)) {
915 +            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
916 +            for (final Action action : actions)
917 +                futures.add(pool.submit(new CheckedRunnable() {
918 +                    public void realRun() throws Throwable { action.run();}}));
919 +            for (Future<?> future : futures)
920 +                try {
921 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
922 +                } catch (ExecutionException ex) {
923 +                    threadUnexpectedException(ex.getCause());
924 +                } catch (Exception ex) {
925 +                    threadUnexpectedException(ex);
926 +                }
927 +        }
928 +    }
929 +
930 +    /**
931 +     * A debugging tool to print stack traces of most threads, as jstack does.
932 +     * Uninteresting threads are filtered out.
933 +     */
934 +    static void dumpTestThreads() {
935 +        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
936 +        System.err.println("------ stacktrace dump start ------");
937 +        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
938 +            String name = info.getThreadName();
939 +            if ("Signal Dispatcher".equals(name))
940 +                continue;
941 +            if ("Reference Handler".equals(name)
942 +                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
943 +                continue;
944 +            if ("Finalizer".equals(name)
945 +                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
946 +                continue;
947 +            if ("checkForWedgedTest".equals(name))
948 +                continue;
949 +            System.err.print(info);
950 +        }
951 +        System.err.println("------ stacktrace dump end ------");
952 +    }
953 +
954 +    /**
955 +     * Checks that thread does not terminate within the default
956 +     * millisecond delay of {@code timeoutMillis()}.
957 +     */
958 +    void assertThreadStaysAlive(Thread thread) {
959 +        assertThreadStaysAlive(thread, timeoutMillis());
960 +    }
961 +
962      /**
963       * Checks that thread does not terminate within the given millisecond delay.
964       */
965 <    public void assertThreadStaysAlive(Thread thread, long millis) {
965 >    void assertThreadStaysAlive(Thread thread, long millis) {
966          try {
967              // No need to optimize the failing case via Thread.join.
968              delay(millis);
969              assertTrue(thread.isAlive());
970 <        } catch (InterruptedException ie) {
971 <            fail("Unexpected InterruptedException");
970 >        } catch (InterruptedException fail) {
971 >            threadFail("Unexpected InterruptedException");
972 >        }
973 >    }
974 >
975 >    /**
976 >     * Checks that the threads do not terminate within the default
977 >     * millisecond delay of {@code timeoutMillis()}.
978 >     */
979 >    void assertThreadsStayAlive(Thread... threads) {
980 >        assertThreadsStayAlive(timeoutMillis(), threads);
981 >    }
982 >
983 >    /**
984 >     * Checks that the threads do not terminate within the given millisecond delay.
985 >     */
986 >    void assertThreadsStayAlive(long millis, Thread... threads) {
987 >        try {
988 >            // No need to optimize the failing case via Thread.join.
989 >            delay(millis);
990 >            for (Thread thread : threads)
991 >                assertTrue(thread.isAlive());
992 >        } catch (InterruptedException fail) {
993 >            threadFail("Unexpected InterruptedException");
994          }
995      }
996  
997      /**
998 +     * Checks that future.get times out, with the default timeout of
999 +     * {@code timeoutMillis()}.
1000 +     */
1001 +    void assertFutureTimesOut(Future future) {
1002 +        assertFutureTimesOut(future, timeoutMillis());
1003 +    }
1004 +
1005 +    /**
1006 +     * Checks that future.get times out, with the given millisecond timeout.
1007 +     */
1008 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
1009 +        long startTime = System.nanoTime();
1010 +        try {
1011 +            future.get(timeoutMillis, MILLISECONDS);
1012 +            shouldThrow();
1013 +        } catch (TimeoutException success) {
1014 +        } catch (Exception fail) {
1015 +            threadUnexpectedException(fail);
1016 +        } finally { future.cancel(true); }
1017 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1018 +    }
1019 +
1020 +    /**
1021       * Fails with message "should throw exception".
1022       */
1023      public void shouldThrow() {
# Line 534 | Line 1056 | public class JSR166TestCase extends Test
1056      public static final Integer m6  = new Integer(-6);
1057      public static final Integer m10 = new Integer(-10);
1058  
537
1059      /**
1060       * Runs Runnable r with a security policy that permits precisely
1061       * the specified permissions.  If there is no current security
# Line 546 | Line 1067 | public class JSR166TestCase extends Test
1067          SecurityManager sm = System.getSecurityManager();
1068          if (sm == null) {
1069              r.run();
1070 +        }
1071 +        runWithSecurityManagerWithPermissions(r, permissions);
1072 +    }
1073 +
1074 +    /**
1075 +     * Runs Runnable r with a security policy that permits precisely
1076 +     * the specified permissions.  If there is no current security
1077 +     * manager, a temporary one is set for the duration of the
1078 +     * Runnable.  We require that any security manager permit
1079 +     * getPolicy/setPolicy.
1080 +     */
1081 +    public void runWithSecurityManagerWithPermissions(Runnable r,
1082 +                                                      Permission... permissions) {
1083 +        SecurityManager sm = System.getSecurityManager();
1084 +        if (sm == null) {
1085              Policy savedPolicy = Policy.getPolicy();
1086              try {
1087                  Policy.setPolicy(permissivePolicy());
1088                  System.setSecurityManager(new SecurityManager());
1089 <                runWithPermissions(r, permissions);
1089 >                runWithSecurityManagerWithPermissions(r, permissions);
1090              } finally {
1091                  System.setSecurityManager(null);
1092                  Policy.setPolicy(savedPolicy);
# Line 598 | Line 1134 | public class JSR166TestCase extends Test
1134              return perms.implies(p);
1135          }
1136          public void refresh() {}
1137 +        public String toString() {
1138 +            List<Permission> ps = new ArrayList<Permission>();
1139 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1140 +                ps.add(e.nextElement());
1141 +            return "AdjustablePolicy with permissions " + ps;
1142 +        }
1143      }
1144  
1145      /**
# Line 626 | Line 1168 | public class JSR166TestCase extends Test
1168      void sleep(long millis) {
1169          try {
1170              delay(millis);
1171 <        } catch (InterruptedException ie) {
1171 >        } catch (InterruptedException fail) {
1172              AssertionFailedError afe =
1173                  new AssertionFailedError("Unexpected InterruptedException");
1174 <            afe.initCause(ie);
1174 >            afe.initCause(fail);
1175              throw afe;
1176          }
1177      }
1178  
1179      /**
1180 <     * Sleeps until the timeout has elapsed, or interrupted.
639 <     * Does <em>NOT</em> throw InterruptedException.
640 <     */
641 <    void sleepTillInterrupted(long timeoutMillis) {
642 <        try {
643 <            Thread.sleep(timeoutMillis);
644 <        } catch (InterruptedException wakeup) {}
645 <    }
646 <
647 <    /**
648 <     * Waits up to the specified number of milliseconds for the given
1180 >     * Spin-waits up to the specified number of milliseconds for the given
1181       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1182       */
1183      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1184 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
653 <        long t0 = System.nanoTime();
1184 >        long startTime = System.nanoTime();
1185          for (;;) {
1186              Thread.State s = thread.getState();
1187              if (s == Thread.State.BLOCKED ||
# Line 659 | Line 1190 | public class JSR166TestCase extends Test
1190                  return;
1191              else if (s == Thread.State.TERMINATED)
1192                  fail("Unexpected thread termination");
1193 <            else if (System.nanoTime() - t0 > timeoutNanos) {
1193 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1194                  threadAssertTrue(thread.isAlive());
1195                  return;
1196              }
# Line 678 | Line 1209 | public class JSR166TestCase extends Test
1209      /**
1210       * Returns the number of milliseconds since time given by
1211       * startNanoTime, which must have been previously returned from a
1212 <     * call to {@link System.nanoTime()}.
1212 >     * call to {@link System#nanoTime()}.
1213       */
1214 <    long millisElapsedSince(long startNanoTime) {
1214 >    static long millisElapsedSince(long startNanoTime) {
1215          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1216      }
1217  
1218 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1219 + //         long startTime = System.nanoTime();
1220 + //         try {
1221 + //             r.run();
1222 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1223 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1224 + //             throw new AssertionFailedError("did not return promptly");
1225 + //     }
1226 +
1227 + //     void assertTerminatesPromptly(Runnable r) {
1228 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1229 + //     }
1230 +
1231 +    /**
1232 +     * Checks that timed f.get() returns the expected value, and does not
1233 +     * wait for the timeout to elapse before returning.
1234 +     */
1235 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1236 +        long startTime = System.nanoTime();
1237 +        try {
1238 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1239 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1240 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1241 +            throw new AssertionFailedError("timed get did not return promptly");
1242 +    }
1243 +
1244 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1245 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1246 +    }
1247 +
1248      /**
1249       * Returns a new started daemon Thread running the given runnable.
1250       */
# Line 702 | Line 1263 | public class JSR166TestCase extends Test
1263      void awaitTermination(Thread t, long timeoutMillis) {
1264          try {
1265              t.join(timeoutMillis);
1266 <        } catch (InterruptedException ie) {
1267 <            threadUnexpectedException(ie);
1266 >        } catch (InterruptedException fail) {
1267 >            threadUnexpectedException(fail);
1268          } finally {
1269 <            if (t.isAlive()) {
1269 >            if (t.getState() != Thread.State.TERMINATED) {
1270                  t.interrupt();
1271 <                fail("Test timed out");
1271 >                threadFail("timed out waiting for thread to terminate");
1272              }
1273          }
1274      }
# Line 729 | Line 1290 | public class JSR166TestCase extends Test
1290          public final void run() {
1291              try {
1292                  realRun();
1293 <            } catch (Throwable t) {
1294 <                threadUnexpectedException(t);
1293 >            } catch (Throwable fail) {
1294 >                threadUnexpectedException(fail);
1295              }
1296          }
1297      }
# Line 783 | Line 1344 | public class JSR166TestCase extends Test
1344                  realRun();
1345                  threadShouldThrow("InterruptedException");
1346              } catch (InterruptedException success) {
1347 <            } catch (Throwable t) {
1348 <                threadUnexpectedException(t);
1347 >                threadAssertFalse(Thread.interrupted());
1348 >            } catch (Throwable fail) {
1349 >                threadUnexpectedException(fail);
1350              }
1351          }
1352      }
# Line 795 | Line 1357 | public class JSR166TestCase extends Test
1357          public final T call() {
1358              try {
1359                  return realCall();
1360 <            } catch (Throwable t) {
1361 <                threadUnexpectedException(t);
1360 >            } catch (Throwable fail) {
1361 >                threadUnexpectedException(fail);
1362                  return null;
1363              }
1364          }
# Line 812 | Line 1374 | public class JSR166TestCase extends Test
1374                  threadShouldThrow("InterruptedException");
1375                  return result;
1376              } catch (InterruptedException success) {
1377 <            } catch (Throwable t) {
1378 <                threadUnexpectedException(t);
1377 >                threadAssertFalse(Thread.interrupted());
1378 >            } catch (Throwable fail) {
1379 >                threadUnexpectedException(fail);
1380              }
1381              return null;
1382          }
# Line 830 | Line 1393 | public class JSR166TestCase extends Test
1393      public static final String TEST_STRING = "a test string";
1394  
1395      public static class StringTask implements Callable<String> {
1396 <        public String call() { return TEST_STRING; }
1396 >        final String value;
1397 >        public StringTask() { this(TEST_STRING); }
1398 >        public StringTask(String value) { this.value = value; }
1399 >        public String call() { return value; }
1400      }
1401  
1402      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 843 | Line 1409 | public class JSR166TestCase extends Test
1409              }};
1410      }
1411  
1412 <    public Runnable awaiter(final CountDownLatch latch) {
1412 >    public Runnable countDowner(final CountDownLatch latch) {
1413          return new CheckedRunnable() {
1414              public void realRun() throws InterruptedException {
1415 <                await(latch);
1415 >                latch.countDown();
1416              }};
1417      }
1418  
1419 +    class LatchAwaiter extends CheckedRunnable {
1420 +        static final int NEW = 0;
1421 +        static final int RUNNING = 1;
1422 +        static final int DONE = 2;
1423 +        final CountDownLatch latch;
1424 +        int state = NEW;
1425 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1426 +        public void realRun() throws InterruptedException {
1427 +            state = 1;
1428 +            await(latch);
1429 +            state = 2;
1430 +        }
1431 +    }
1432 +
1433 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1434 +        return new LatchAwaiter(latch);
1435 +    }
1436 +
1437      public void await(CountDownLatch latch) {
1438          try {
1439 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1440 <        } catch (Throwable t) {
1441 <            threadUnexpectedException(t);
1439 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1440 >                fail("timed out waiting for CountDownLatch for "
1441 >                     + (LONG_DELAY_MS/1000) + " sec");
1442 >        } catch (Throwable fail) {
1443 >            threadUnexpectedException(fail);
1444 >        }
1445 >    }
1446 >
1447 >    public void await(Semaphore semaphore) {
1448 >        try {
1449 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1450 >                fail("timed out waiting for Semaphore for "
1451 >                     + (LONG_DELAY_MS/1000) + " sec");
1452 >        } catch (Throwable fail) {
1453 >            threadUnexpectedException(fail);
1454          }
1455      }
1456  
1457 + //     /**
1458 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1459 + //      */
1460 + //     public void await(AtomicBoolean flag) {
1461 + //         await(flag, LONG_DELAY_MS);
1462 + //     }
1463 +
1464 + //     /**
1465 + //      * Spin-waits up to the specified timeout until flag becomes true.
1466 + //      */
1467 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1468 + //         long startTime = System.nanoTime();
1469 + //         while (!flag.get()) {
1470 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1471 + //                 throw new AssertionFailedError("timed out");
1472 + //             Thread.yield();
1473 + //         }
1474 + //     }
1475 +
1476      public static class NPETask implements Callable<String> {
1477          public String call() { throw new NullPointerException(); }
1478      }
# Line 1026 | Line 1641 | public class JSR166TestCase extends Test
1641      public abstract class CheckedRecursiveAction extends RecursiveAction {
1642          protected abstract void realCompute() throws Throwable;
1643  
1644 <        public final void compute() {
1644 >        @Override protected final void compute() {
1645              try {
1646                  realCompute();
1647 <            } catch (Throwable t) {
1648 <                threadUnexpectedException(t);
1647 >            } catch (Throwable fail) {
1648 >                threadUnexpectedException(fail);
1649              }
1650          }
1651      }
# Line 1041 | Line 1656 | public class JSR166TestCase extends Test
1656      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1657          protected abstract T realCompute() throws Throwable;
1658  
1659 <        public final T compute() {
1659 >        @Override protected final T compute() {
1660              try {
1661                  return realCompute();
1662 <            } catch (Throwable t) {
1663 <                threadUnexpectedException(t);
1662 >            } catch (Throwable fail) {
1663 >                threadUnexpectedException(fail);
1664                  return null;
1665              }
1666          }
# Line 1060 | Line 1675 | public class JSR166TestCase extends Test
1675      }
1676  
1677      /**
1678 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1679 <     * of throwing checked exceptions.
1678 >     * A CyclicBarrier that uses timed await and fails with
1679 >     * AssertionFailedErrors instead of throwing checked exceptions.
1680       */
1681      public class CheckedBarrier extends CyclicBarrier {
1682          public CheckedBarrier(int parties) { super(parties); }
1683  
1684          public int await() {
1685              try {
1686 <                return super.await();
1687 <            } catch (Exception e) {
1686 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1687 >            } catch (TimeoutException timedOut) {
1688 >                throw new AssertionFailedError("timed out");
1689 >            } catch (Exception fail) {
1690                  AssertionFailedError afe =
1691 <                    new AssertionFailedError("Unexpected exception: " + e);
1692 <                afe.initCause(e);
1691 >                    new AssertionFailedError("Unexpected exception: " + fail);
1692 >                afe.initCause(fail);
1693                  throw afe;
1694              }
1695          }
1696      }
1697  
1698 <    public void checkEmpty(BlockingQueue q) {
1698 >    void checkEmpty(BlockingQueue q) {
1699          try {
1700              assertTrue(q.isEmpty());
1701              assertEquals(0, q.size());
# Line 1100 | Line 1717 | public class JSR166TestCase extends Test
1717                  q.remove();
1718                  shouldThrow();
1719              } catch (NoSuchElementException success) {}
1720 <        } catch (InterruptedException ie) {
1104 <            threadUnexpectedException(ie);
1105 <        }
1720 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1721      }
1722  
1723 <    @SuppressWarnings("unchecked")
1724 <    public <T> T serialClone(T o) {
1723 >    void assertSerialEquals(Object x, Object y) {
1724 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1725 >    }
1726 >
1727 >    void assertNotSerialEquals(Object x, Object y) {
1728 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1729 >    }
1730 >
1731 >    byte[] serialBytes(Object o) {
1732          try {
1733              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1734              ObjectOutputStream oos = new ObjectOutputStream(bos);
1735              oos.writeObject(o);
1736              oos.flush();
1737              oos.close();
1738 <            ByteArrayInputStream bin =
1739 <                new ByteArrayInputStream(bos.toByteArray());
1740 <            ObjectInputStream ois = new ObjectInputStream(bin);
1741 <            return (T) ois.readObject();
1742 <        } catch (Throwable t) {
1743 <            threadUnexpectedException(t);
1738 >            return bos.toByteArray();
1739 >        } catch (Throwable fail) {
1740 >            threadUnexpectedException(fail);
1741 >            return new byte[0];
1742 >        }
1743 >    }
1744 >
1745 >    @SuppressWarnings("unchecked")
1746 >    <T> T serialClone(T o) {
1747 >        try {
1748 >            ObjectInputStream ois = new ObjectInputStream
1749 >                (new ByteArrayInputStream(serialBytes(o)));
1750 >            T clone = (T) ois.readObject();
1751 >            assertSame(o.getClass(), clone.getClass());
1752 >            return clone;
1753 >        } catch (Throwable fail) {
1754 >            threadUnexpectedException(fail);
1755              return null;
1756          }
1757      }
1758 +
1759 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1760 +                             Runnable... throwingActions) {
1761 +        for (Runnable throwingAction : throwingActions) {
1762 +            boolean threw = false;
1763 +            try { throwingAction.run(); }
1764 +            catch (Throwable t) {
1765 +                threw = true;
1766 +                if (!expectedExceptionClass.isInstance(t)) {
1767 +                    AssertionFailedError afe =
1768 +                        new AssertionFailedError
1769 +                        ("Expected " + expectedExceptionClass.getName() +
1770 +                         ", got " + t.getClass().getName());
1771 +                    afe.initCause(t);
1772 +                    threadUnexpectedException(afe);
1773 +                }
1774 +            }
1775 +            if (!threw)
1776 +                shouldThrow(expectedExceptionClass.getName());
1777 +        }
1778 +    }
1779 +
1780 +    public void assertIteratorExhausted(Iterator<?> it) {
1781 +        try {
1782 +            it.next();
1783 +            shouldThrow();
1784 +        } catch (NoSuchElementException success) {}
1785 +        assertFalse(it.hasNext());
1786 +    }
1787   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines