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.83 by jsr166, Fri May 27 19:29:59 2011 UTC vs.
Revision 1.193 by jsr166, Mon May 23 18:19:48 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 > * @modules java.management
13 > * @build *
14 > * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
15 > */
16 >
17 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
18 > import static java.util.concurrent.TimeUnit.MINUTES;
19 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
20 >
21   import java.io.ByteArrayInputStream;
22   import java.io.ByteArrayOutputStream;
23   import java.io.ObjectInputStream;
24   import java.io.ObjectOutputStream;
25 < import java.util.Arrays;
26 < import java.util.Date;
27 < import java.util.NoSuchElementException;
28 < import java.util.PropertyPermission;
29 < import java.util.concurrent.*;
30 < import java.util.concurrent.atomic.AtomicBoolean;
31 < import java.util.concurrent.atomic.AtomicReference;
32 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
25 > import java.lang.management.ManagementFactory;
26 > import java.lang.management.ThreadInfo;
27 > import java.lang.management.ThreadMXBean;
28 > import java.lang.reflect.Constructor;
29 > import java.lang.reflect.Method;
30 > import java.lang.reflect.Modifier;
31 > import java.nio.file.Files;
32 > import java.nio.file.Paths;
33   import java.security.CodeSource;
34   import java.security.Permission;
35   import java.security.PermissionCollection;
# Line 27 | Line 37 | import java.security.Permissions;
37   import java.security.Policy;
38   import java.security.ProtectionDomain;
39   import java.security.SecurityPermission;
40 + import java.util.ArrayList;
41 + import java.util.Arrays;
42 + import java.util.Date;
43 + import java.util.Enumeration;
44 + import java.util.Iterator;
45 + import java.util.List;
46 + import java.util.NoSuchElementException;
47 + import java.util.PropertyPermission;
48 + import java.util.concurrent.BlockingQueue;
49 + import java.util.concurrent.Callable;
50 + import java.util.concurrent.CountDownLatch;
51 + import java.util.concurrent.CyclicBarrier;
52 + import java.util.concurrent.ExecutionException;
53 + import java.util.concurrent.Executors;
54 + import java.util.concurrent.ExecutorService;
55 + import java.util.concurrent.ForkJoinPool;
56 + import java.util.concurrent.Future;
57 + import java.util.concurrent.RecursiveAction;
58 + import java.util.concurrent.RecursiveTask;
59 + import java.util.concurrent.RejectedExecutionHandler;
60 + import java.util.concurrent.Semaphore;
61 + import java.util.concurrent.SynchronousQueue;
62 + import java.util.concurrent.ThreadFactory;
63 + import java.util.concurrent.ThreadPoolExecutor;
64 + import java.util.concurrent.TimeoutException;
65 + import java.util.concurrent.atomic.AtomicBoolean;
66 + import java.util.concurrent.atomic.AtomicReference;
67 + import java.util.regex.Matcher;
68 + import java.util.regex.Pattern;
69 +
70 + import junit.framework.AssertionFailedError;
71 + import junit.framework.Test;
72 + import junit.framework.TestCase;
73 + import junit.framework.TestResult;
74 + import junit.framework.TestSuite;
75  
76   /**
77   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 38 | Line 83 | import java.security.SecurityPermission;
83   *
84   * <ol>
85   *
86 < * <li> All assertions in code running in generated threads must use
86 > * <li>All assertions in code running in generated threads must use
87   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
88   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
89   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
90   * particularly recommended) for other code to use these forms too.
91   * Only the most typically used JUnit assertion methods are defined
92 < * this way, but enough to live with.</li>
92 > * this way, but enough to live with.
93   *
94 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
94 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
95   * to invoke {@code super.setUp} and {@code super.tearDown} within
96   * them. These methods are used to clear and check for thread
97 < * assertion failures.</li>
97 > * assertion failures.
98   *
99   * <li>All delays and timeouts must use one of the constants {@code
100   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 60 | Line 105 | import java.security.SecurityPermission;
105   * is always discriminable as larger than SHORT and smaller than
106   * MEDIUM.  And so on. These constants are set to conservative values,
107   * but even so, if there is ever any doubt, they can all be increased
108 < * in one spot to rerun tests on slower platforms.</li>
108 > * in one spot to rerun tests on slower platforms.
109   *
110 < * <li> All threads generated must be joined inside each test case
110 > * <li>All threads generated must be joined inside each test case
111   * method (or {@code fail} to do so) before returning from the
112   * method. The {@code joinPool} method can be used to do this when
113 < * using Executors.</li>
113 > * using Executors.
114   *
115   * </ol>
116   *
117 < * <p> <b>Other notes</b>
117 > * <p><b>Other notes</b>
118   * <ul>
119   *
120 < * <li> Usually, there is one testcase method per JSR166 method
120 > * <li>Usually, there is one testcase method per JSR166 method
121   * covering "normal" operation, and then as many exception-testing
122   * methods as there are exceptions the method can throw. Sometimes
123   * there are multiple tests per JSR166 method when the different
124   * "normal" behaviors differ significantly. And sometimes testcases
125 < * cover multiple methods when they cannot be tested in
81 < * isolation.</li>
125 > * cover multiple methods when they cannot be tested in isolation.
126   *
127 < * <li> The documentation style for testcases is to provide as javadoc
127 > * <li>The documentation style for testcases is to provide as javadoc
128   * a simple sentence or two describing the property that the testcase
129   * method purports to test. The javadocs do not say anything about how
130 < * the property is tested. To find out, read the code.</li>
130 > * the property is tested. To find out, read the code.
131   *
132 < * <li> These tests are "conformance tests", and do not attempt to
132 > * <li>These tests are "conformance tests", and do not attempt to
133   * test throughput, latency, scalability or other performance factors
134   * (see the separate "jtreg" tests for a set intended to check these
135   * for the most central aspects of functionality.) So, most tests use
136   * the smallest sensible numbers of threads, collection sizes, etc
137 < * needed to check basic conformance.</li>
137 > * needed to check basic conformance.
138   *
139   * <li>The test classes currently do not declare inclusion in
140   * any particular package to simplify things for people integrating
141 < * them in TCK test suites.</li>
141 > * them in TCK test suites.
142   *
143 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
144 < * runs all JSR166 unit tests.</li>
143 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
144 > * runs all JSR166 unit tests.
145   *
146   * </ul>
147   */
# Line 109 | Line 153 | public class JSR166TestCase extends Test
153          Boolean.getBoolean("jsr166.expensiveTests");
154  
155      /**
156 +     * If true, also run tests that are not part of the official tck
157 +     * because they test unspecified implementation details.
158 +     */
159 +    protected static final boolean testImplementationDetails =
160 +        Boolean.getBoolean("jsr166.testImplementationDetails");
161 +
162 +    /**
163       * If true, report on stdout all "slow" tests, that is, ones that
164       * take more than profileThreshold milliseconds to execute.
165       */
# Line 122 | Line 173 | public class JSR166TestCase extends Test
173      private static final long profileThreshold =
174          Long.getLong("jsr166.profileThreshold", 100);
175  
176 +    /**
177 +     * The number of repetitions per test (for tickling rare bugs).
178 +     */
179 +    private static final int runsPerTest =
180 +        Integer.getInteger("jsr166.runsPerTest", 1);
181 +
182 +    /**
183 +     * The number of repetitions of the test suite (for finding leaks?).
184 +     */
185 +    private static final int suiteRuns =
186 +        Integer.getInteger("jsr166.suiteRuns", 1);
187 +
188 +    /**
189 +     * Returns the value of the system property, or NaN if not defined.
190 +     */
191 +    private static float systemPropertyValue(String name) {
192 +        String floatString = System.getProperty(name);
193 +        if (floatString == null)
194 +            return Float.NaN;
195 +        try {
196 +            return Float.parseFloat(floatString);
197 +        } catch (NumberFormatException ex) {
198 +            throw new IllegalArgumentException(
199 +                String.format("Bad float value in system property %s=%s",
200 +                              name, floatString));
201 +        }
202 +    }
203 +
204 +    /**
205 +     * The scaling factor to apply to standard delays used in tests.
206 +     * May be initialized from any of:
207 +     * - the "jsr166.delay.factor" system property
208 +     * - the "test.timeout.factor" system property (as used by jtreg)
209 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
210 +     * - hard-coded fuzz factor when using a known slowpoke VM
211 +     */
212 +    private static final float delayFactor = delayFactor();
213 +
214 +    private static float delayFactor() {
215 +        float x;
216 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
217 +            return x;
218 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
219 +            return x;
220 +        String prop = System.getProperty("java.vm.version");
221 +        if (prop != null && prop.matches(".*debug.*"))
222 +            return 4.0f; // How much slower is fastdebug than product?!
223 +        return 1.0f;
224 +    }
225 +
226 +    public JSR166TestCase() { super(); }
227 +    public JSR166TestCase(String name) { super(name); }
228 +
229 +    /**
230 +     * A filter for tests to run, matching strings of the form
231 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
232 +     * Usefully combined with jsr166.runsPerTest.
233 +     */
234 +    private static final Pattern methodFilter = methodFilter();
235 +
236 +    private static Pattern methodFilter() {
237 +        String regex = System.getProperty("jsr166.methodFilter");
238 +        return (regex == null) ? null : Pattern.compile(regex);
239 +    }
240 +
241 +    // Instrumentation to debug very rare, but very annoying hung test runs.
242 +    static volatile TestCase currentTestCase;
243 +    // static volatile int currentRun = 0;
244 +    static {
245 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
246 +            // Avoid spurious reports with enormous runsPerTest.
247 +            // A single test case run should never take more than 1 second.
248 +            // But let's cap it at the high end too ...
249 +            final int timeoutMinutes =
250 +                Math.min(15, Math.max(runsPerTest / 60, 1));
251 +            for (TestCase lastTestCase = currentTestCase;;) {
252 +                try { MINUTES.sleep(timeoutMinutes); }
253 +                catch (InterruptedException unexpected) { break; }
254 +                if (lastTestCase == currentTestCase) {
255 +                    System.err.printf(
256 +                        "Looks like we're stuck running test: %s%n",
257 +                        lastTestCase);
258 + //                     System.err.printf(
259 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
260 + //                         lastTestCase, currentRun, runsPerTest);
261 + //                     System.err.println("availableProcessors=" +
262 + //                         Runtime.getRuntime().availableProcessors());
263 + //                     System.err.printf("cpu model = %s%n", cpuModel());
264 +                    dumpTestThreads();
265 +                    // one stack dump is probably enough; more would be spam
266 +                    break;
267 +                }
268 +                lastTestCase = currentTestCase;
269 +            }}};
270 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
271 +        thread.setDaemon(true);
272 +        thread.start();
273 +    }
274 +
275 + //     public static String cpuModel() {
276 + //         try {
277 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
278 + //                 .matcher(new String(
279 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
280 + //             matcher.find();
281 + //             return matcher.group(1);
282 + //         } catch (Exception ex) { return null; }
283 + //     }
284 +
285 +    public void runBare() throws Throwable {
286 +        currentTestCase = this;
287 +        if (methodFilter == null
288 +            || methodFilter.matcher(toString()).find())
289 +            super.runBare();
290 +    }
291 +
292      protected void runTest() throws Throwable {
293 <        if (profileTests)
294 <            runTestProfiled();
295 <        else
296 <            super.runTest();
293 >        for (int i = 0; i < runsPerTest; i++) {
294 >            // currentRun = i;
295 >            if (profileTests)
296 >                runTestProfiled();
297 >            else
298 >                super.runTest();
299 >        }
300      }
301  
302      protected void runTestProfiled() throws Throwable {
303 <        long t0 = System.nanoTime();
304 <        try {
303 >        for (int i = 0; i < 2; i++) {
304 >            long startTime = System.nanoTime();
305              super.runTest();
306 <        } finally {
307 <            long elapsedMillis =
308 <                (System.nanoTime() - t0) / (1000L * 1000L);
309 <            if (elapsedMillis >= profileThreshold)
306 >            long elapsedMillis = millisElapsedSince(startTime);
307 >            if (elapsedMillis < profileThreshold)
308 >                break;
309 >            // Never report first run of any test; treat it as a
310 >            // warmup run, notably to trigger all needed classloading,
311 >            if (i > 0)
312                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
313          }
314      }
315  
316      /**
317 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
317 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
318       */
319      public static void main(String[] args) {
320 +        main(suite(), args);
321 +    }
322 +
323 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
324 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
325 +        long runTime;
326 +        public void startTest(Test test) {}
327 +        protected void printHeader(long runTime) {
328 +            this.runTime = runTime; // defer printing for later
329 +        }
330 +        protected void printFooter(TestResult result) {
331 +            if (result.wasSuccessful()) {
332 +                getWriter().println("OK (" + result.runCount() + " tests)"
333 +                    + "  Time: " + elapsedTimeAsString(runTime));
334 +            } else {
335 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
336 +                super.printFooter(result);
337 +            }
338 +        }
339 +    }
340 +
341 +    /**
342 +     * Returns a TestRunner that doesn't bother with unnecessary
343 +     * fluff, like printing a "." for each test case.
344 +     */
345 +    static junit.textui.TestRunner newPithyTestRunner() {
346 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
347 +        runner.setPrinter(new PithyResultPrinter(System.out));
348 +        return runner;
349 +    }
350 +
351 +    /**
352 +     * Runs all unit tests in the given test suite.
353 +     * Actual behavior influenced by jsr166.* system properties.
354 +     */
355 +    static void main(Test suite, String[] args) {
356          if (useSecurityManager) {
357              System.err.println("Setting a permissive security manager");
358              Policy.setPolicy(permissivePolicy());
359              System.setSecurityManager(new SecurityManager());
360          }
361 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
362 <
363 <        Test s = suite();
364 <        for (int i = 0; i < iters; ++i) {
157 <            junit.textui.TestRunner.run(s);
361 >        for (int i = 0; i < suiteRuns; i++) {
362 >            TestResult result = newPithyTestRunner().doRun(suite);
363 >            if (!result.wasSuccessful())
364 >                System.exit(1);
365              System.gc();
366              System.runFinalization();
367          }
161        System.exit(0);
368      }
369  
370      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 174 | Line 380 | public class JSR166TestCase extends Test
380          return suite;
381      }
382  
383 +    public static void addNamedTestClasses(TestSuite suite,
384 +                                           String... testClassNames) {
385 +        for (String testClassName : testClassNames) {
386 +            try {
387 +                Class<?> testClass = Class.forName(testClassName);
388 +                Method m = testClass.getDeclaredMethod("suite",
389 +                                                       new Class<?>[0]);
390 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
391 +            } catch (Exception e) {
392 +                throw new Error("Missing test class", e);
393 +            }
394 +        }
395 +    }
396 +
397 +    public static final double JAVA_CLASS_VERSION;
398 +    public static final String JAVA_SPECIFICATION_VERSION;
399 +    static {
400 +        try {
401 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
402 +                new java.security.PrivilegedAction<Double>() {
403 +                public Double run() {
404 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
405 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
406 +                new java.security.PrivilegedAction<String>() {
407 +                public String run() {
408 +                    return System.getProperty("java.specification.version");}});
409 +        } catch (Throwable t) {
410 +            throw new Error(t);
411 +        }
412 +    }
413 +
414 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
415 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
416 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
417 +    public static boolean atLeastJava9() {
418 +        return JAVA_CLASS_VERSION >= 53.0
419 +            // As of 2015-09, java9 still uses 52.0 class file version
420 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
421 +    }
422 +    public static boolean atLeastJava10() {
423 +        return JAVA_CLASS_VERSION >= 54.0
424 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
425 +    }
426 +
427      /**
428       * Collects all JSR166 unit tests as one suite.
429       */
430      public static Test suite() {
431 <        return newTestSuite(
431 >        // Java7+ test classes
432 >        TestSuite suite = newTestSuite(
433              ForkJoinPoolTest.suite(),
434              ForkJoinTaskTest.suite(),
435              RecursiveActionTest.suite(),
# Line 243 | Line 494 | public class JSR166TestCase extends Test
494              TreeSetTest.suite(),
495              TreeSubMapTest.suite(),
496              TreeSubSetTest.suite());
497 +
498 +        // Java8+ test classes
499 +        if (atLeastJava8()) {
500 +            String[] java8TestClassNames = {
501 +                "Atomic8Test",
502 +                "CompletableFutureTest",
503 +                "ConcurrentHashMap8Test",
504 +                "CountedCompleterTest",
505 +                "DoubleAccumulatorTest",
506 +                "DoubleAdderTest",
507 +                "ForkJoinPool8Test",
508 +                "ForkJoinTask8Test",
509 +                "LongAccumulatorTest",
510 +                "LongAdderTest",
511 +                "SplittableRandomTest",
512 +                "StampedLockTest",
513 +                "SubmissionPublisherTest",
514 +                "ThreadLocalRandom8Test",
515 +                "TimeUnit8Test",
516 +            };
517 +            addNamedTestClasses(suite, java8TestClassNames);
518 +        }
519 +
520 +        // Java9+ test classes
521 +        if (atLeastJava9()) {
522 +            String[] java9TestClassNames = {
523 +                "ExecutorCompletionService9Test",
524 +            };
525 +            addNamedTestClasses(suite, java9TestClassNames);
526 +        }
527 +
528 +        return suite;
529      }
530  
531 +    /** Returns list of junit-style test method names in given class. */
532 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
533 +        Method[] methods = testClass.getDeclaredMethods();
534 +        ArrayList<String> names = new ArrayList<String>(methods.length);
535 +        for (Method method : methods) {
536 +            if (method.getName().startsWith("test")
537 +                && Modifier.isPublic(method.getModifiers())
538 +                // method.getParameterCount() requires jdk8+
539 +                && method.getParameterTypes().length == 0) {
540 +                names.add(method.getName());
541 +            }
542 +        }
543 +        return names;
544 +    }
545 +
546 +    /**
547 +     * Returns junit-style testSuite for the given test class, but
548 +     * parameterized by passing extra data to each test.
549 +     */
550 +    public static <ExtraData> Test parameterizedTestSuite
551 +        (Class<? extends JSR166TestCase> testClass,
552 +         Class<ExtraData> dataClass,
553 +         ExtraData data) {
554 +        try {
555 +            TestSuite suite = new TestSuite();
556 +            Constructor c =
557 +                testClass.getDeclaredConstructor(dataClass, String.class);
558 +            for (String methodName : testMethodNames(testClass))
559 +                suite.addTest((Test) c.newInstance(data, methodName));
560 +            return suite;
561 +        } catch (Exception e) {
562 +            throw new Error(e);
563 +        }
564 +    }
565 +
566 +    /**
567 +     * Returns junit-style testSuite for the jdk8 extension of the
568 +     * given test class, but parameterized by passing extra data to
569 +     * each test.  Uses reflection to allow compilation in jdk7.
570 +     */
571 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
572 +        (Class<? extends JSR166TestCase> testClass,
573 +         Class<ExtraData> dataClass,
574 +         ExtraData data) {
575 +        if (atLeastJava8()) {
576 +            String name = testClass.getName();
577 +            String name8 = name.replaceAll("Test$", "8Test");
578 +            if (name.equals(name8)) throw new Error(name);
579 +            try {
580 +                return (Test)
581 +                    Class.forName(name8)
582 +                    .getMethod("testSuite", new Class[] { dataClass })
583 +                    .invoke(null, data);
584 +            } catch (Exception e) {
585 +                throw new Error(e);
586 +            }
587 +        } else {
588 +            return new TestSuite();
589 +        }
590 +    }
591 +
592 +    // Delays for timing-dependent tests, in milliseconds.
593  
594      public static long SHORT_DELAY_MS;
595      public static long SMALL_DELAY_MS;
596      public static long MEDIUM_DELAY_MS;
597      public static long LONG_DELAY_MS;
598  
254
599      /**
600 <     * Returns the shortest timed delay. This could
601 <     * be reimplemented to use for example a Property.
600 >     * Returns the shortest timed delay. This can be scaled up for
601 >     * slow machines using the jsr166.delay.factor system property,
602 >     * or via jtreg's -timeoutFactor: flag.
603 >     * http://openjdk.java.net/jtreg/command-help.html
604       */
605      protected long getShortDelay() {
606 <        return 50;
606 >        return (long) (50 * delayFactor);
607      }
608  
609      /**
# Line 279 | Line 625 | public class JSR166TestCase extends Test
625      }
626  
627      /**
628 <     * Returns a new Date instance representing a time delayMillis
629 <     * milliseconds in the future.
628 >     * Returns a new Date instance representing a time at least
629 >     * delayMillis milliseconds in the future.
630       */
631      Date delayedDate(long delayMillis) {
632 <        return new Date(new Date().getTime() + delayMillis);
632 >        // Add 1 because currentTimeMillis is known to round into the past.
633 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
634      }
635  
636      /**
# Line 299 | Line 646 | public class JSR166TestCase extends Test
646       * the same test have no effect.
647       */
648      public void threadRecordFailure(Throwable t) {
649 +        System.err.println(t);
650 +        dumpTestThreads();
651          threadFailure.compareAndSet(null, t);
652      }
653  
# Line 306 | Line 655 | public class JSR166TestCase extends Test
655          setDelays();
656      }
657  
658 +    void tearDownFail(String format, Object... args) {
659 +        String msg = toString() + ": " + String.format(format, args);
660 +        System.err.println(msg);
661 +        dumpTestThreads();
662 +        throw new AssertionFailedError(msg);
663 +    }
664 +
665      /**
666 +     * Extra checks that get done for all test cases.
667 +     *
668       * Triggers test case failure if any thread assertions have failed,
669       * by rethrowing, in the test harness thread, any exception recorded
670       * earlier by threadRecordFailure.
671 +     *
672 +     * Triggers test case failure if interrupt status is set in the main thread.
673       */
674      public void tearDown() throws Exception {
675          Throwable t = threadFailure.getAndSet(null);
# Line 327 | Line 687 | public class JSR166TestCase extends Test
687                  throw afe;
688              }
689          }
690 +
691 +        if (Thread.interrupted())
692 +            tearDownFail("interrupt status set in main thread");
693 +
694 +        checkForkJoinPoolThreadLeaks();
695 +    }
696 +
697 +    /**
698 +     * Finds missing PoolCleaners
699 +     */
700 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
701 +        Thread[] survivors = new Thread[7];
702 +        int count = Thread.enumerate(survivors);
703 +        for (int i = 0; i < count; i++) {
704 +            Thread thread = survivors[i];
705 +            String name = thread.getName();
706 +            if (name.startsWith("ForkJoinPool-")) {
707 +                // give thread some time to terminate
708 +                thread.join(LONG_DELAY_MS);
709 +                if (thread.isAlive())
710 +                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
711 +                                 thread);
712 +            }
713 +        }
714 +
715 +        if (!ForkJoinPool.commonPool()
716 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
717 +            tearDownFail("ForkJoin common pool thread stuck");
718      }
719  
720      /**
# Line 339 | Line 727 | public class JSR166TestCase extends Test
727              fail(reason);
728          } catch (AssertionFailedError t) {
729              threadRecordFailure(t);
730 <            fail(reason);
730 >            throw t;
731          }
732      }
733  
# Line 407 | Line 795 | public class JSR166TestCase extends Test
795      public void threadAssertEquals(Object x, Object y) {
796          try {
797              assertEquals(x, y);
798 <        } catch (AssertionFailedError t) {
799 <            threadRecordFailure(t);
800 <            throw t;
801 <        } catch (Throwable t) {
802 <            threadUnexpectedException(t);
798 >        } catch (AssertionFailedError fail) {
799 >            threadRecordFailure(fail);
800 >            throw fail;
801 >        } catch (Throwable fail) {
802 >            threadUnexpectedException(fail);
803          }
804      }
805  
# Line 423 | Line 811 | public class JSR166TestCase extends Test
811      public void threadAssertSame(Object x, Object y) {
812          try {
813              assertSame(x, y);
814 <        } catch (AssertionFailedError t) {
815 <            threadRecordFailure(t);
816 <            throw t;
814 >        } catch (AssertionFailedError fail) {
815 >            threadRecordFailure(fail);
816 >            throw fail;
817          }
818      }
819  
# Line 466 | Line 854 | public class JSR166TestCase extends Test
854      /**
855       * Delays, via Thread.sleep, for the given millisecond delay, but
856       * if the sleep is shorter than specified, may re-sleep or yield
857 <     * until time elapses.
857 >     * until time elapses.  Ensures that the given time, as measured
858 >     * by System.nanoTime(), has elapsed.
859       */
860      static void delay(long millis) throws InterruptedException {
861 <        long startTime = System.nanoTime();
862 <        long ns = millis * 1000 * 1000;
863 <        for (;;) {
861 >        long nanos = millis * (1000 * 1000);
862 >        final long wakeupTime = System.nanoTime() + nanos;
863 >        do {
864              if (millis > 0L)
865                  Thread.sleep(millis);
866              else // too short to sleep
867                  Thread.yield();
868 <            long d = ns - (System.nanoTime() - startTime);
869 <            if (d > 0L)
870 <                millis = d / (1000 * 1000);
871 <            else
872 <                break;
868 >            nanos = wakeupTime - System.nanoTime();
869 >            millis = nanos / (1000 * 1000);
870 >        } while (nanos >= 0L);
871 >    }
872 >
873 >    /**
874 >     * Allows use of try-with-resources with per-test thread pools.
875 >     */
876 >    class PoolCleaner implements AutoCloseable {
877 >        private final ExecutorService pool;
878 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
879 >        public void close() { joinPool(pool); }
880 >    }
881 >
882 >    /**
883 >     * An extension of PoolCleaner that has an action to release the pool.
884 >     */
885 >    class PoolCleanerWithReleaser extends PoolCleaner {
886 >        private final Runnable releaser;
887 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
888 >            super(pool);
889 >            this.releaser = releaser;
890 >        }
891 >        public void close() {
892 >            try {
893 >                releaser.run();
894 >            } finally {
895 >                super.close();
896 >            }
897          }
898      }
899  
900 +    PoolCleaner cleaner(ExecutorService pool) {
901 +        return new PoolCleaner(pool);
902 +    }
903 +
904 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
905 +        return new PoolCleanerWithReleaser(pool, releaser);
906 +    }
907 +
908 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
909 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
910 +    }
911 +
912 +    Runnable releaser(final CountDownLatch latch) {
913 +        return new Runnable() { public void run() {
914 +            do { latch.countDown(); }
915 +            while (latch.getCount() > 0);
916 +        }};
917 +    }
918 +
919 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
920 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
921 +    }
922 +
923 +    Runnable releaser(final AtomicBoolean flag) {
924 +        return new Runnable() { public void run() { flag.set(true); }};
925 +    }
926 +
927      /**
928       * Waits out termination of a thread pool or fails doing so.
929       */
930 <    void joinPool(ExecutorService exec) {
930 >    void joinPool(ExecutorService pool) {
931          try {
932 <            exec.shutdown();
933 <            assertTrue("ExecutorService did not terminate in a timely manner",
934 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
932 >            pool.shutdown();
933 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
934 >                try {
935 >                    threadFail("ExecutorService " + pool +
936 >                               " did not terminate in a timely manner");
937 >                } finally {
938 >                    // last resort, for the benefit of subsequent tests
939 >                    pool.shutdownNow();
940 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
941 >                }
942 >            }
943          } catch (SecurityException ok) {
944              // Allowed in case test doesn't have privs
945 <        } catch (InterruptedException ie) {
946 <            fail("Unexpected InterruptedException");
945 >        } catch (InterruptedException fail) {
946 >            threadFail("Unexpected InterruptedException");
947          }
948      }
949  
950 +    /** Like Runnable, but with the freedom to throw anything */
951 +    interface Action { public void run() throws Throwable; }
952 +
953 +    /**
954 +     * Runs all the given actions in parallel, failing if any fail.
955 +     * Useful for running multiple variants of tests that are
956 +     * necessarily individually slow because they must block.
957 +     */
958 +    void testInParallel(Action ... actions) {
959 +        ExecutorService pool = Executors.newCachedThreadPool();
960 +        try (PoolCleaner cleaner = cleaner(pool)) {
961 +            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
962 +            for (final Action action : actions)
963 +                futures.add(pool.submit(new CheckedRunnable() {
964 +                    public void realRun() throws Throwable { action.run();}}));
965 +            for (Future<?> future : futures)
966 +                try {
967 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
968 +                } catch (ExecutionException ex) {
969 +                    threadUnexpectedException(ex.getCause());
970 +                } catch (Exception ex) {
971 +                    threadUnexpectedException(ex);
972 +                }
973 +        }
974 +    }
975 +
976 +    /**
977 +     * A debugging tool to print stack traces of most threads, as jstack does.
978 +     * Uninteresting threads are filtered out.
979 +     */
980 +    static void dumpTestThreads() {
981 +        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
982 +        System.err.println("------ stacktrace dump start ------");
983 +        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
984 +            String name = info.getThreadName();
985 +            if ("Signal Dispatcher".equals(name))
986 +                continue;
987 +            if ("Reference Handler".equals(name)
988 +                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
989 +                continue;
990 +            if ("Finalizer".equals(name)
991 +                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
992 +                continue;
993 +            if ("checkForWedgedTest".equals(name))
994 +                continue;
995 +            System.err.print(info);
996 +        }
997 +        System.err.println("------ stacktrace dump end ------");
998 +    }
999 +
1000      /**
1001       * Checks that thread does not terminate within the default
1002       * millisecond delay of {@code timeoutMillis()}.
# Line 515 | Line 1013 | public class JSR166TestCase extends Test
1013              // No need to optimize the failing case via Thread.join.
1014              delay(millis);
1015              assertTrue(thread.isAlive());
1016 <        } catch (InterruptedException ie) {
1017 <            fail("Unexpected InterruptedException");
1016 >        } catch (InterruptedException fail) {
1017 >            threadFail("Unexpected InterruptedException");
1018 >        }
1019 >    }
1020 >
1021 >    /**
1022 >     * Checks that the threads do not terminate within the default
1023 >     * millisecond delay of {@code timeoutMillis()}.
1024 >     */
1025 >    void assertThreadsStayAlive(Thread... threads) {
1026 >        assertThreadsStayAlive(timeoutMillis(), threads);
1027 >    }
1028 >
1029 >    /**
1030 >     * Checks that the threads do not terminate within the given millisecond delay.
1031 >     */
1032 >    void assertThreadsStayAlive(long millis, Thread... threads) {
1033 >        try {
1034 >            // No need to optimize the failing case via Thread.join.
1035 >            delay(millis);
1036 >            for (Thread thread : threads)
1037 >                assertTrue(thread.isAlive());
1038 >        } catch (InterruptedException fail) {
1039 >            threadFail("Unexpected InterruptedException");
1040          }
1041      }
1042  
# Line 537 | Line 1057 | public class JSR166TestCase extends Test
1057              future.get(timeoutMillis, MILLISECONDS);
1058              shouldThrow();
1059          } catch (TimeoutException success) {
1060 <        } catch (Exception e) {
1061 <            threadUnexpectedException(e);
1060 >        } catch (Exception fail) {
1061 >            threadUnexpectedException(fail);
1062          } finally { future.cancel(true); }
1063          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1064      }
# Line 582 | Line 1102 | public class JSR166TestCase extends Test
1102      public static final Integer m6  = new Integer(-6);
1103      public static final Integer m10 = new Integer(-10);
1104  
585
1105      /**
1106       * Runs Runnable r with a security policy that permits precisely
1107       * the specified permissions.  If there is no current security
# Line 594 | Line 1113 | public class JSR166TestCase extends Test
1113          SecurityManager sm = System.getSecurityManager();
1114          if (sm == null) {
1115              r.run();
1116 +        }
1117 +        runWithSecurityManagerWithPermissions(r, permissions);
1118 +    }
1119 +
1120 +    /**
1121 +     * Runs Runnable r with a security policy that permits precisely
1122 +     * the specified permissions.  If there is no current security
1123 +     * manager, a temporary one is set for the duration of the
1124 +     * Runnable.  We require that any security manager permit
1125 +     * getPolicy/setPolicy.
1126 +     */
1127 +    public void runWithSecurityManagerWithPermissions(Runnable r,
1128 +                                                      Permission... permissions) {
1129 +        SecurityManager sm = System.getSecurityManager();
1130 +        if (sm == null) {
1131              Policy savedPolicy = Policy.getPolicy();
1132              try {
1133                  Policy.setPolicy(permissivePolicy());
1134                  System.setSecurityManager(new SecurityManager());
1135 <                runWithPermissions(r, permissions);
1135 >                runWithSecurityManagerWithPermissions(r, permissions);
1136              } finally {
1137                  System.setSecurityManager(null);
1138                  Policy.setPolicy(savedPolicy);
# Line 646 | Line 1180 | public class JSR166TestCase extends Test
1180              return perms.implies(p);
1181          }
1182          public void refresh() {}
1183 +        public String toString() {
1184 +            List<Permission> ps = new ArrayList<Permission>();
1185 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1186 +                ps.add(e.nextElement());
1187 +            return "AdjustablePolicy with permissions " + ps;
1188 +        }
1189      }
1190  
1191      /**
# Line 674 | Line 1214 | public class JSR166TestCase extends Test
1214      void sleep(long millis) {
1215          try {
1216              delay(millis);
1217 <        } catch (InterruptedException ie) {
1217 >        } catch (InterruptedException fail) {
1218              AssertionFailedError afe =
1219                  new AssertionFailedError("Unexpected InterruptedException");
1220 <            afe.initCause(ie);
1220 >            afe.initCause(fail);
1221              throw afe;
1222          }
1223      }
1224  
1225      /**
1226 <     * Waits up to the specified number of milliseconds for the given
1226 >     * Spin-waits up to the specified number of milliseconds for the given
1227       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1228       */
1229      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1230 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
691 <        long t0 = System.nanoTime();
1230 >        long startTime = System.nanoTime();
1231          for (;;) {
1232              Thread.State s = thread.getState();
1233              if (s == Thread.State.BLOCKED ||
# Line 697 | Line 1236 | public class JSR166TestCase extends Test
1236                  return;
1237              else if (s == Thread.State.TERMINATED)
1238                  fail("Unexpected thread termination");
1239 <            else if (System.nanoTime() - t0 > timeoutNanos) {
1239 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1240                  threadAssertTrue(thread.isAlive());
1241                  return;
1242              }
# Line 716 | Line 1255 | public class JSR166TestCase extends Test
1255      /**
1256       * Returns the number of milliseconds since time given by
1257       * startNanoTime, which must have been previously returned from a
1258 <     * call to {@link System.nanoTime()}.
1258 >     * call to {@link System#nanoTime()}.
1259       */
1260 <    long millisElapsedSince(long startNanoTime) {
1260 >    static long millisElapsedSince(long startNanoTime) {
1261          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1262      }
1263  
1264 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1265 + //         long startTime = System.nanoTime();
1266 + //         try {
1267 + //             r.run();
1268 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1269 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1270 + //             throw new AssertionFailedError("did not return promptly");
1271 + //     }
1272 +
1273 + //     void assertTerminatesPromptly(Runnable r) {
1274 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1275 + //     }
1276 +
1277 +    /**
1278 +     * Checks that timed f.get() returns the expected value, and does not
1279 +     * wait for the timeout to elapse before returning.
1280 +     */
1281 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1282 +        long startTime = System.nanoTime();
1283 +        try {
1284 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1285 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1286 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1287 +            throw new AssertionFailedError("timed get did not return promptly");
1288 +    }
1289 +
1290 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1291 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1292 +    }
1293 +
1294      /**
1295       * Returns a new started daemon Thread running the given runnable.
1296       */
# Line 740 | Line 1309 | public class JSR166TestCase extends Test
1309      void awaitTermination(Thread t, long timeoutMillis) {
1310          try {
1311              t.join(timeoutMillis);
1312 <        } catch (InterruptedException ie) {
1313 <            threadUnexpectedException(ie);
1312 >        } catch (InterruptedException fail) {
1313 >            threadUnexpectedException(fail);
1314          } finally {
1315              if (t.getState() != Thread.State.TERMINATED) {
1316                  t.interrupt();
1317 <                fail("Test timed out");
1317 >                threadFail("timed out waiting for thread to terminate");
1318              }
1319          }
1320      }
# Line 767 | Line 1336 | public class JSR166TestCase extends Test
1336          public final void run() {
1337              try {
1338                  realRun();
1339 <            } catch (Throwable t) {
1340 <                threadUnexpectedException(t);
1339 >            } catch (Throwable fail) {
1340 >                threadUnexpectedException(fail);
1341              }
1342          }
1343      }
# Line 822 | Line 1391 | public class JSR166TestCase extends Test
1391                  threadShouldThrow("InterruptedException");
1392              } catch (InterruptedException success) {
1393                  threadAssertFalse(Thread.interrupted());
1394 <            } catch (Throwable t) {
1395 <                threadUnexpectedException(t);
1394 >            } catch (Throwable fail) {
1395 >                threadUnexpectedException(fail);
1396              }
1397          }
1398      }
# Line 834 | Line 1403 | public class JSR166TestCase extends Test
1403          public final T call() {
1404              try {
1405                  return realCall();
1406 <            } catch (Throwable t) {
1407 <                threadUnexpectedException(t);
1406 >            } catch (Throwable fail) {
1407 >                threadUnexpectedException(fail);
1408                  return null;
1409              }
1410          }
# Line 852 | Line 1421 | public class JSR166TestCase extends Test
1421                  return result;
1422              } catch (InterruptedException success) {
1423                  threadAssertFalse(Thread.interrupted());
1424 <            } catch (Throwable t) {
1425 <                threadUnexpectedException(t);
1424 >            } catch (Throwable fail) {
1425 >                threadUnexpectedException(fail);
1426              }
1427              return null;
1428          }
# Line 870 | Line 1439 | public class JSR166TestCase extends Test
1439      public static final String TEST_STRING = "a test string";
1440  
1441      public static class StringTask implements Callable<String> {
1442 <        public String call() { return TEST_STRING; }
1442 >        final String value;
1443 >        public StringTask() { this(TEST_STRING); }
1444 >        public StringTask(String value) { this.value = value; }
1445 >        public String call() { return value; }
1446      }
1447  
1448      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 883 | Line 1455 | public class JSR166TestCase extends Test
1455              }};
1456      }
1457  
1458 <    public Runnable awaiter(final CountDownLatch latch) {
1458 >    public Runnable countDowner(final CountDownLatch latch) {
1459          return new CheckedRunnable() {
1460              public void realRun() throws InterruptedException {
1461 <                await(latch);
1461 >                latch.countDown();
1462              }};
1463      }
1464  
1465 +    class LatchAwaiter extends CheckedRunnable {
1466 +        static final int NEW = 0;
1467 +        static final int RUNNING = 1;
1468 +        static final int DONE = 2;
1469 +        final CountDownLatch latch;
1470 +        int state = NEW;
1471 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1472 +        public void realRun() throws InterruptedException {
1473 +            state = 1;
1474 +            await(latch);
1475 +            state = 2;
1476 +        }
1477 +    }
1478 +
1479 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1480 +        return new LatchAwaiter(latch);
1481 +    }
1482 +
1483 +    public void await(CountDownLatch latch, long timeoutMillis) {
1484 +        try {
1485 +            if (!latch.await(timeoutMillis, MILLISECONDS))
1486 +                fail("timed out waiting for CountDownLatch for "
1487 +                     + (timeoutMillis/1000) + " sec");
1488 +        } catch (Throwable fail) {
1489 +            threadUnexpectedException(fail);
1490 +        }
1491 +    }
1492 +
1493      public void await(CountDownLatch latch) {
1494 +        await(latch, LONG_DELAY_MS);
1495 +    }
1496 +
1497 +    public void await(Semaphore semaphore) {
1498          try {
1499 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1500 <        } catch (Throwable t) {
1501 <            threadUnexpectedException(t);
1499 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1500 >                fail("timed out waiting for Semaphore for "
1501 >                     + (LONG_DELAY_MS/1000) + " sec");
1502 >        } catch (Throwable fail) {
1503 >            threadUnexpectedException(fail);
1504          }
1505      }
1506  
# Line 1085 | Line 1691 | public class JSR166TestCase extends Test
1691      public abstract class CheckedRecursiveAction extends RecursiveAction {
1692          protected abstract void realCompute() throws Throwable;
1693  
1694 <        public final void compute() {
1694 >        @Override protected final void compute() {
1695              try {
1696                  realCompute();
1697 <            } catch (Throwable t) {
1698 <                threadUnexpectedException(t);
1697 >            } catch (Throwable fail) {
1698 >                threadUnexpectedException(fail);
1699              }
1700          }
1701      }
# Line 1100 | Line 1706 | public class JSR166TestCase extends Test
1706      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1707          protected abstract T realCompute() throws Throwable;
1708  
1709 <        public final T compute() {
1709 >        @Override protected final T compute() {
1710              try {
1711                  return realCompute();
1712 <            } catch (Throwable t) {
1713 <                threadUnexpectedException(t);
1712 >            } catch (Throwable fail) {
1713 >                threadUnexpectedException(fail);
1714                  return null;
1715              }
1716          }
# Line 1119 | Line 1725 | public class JSR166TestCase extends Test
1725      }
1726  
1727      /**
1728 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1729 <     * of throwing checked exceptions.
1728 >     * A CyclicBarrier that uses timed await and fails with
1729 >     * AssertionFailedErrors instead of throwing checked exceptions.
1730       */
1731      public class CheckedBarrier extends CyclicBarrier {
1732          public CheckedBarrier(int parties) { super(parties); }
1733  
1734          public int await() {
1735              try {
1736 <                return super.await();
1737 <            } catch (Exception e) {
1736 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1737 >            } catch (TimeoutException timedOut) {
1738 >                throw new AssertionFailedError("timed out");
1739 >            } catch (Exception fail) {
1740                  AssertionFailedError afe =
1741 <                    new AssertionFailedError("Unexpected exception: " + e);
1742 <                afe.initCause(e);
1741 >                    new AssertionFailedError("Unexpected exception: " + fail);
1742 >                afe.initCause(fail);
1743                  throw afe;
1744              }
1745          }
# Line 1159 | Line 1767 | public class JSR166TestCase extends Test
1767                  q.remove();
1768                  shouldThrow();
1769              } catch (NoSuchElementException success) {}
1770 <        } catch (InterruptedException ie) {
1163 <            threadUnexpectedException(ie);
1164 <        }
1770 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1771      }
1772  
1773 <    @SuppressWarnings("unchecked")
1774 <    <T> T serialClone(T o) {
1773 >    void assertSerialEquals(Object x, Object y) {
1774 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1775 >    }
1776 >
1777 >    void assertNotSerialEquals(Object x, Object y) {
1778 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1779 >    }
1780 >
1781 >    byte[] serialBytes(Object o) {
1782          try {
1783              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1784              ObjectOutputStream oos = new ObjectOutputStream(bos);
1785              oos.writeObject(o);
1786              oos.flush();
1787              oos.close();
1788 <            ByteArrayInputStream bin =
1789 <                new ByteArrayInputStream(bos.toByteArray());
1790 <            ObjectInputStream ois = new ObjectInputStream(bin);
1791 <            return (T) ois.readObject();
1792 <        } catch (Throwable t) {
1793 <            threadUnexpectedException(t);
1788 >            return bos.toByteArray();
1789 >        } catch (Throwable fail) {
1790 >            threadUnexpectedException(fail);
1791 >            return new byte[0];
1792 >        }
1793 >    }
1794 >
1795 >    @SuppressWarnings("unchecked")
1796 >    <T> T serialClone(T o) {
1797 >        try {
1798 >            ObjectInputStream ois = new ObjectInputStream
1799 >                (new ByteArrayInputStream(serialBytes(o)));
1800 >            T clone = (T) ois.readObject();
1801 >            assertSame(o.getClass(), clone.getClass());
1802 >            return clone;
1803 >        } catch (Throwable fail) {
1804 >            threadUnexpectedException(fail);
1805              return null;
1806          }
1807      }
1808 +
1809 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1810 +                             Runnable... throwingActions) {
1811 +        for (Runnable throwingAction : throwingActions) {
1812 +            boolean threw = false;
1813 +            try { throwingAction.run(); }
1814 +            catch (Throwable t) {
1815 +                threw = true;
1816 +                if (!expectedExceptionClass.isInstance(t)) {
1817 +                    AssertionFailedError afe =
1818 +                        new AssertionFailedError
1819 +                        ("Expected " + expectedExceptionClass.getName() +
1820 +                         ", got " + t.getClass().getName());
1821 +                    afe.initCause(t);
1822 +                    threadUnexpectedException(afe);
1823 +                }
1824 +            }
1825 +            if (!threw)
1826 +                shouldThrow(expectedExceptionClass.getName());
1827 +        }
1828 +    }
1829 +
1830 +    public void assertIteratorExhausted(Iterator<?> it) {
1831 +        try {
1832 +            it.next();
1833 +            shouldThrow();
1834 +        } catch (NoSuchElementException success) {}
1835 +        assertFalse(it.hasNext());
1836 +    }
1837 +
1838 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1839 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1840 +    }
1841 +
1842 +    public Runnable runnableThrowing(final RuntimeException ex) {
1843 +        return new Runnable() { public void run() { throw ex; }};
1844 +    }
1845 +
1846 +    /** A reusable thread pool to be shared by tests. */
1847 +    static final ExecutorService cachedThreadPool =
1848 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1849 +                               1000L, MILLISECONDS,
1850 +                               new SynchronousQueue<Runnable>());
1851 +
1852   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines