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.64 by jsr166, Fri Oct 15 22:30:07 2010 UTC vs.
Revision 1.181 by jsr166, Mon Nov 9 06:06:54 2015 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.PropertyPermission;
11 import java.util.concurrent.*;
12 import java.util.concurrent.atomic.AtomicReference;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.MINUTES;
11 + import static java.util.concurrent.TimeUnit.NANOSECONDS;
12 +
13 + import java.io.ByteArrayInputStream;
14 + import java.io.ByteArrayOutputStream;
15 + import java.io.ObjectInputStream;
16 + import java.io.ObjectOutputStream;
17 + import java.lang.management.ManagementFactory;
18 + import java.lang.management.ThreadInfo;
19 + import java.lang.management.ThreadMXBean;
20 + import java.lang.reflect.Constructor;
21 + import java.lang.reflect.Method;
22 + import java.lang.reflect.Modifier;
23 + import java.nio.file.Files;
24 + import java.nio.file.Paths;
25   import java.security.CodeSource;
26   import java.security.Permission;
27   import java.security.PermissionCollection;
# Line 18 | Line 29 | import java.security.Permissions;
29   import java.security.Policy;
30   import java.security.ProtectionDomain;
31   import java.security.SecurityPermission;
32 + import java.util.ArrayList;
33 + import java.util.Arrays;
34 + import java.util.Date;
35 + import java.util.Enumeration;
36 + import java.util.Iterator;
37 + import java.util.List;
38 + import java.util.NoSuchElementException;
39 + import java.util.PropertyPermission;
40 + import java.util.concurrent.BlockingQueue;
41 + import java.util.concurrent.Callable;
42 + import java.util.concurrent.CountDownLatch;
43 + import java.util.concurrent.CyclicBarrier;
44 + import java.util.concurrent.ExecutionException;
45 + import java.util.concurrent.Executors;
46 + import java.util.concurrent.ExecutorService;
47 + import java.util.concurrent.ForkJoinPool;
48 + import java.util.concurrent.Future;
49 + import java.util.concurrent.RecursiveAction;
50 + import java.util.concurrent.RecursiveTask;
51 + import java.util.concurrent.RejectedExecutionHandler;
52 + import java.util.concurrent.Semaphore;
53 + import java.util.concurrent.ThreadFactory;
54 + import java.util.concurrent.ThreadPoolExecutor;
55 + import java.util.concurrent.TimeoutException;
56 + import java.util.concurrent.atomic.AtomicReference;
57 + import java.util.regex.Matcher;
58 + import java.util.regex.Pattern;
59 +
60 + import junit.framework.AssertionFailedError;
61 + import junit.framework.Test;
62 + import junit.framework.TestCase;
63 + import junit.framework.TestResult;
64 + import junit.framework.TestSuite;
65  
66   /**
67   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 29 | Line 73 | import java.security.SecurityPermission;
73   *
74   * <ol>
75   *
76 < * <li> All assertions in code running in generated threads must use
76 > * <li>All assertions in code running in generated threads must use
77   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
78   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
79   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
80   * particularly recommended) for other code to use these forms too.
81   * Only the most typically used JUnit assertion methods are defined
82 < * this way, but enough to live with.</li>
82 > * this way, but enough to live with.
83   *
84 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
84 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
85   * to invoke {@code super.setUp} and {@code super.tearDown} within
86   * them. These methods are used to clear and check for thread
87 < * assertion failures.</li>
87 > * assertion failures.
88   *
89   * <li>All delays and timeouts must use one of the constants {@code
90   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 51 | Line 95 | import java.security.SecurityPermission;
95   * is always discriminable as larger than SHORT and smaller than
96   * MEDIUM.  And so on. These constants are set to conservative values,
97   * but even so, if there is ever any doubt, they can all be increased
98 < * in one spot to rerun tests on slower platforms.</li>
98 > * in one spot to rerun tests on slower platforms.
99   *
100 < * <li> All threads generated must be joined inside each test case
100 > * <li>All threads generated must be joined inside each test case
101   * method (or {@code fail} to do so) before returning from the
102   * method. The {@code joinPool} method can be used to do this when
103 < * using Executors.</li>
103 > * using Executors.
104   *
105   * </ol>
106   *
107 < * <p> <b>Other notes</b>
107 > * <p><b>Other notes</b>
108   * <ul>
109   *
110 < * <li> Usually, there is one testcase method per JSR166 method
110 > * <li>Usually, there is one testcase method per JSR166 method
111   * covering "normal" operation, and then as many exception-testing
112   * methods as there are exceptions the method can throw. Sometimes
113   * there are multiple tests per JSR166 method when the different
114   * "normal" behaviors differ significantly. And sometimes testcases
115 < * cover multiple methods when they cannot be tested in
72 < * isolation.</li>
115 > * cover multiple methods when they cannot be tested in isolation.
116   *
117 < * <li> The documentation style for testcases is to provide as javadoc
117 > * <li>The documentation style for testcases is to provide as javadoc
118   * a simple sentence or two describing the property that the testcase
119   * method purports to test. The javadocs do not say anything about how
120 < * the property is tested. To find out, read the code.</li>
120 > * the property is tested. To find out, read the code.
121   *
122 < * <li> These tests are "conformance tests", and do not attempt to
122 > * <li>These tests are "conformance tests", and do not attempt to
123   * test throughput, latency, scalability or other performance factors
124   * (see the separate "jtreg" tests for a set intended to check these
125   * for the most central aspects of functionality.) So, most tests use
126   * the smallest sensible numbers of threads, collection sizes, etc
127 < * needed to check basic conformance.</li>
127 > * needed to check basic conformance.
128   *
129   * <li>The test classes currently do not declare inclusion in
130   * any particular package to simplify things for people integrating
131 < * them in TCK test suites.</li>
131 > * them in TCK test suites.
132   *
133 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
134 < * runs all JSR166 unit tests.</li>
133 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
134 > * runs all JSR166 unit tests.
135   *
136   * </ul>
137   */
# Line 100 | Line 143 | public class JSR166TestCase extends Test
143          Boolean.getBoolean("jsr166.expensiveTests");
144  
145      /**
146 +     * If true, also run tests that are not part of the official tck
147 +     * because they test unspecified implementation details.
148 +     */
149 +    protected static final boolean testImplementationDetails =
150 +        Boolean.getBoolean("jsr166.testImplementationDetails");
151 +
152 +    /**
153       * If true, report on stdout all "slow" tests, that is, ones that
154       * take more than profileThreshold milliseconds to execute.
155       */
# Line 113 | Line 163 | public class JSR166TestCase extends Test
163      private static final long profileThreshold =
164          Long.getLong("jsr166.profileThreshold", 100);
165  
166 +    /**
167 +     * The number of repetitions per test (for tickling rare bugs).
168 +     */
169 +    private static final int runsPerTest =
170 +        Integer.getInteger("jsr166.runsPerTest", 1);
171 +
172 +    /**
173 +     * The number of repetitions of the test suite (for finding leaks?).
174 +     */
175 +    private static final int suiteRuns =
176 +        Integer.getInteger("jsr166.suiteRuns", 1);
177 +
178 +    /**
179 +     * The scaling factor to apply to standard delays used in tests.
180 +     */
181 +    private static final int delayFactor =
182 +        Integer.getInteger("jsr166.delay.factor", 1);
183 +
184 +    public JSR166TestCase() { super(); }
185 +    public JSR166TestCase(String name) { super(name); }
186 +
187 +    /**
188 +     * A filter for tests to run, matching strings of the form
189 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
190 +     * Usefully combined with jsr166.runsPerTest.
191 +     */
192 +    private static final Pattern methodFilter = methodFilter();
193 +
194 +    private static Pattern methodFilter() {
195 +        String regex = System.getProperty("jsr166.methodFilter");
196 +        return (regex == null) ? null : Pattern.compile(regex);
197 +    }
198 +
199 +    // Instrumentation to debug very rare, but very annoying hung test runs.
200 +    static volatile TestCase currentTestCase;
201 +    // static volatile int currentRun = 0;
202 +    static {
203 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
204 +            // Avoid spurious reports with enormous runsPerTest.
205 +            // A single test case run should never take more than 1 second.
206 +            // But let's cap it at the high end too ...
207 +            final int timeoutMinutes =
208 +                Math.min(15, Math.max(runsPerTest / 60, 1));
209 +            for (TestCase lastTestCase = currentTestCase;;) {
210 +                try { MINUTES.sleep(timeoutMinutes); }
211 +                catch (InterruptedException unexpected) { break; }
212 +                if (lastTestCase == currentTestCase) {
213 +                    System.err.printf(
214 +                        "Looks like we're stuck running test: %s%n",
215 +                        lastTestCase);
216 + //                     System.err.printf(
217 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
218 + //                         lastTestCase, currentRun, runsPerTest);
219 + //                     System.err.println("availableProcessors=" +
220 + //                         Runtime.getRuntime().availableProcessors());
221 + //                     System.err.printf("cpu model = %s%n", cpuModel());
222 +                    dumpTestThreads();
223 +                    // one stack dump is probably enough; more would be spam
224 +                    break;
225 +                }
226 +                lastTestCase = currentTestCase;
227 +            }}};
228 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
229 +        thread.setDaemon(true);
230 +        thread.start();
231 +    }
232 +
233 + //     public static String cpuModel() {
234 + //         try {
235 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
236 + //                 .matcher(new String(
237 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
238 + //             matcher.find();
239 + //             return matcher.group(1);
240 + //         } catch (Exception ex) { return null; }
241 + //     }
242 +
243 +    public void runBare() throws Throwable {
244 +        currentTestCase = this;
245 +        if (methodFilter == null
246 +            || methodFilter.matcher(toString()).find())
247 +            super.runBare();
248 +    }
249 +
250      protected void runTest() throws Throwable {
251 <        if (profileTests)
252 <            runTestProfiled();
253 <        else
254 <            super.runTest();
251 >        for (int i = 0; i < runsPerTest; i++) {
252 >            // currentRun = i;
253 >            if (profileTests)
254 >                runTestProfiled();
255 >            else
256 >                super.runTest();
257 >        }
258      }
259  
260      protected void runTestProfiled() throws Throwable {
261 <        long t0 = System.nanoTime();
262 <        try {
261 >        for (int i = 0; i < 2; i++) {
262 >            long startTime = System.nanoTime();
263              super.runTest();
264 <        } finally {
265 <            long elapsedMillis =
266 <                (System.nanoTime() - t0) / (1000L * 1000L);
267 <            if (elapsedMillis >= profileThreshold)
264 >            long elapsedMillis = millisElapsedSince(startTime);
265 >            if (elapsedMillis < profileThreshold)
266 >                break;
267 >            // Never report first run of any test; treat it as a
268 >            // warmup run, notably to trigger all needed classloading,
269 >            if (i > 0)
270                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
271          }
272      }
273  
274      /**
275 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
275 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
276       */
277      public static void main(String[] args) {
278 +        main(suite(), args);
279 +    }
280 +
281 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
282 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
283 +        long runTime;
284 +        public void startTest(Test test) {}
285 +        protected void printHeader(long runTime) {
286 +            this.runTime = runTime; // defer printing for later
287 +        }
288 +        protected void printFooter(TestResult result) {
289 +            if (result.wasSuccessful()) {
290 +                getWriter().println("OK (" + result.runCount() + " tests)"
291 +                    + "  Time: " + elapsedTimeAsString(runTime));
292 +            } else {
293 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
294 +                super.printFooter(result);
295 +            }
296 +        }
297 +    }
298 +
299 +    /**
300 +     * Returns a TestRunner that doesn't bother with unnecessary
301 +     * fluff, like printing a "." for each test case.
302 +     */
303 +    static junit.textui.TestRunner newPithyTestRunner() {
304 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
305 +        runner.setPrinter(new PithyResultPrinter(System.out));
306 +        return runner;
307 +    }
308 +
309 +    /**
310 +     * Runs all unit tests in the given test suite.
311 +     * Actual behavior influenced by jsr166.* system properties.
312 +     */
313 +    static void main(Test suite, String[] args) {
314          if (useSecurityManager) {
315              System.err.println("Setting a permissive security manager");
316              Policy.setPolicy(permissivePolicy());
317              System.setSecurityManager(new SecurityManager());
318          }
319 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
320 <
321 <        Test s = suite();
322 <        for (int i = 0; i < iters; ++i) {
148 <            junit.textui.TestRunner.run(s);
319 >        for (int i = 0; i < suiteRuns; i++) {
320 >            TestResult result = newPithyTestRunner().doRun(suite);
321 >            if (!result.wasSuccessful())
322 >                System.exit(1);
323              System.gc();
324              System.runFinalization();
325          }
152        System.exit(0);
326      }
327  
328      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 165 | Line 338 | public class JSR166TestCase extends Test
338          return suite;
339      }
340  
341 +    public static void addNamedTestClasses(TestSuite suite,
342 +                                           String... testClassNames) {
343 +        for (String testClassName : testClassNames) {
344 +            try {
345 +                Class<?> testClass = Class.forName(testClassName);
346 +                Method m = testClass.getDeclaredMethod("suite",
347 +                                                       new Class<?>[0]);
348 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
349 +            } catch (Exception e) {
350 +                throw new Error("Missing test class", e);
351 +            }
352 +        }
353 +    }
354 +
355 +    public static final double JAVA_CLASS_VERSION;
356 +    public static final String JAVA_SPECIFICATION_VERSION;
357 +    static {
358 +        try {
359 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
360 +                new java.security.PrivilegedAction<Double>() {
361 +                public Double run() {
362 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
363 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
364 +                new java.security.PrivilegedAction<String>() {
365 +                public String run() {
366 +                    return System.getProperty("java.specification.version");}});
367 +        } catch (Throwable t) {
368 +            throw new Error(t);
369 +        }
370 +    }
371 +
372 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
373 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
374 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
375 +    public static boolean atLeastJava9() {
376 +        return JAVA_CLASS_VERSION >= 53.0
377 +            // As of 2015-09, java9 still uses 52.0 class file version
378 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
379 +    }
380 +    public static boolean atLeastJava10() {
381 +        return JAVA_CLASS_VERSION >= 54.0
382 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
383 +    }
384 +
385      /**
386       * Collects all JSR166 unit tests as one suite.
387       */
388      public static Test suite() {
389 <        return newTestSuite(
389 >        // Java7+ test classes
390 >        TestSuite suite = newTestSuite(
391              ForkJoinPoolTest.suite(),
392              ForkJoinTaskTest.suite(),
393              RecursiveActionTest.suite(),
# Line 234 | Line 452 | public class JSR166TestCase extends Test
452              TreeSetTest.suite(),
453              TreeSubMapTest.suite(),
454              TreeSubSetTest.suite());
455 +
456 +        // Java8+ test classes
457 +        if (atLeastJava8()) {
458 +            String[] java8TestClassNames = {
459 +                "Atomic8Test",
460 +                "CompletableFutureTest",
461 +                "ConcurrentHashMap8Test",
462 +                "CountedCompleterTest",
463 +                "DoubleAccumulatorTest",
464 +                "DoubleAdderTest",
465 +                "ForkJoinPool8Test",
466 +                "ForkJoinTask8Test",
467 +                "LongAccumulatorTest",
468 +                "LongAdderTest",
469 +                "SplittableRandomTest",
470 +                "StampedLockTest",
471 +                "SubmissionPublisherTest",
472 +                "ThreadLocalRandom8Test",
473 +            };
474 +            addNamedTestClasses(suite, java8TestClassNames);
475 +        }
476 +
477 +        // Java9+ test classes
478 +        if (atLeastJava9()) {
479 +            String[] java9TestClassNames = {
480 +                // Currently empty, but expecting varhandle tests
481 +            };
482 +            addNamedTestClasses(suite, java9TestClassNames);
483 +        }
484 +
485 +        return suite;
486 +    }
487 +
488 +    /** Returns list of junit-style test method names in given class. */
489 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
490 +        Method[] methods = testClass.getDeclaredMethods();
491 +        ArrayList<String> names = new ArrayList<String>(methods.length);
492 +        for (Method method : methods) {
493 +            if (method.getName().startsWith("test")
494 +                && Modifier.isPublic(method.getModifiers())
495 +                // method.getParameterCount() requires jdk8+
496 +                && method.getParameterTypes().length == 0) {
497 +                names.add(method.getName());
498 +            }
499 +        }
500 +        return names;
501 +    }
502 +
503 +    /**
504 +     * Returns junit-style testSuite for the given test class, but
505 +     * parameterized by passing extra data to each test.
506 +     */
507 +    public static <ExtraData> Test parameterizedTestSuite
508 +        (Class<? extends JSR166TestCase> testClass,
509 +         Class<ExtraData> dataClass,
510 +         ExtraData data) {
511 +        try {
512 +            TestSuite suite = new TestSuite();
513 +            Constructor c =
514 +                testClass.getDeclaredConstructor(dataClass, String.class);
515 +            for (String methodName : testMethodNames(testClass))
516 +                suite.addTest((Test) c.newInstance(data, methodName));
517 +            return suite;
518 +        } catch (Exception e) {
519 +            throw new Error(e);
520 +        }
521      }
522  
523 +    /**
524 +     * Returns junit-style testSuite for the jdk8 extension of the
525 +     * given test class, but parameterized by passing extra data to
526 +     * each test.  Uses reflection to allow compilation in jdk7.
527 +     */
528 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
529 +        (Class<? extends JSR166TestCase> testClass,
530 +         Class<ExtraData> dataClass,
531 +         ExtraData data) {
532 +        if (atLeastJava8()) {
533 +            String name = testClass.getName();
534 +            String name8 = name.replaceAll("Test$", "8Test");
535 +            if (name.equals(name8)) throw new Error(name);
536 +            try {
537 +                return (Test)
538 +                    Class.forName(name8)
539 +                    .getMethod("testSuite", new Class[] { dataClass })
540 +                    .invoke(null, data);
541 +            } catch (Exception e) {
542 +                throw new Error(e);
543 +            }
544 +        } else {
545 +            return new TestSuite();
546 +        }
547 +    }
548 +
549 +    // Delays for timing-dependent tests, in milliseconds.
550  
551      public static long SHORT_DELAY_MS;
552      public static long SMALL_DELAY_MS;
553      public static long MEDIUM_DELAY_MS;
554      public static long LONG_DELAY_MS;
555  
245
556      /**
557 <     * Returns the shortest timed delay. This could
558 <     * be reimplemented to use for example a Property.
557 >     * Returns the shortest timed delay. This can be scaled up for
558 >     * slow machines using the jsr166.delay.factor system property.
559       */
560      protected long getShortDelay() {
561 <        return 50;
561 >        return 50 * delayFactor;
562      }
563  
254
564      /**
565       * Sets delays as multiples of SHORT_DELAY.
566       */
# Line 259 | Line 568 | public class JSR166TestCase extends Test
568          SHORT_DELAY_MS = getShortDelay();
569          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
570          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
571 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
571 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
572 >    }
573 >
574 >    /**
575 >     * Returns a timeout in milliseconds to be used in tests that
576 >     * verify that operations block or time out.
577 >     */
578 >    long timeoutMillis() {
579 >        return SHORT_DELAY_MS / 4;
580 >    }
581 >
582 >    /**
583 >     * Returns a new Date instance representing a time at least
584 >     * delayMillis milliseconds in the future.
585 >     */
586 >    Date delayedDate(long delayMillis) {
587 >        // Add 1 because currentTimeMillis is known to round into the past.
588 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
589      }
590  
591      /**
# Line 275 | Line 601 | public class JSR166TestCase extends Test
601       * the same test have no effect.
602       */
603      public void threadRecordFailure(Throwable t) {
604 +        System.err.println(t);
605 +        dumpTestThreads();
606          threadFailure.compareAndSet(null, t);
607      }
608  
# Line 282 | Line 610 | public class JSR166TestCase extends Test
610          setDelays();
611      }
612  
613 +    void tearDownFail(String format, Object... args) {
614 +        String msg = toString() + ": " + String.format(format, args);
615 +        System.err.println(msg);
616 +        dumpTestThreads();
617 +        throw new AssertionFailedError(msg);
618 +    }
619 +
620      /**
621 +     * Extra checks that get done for all test cases.
622 +     *
623       * Triggers test case failure if any thread assertions have failed,
624       * by rethrowing, in the test harness thread, any exception recorded
625       * earlier by threadRecordFailure.
626 +     *
627 +     * Triggers test case failure if interrupt status is set in the main thread.
628       */
629      public void tearDown() throws Exception {
630 <        Throwable t = threadFailure.get();
630 >        Throwable t = threadFailure.getAndSet(null);
631          if (t != null) {
632              if (t instanceof Error)
633                  throw (Error) t;
# Line 303 | Line 642 | public class JSR166TestCase extends Test
642                  throw afe;
643              }
644          }
645 +
646 +        if (Thread.interrupted())
647 +            tearDownFail("interrupt status set in main thread");
648 +
649 +        checkForkJoinPoolThreadLeaks();
650 +    }
651 +
652 +    /**
653 +     * Finds missing PoolCleaners
654 +     */
655 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
656 +        Thread[] survivors = new Thread[7];
657 +        int count = Thread.enumerate(survivors);
658 +        for (int i = 0; i < count; i++) {
659 +            Thread thread = survivors[i];
660 +            String name = thread.getName();
661 +            if (name.startsWith("ForkJoinPool-")) {
662 +                // give thread some time to terminate
663 +                thread.join(LONG_DELAY_MS);
664 +                if (thread.isAlive())
665 +                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
666 +                                 thread);
667 +            }
668 +        }
669 +
670 +        if (!ForkJoinPool.commonPool()
671 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
672 +            tearDownFail("ForkJoin common pool thread stuck");
673      }
674  
675      /**
# Line 315 | Line 682 | public class JSR166TestCase extends Test
682              fail(reason);
683          } catch (AssertionFailedError t) {
684              threadRecordFailure(t);
685 <            fail(reason);
685 >            throw t;
686          }
687      }
688  
# Line 383 | Line 750 | public class JSR166TestCase extends Test
750      public void threadAssertEquals(Object x, Object y) {
751          try {
752              assertEquals(x, y);
753 <        } catch (AssertionFailedError t) {
754 <            threadRecordFailure(t);
755 <            throw t;
756 <        } catch (Throwable t) {
757 <            threadUnexpectedException(t);
753 >        } catch (AssertionFailedError fail) {
754 >            threadRecordFailure(fail);
755 >            throw fail;
756 >        } catch (Throwable fail) {
757 >            threadUnexpectedException(fail);
758          }
759      }
760  
# Line 399 | Line 766 | public class JSR166TestCase extends Test
766      public void threadAssertSame(Object x, Object y) {
767          try {
768              assertSame(x, y);
769 <        } catch (AssertionFailedError t) {
770 <            threadRecordFailure(t);
771 <            throw t;
769 >        } catch (AssertionFailedError fail) {
770 >            threadRecordFailure(fail);
771 >            throw fail;
772          }
773      }
774  
# Line 434 | Line 801 | public class JSR166TestCase extends Test
801          else {
802              AssertionFailedError afe =
803                  new AssertionFailedError("unexpected exception: " + t);
804 <            t.initCause(t);
804 >            afe.initCause(t);
805              throw afe;
806          }
807      }
808  
809      /**
810 +     * Delays, via Thread.sleep, for the given millisecond delay, but
811 +     * if the sleep is shorter than specified, may re-sleep or yield
812 +     * until time elapses.  Ensures that the given time, as measured
813 +     * by System.nanoTime(), has elapsed.
814 +     */
815 +    static void delay(long millis) throws InterruptedException {
816 +        long nanos = millis * (1000 * 1000);
817 +        final long wakeupTime = System.nanoTime() + nanos;
818 +        do {
819 +            if (millis > 0L)
820 +                Thread.sleep(millis);
821 +            else // too short to sleep
822 +                Thread.yield();
823 +            nanos = wakeupTime - System.nanoTime();
824 +            millis = nanos / (1000 * 1000);
825 +        } while (nanos >= 0L);
826 +    }
827 +
828 +    /**
829 +     * Allows use of try-with-resources with per-test thread pools.
830 +     */
831 +    class PoolCleaner implements AutoCloseable {
832 +        private final ExecutorService pool;
833 +        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
834 +        public void close() { joinPool(pool); }
835 +    }
836 +
837 +    /**
838 +     * An extension of PoolCleaner that has an action to release the pool.
839 +     */
840 +    class PoolCleanerWithReleaser extends PoolCleaner {
841 +        private final Runnable releaser;
842 +        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
843 +            super(pool);
844 +            this.releaser = releaser;
845 +        }
846 +        public void close() {
847 +            try {
848 +                releaser.run();
849 +            } finally {
850 +                super.close();
851 +            }
852 +        }
853 +    }
854 +
855 +    PoolCleaner cleaner(ExecutorService pool) {
856 +        return new PoolCleaner(pool);
857 +    }
858 +
859 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
860 +        return new PoolCleanerWithReleaser(pool, releaser);
861 +    }
862 +
863 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
864 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
865 +    }
866 +
867 +    Runnable releaser(final CountDownLatch latch) {
868 +        return new Runnable() { public void run() {
869 +            do { latch.countDown(); }
870 +            while (latch.getCount() > 0);
871 +        }};
872 +    }
873 +
874 +    /**
875       * Waits out termination of a thread pool or fails doing so.
876       */
877 <    public void joinPool(ExecutorService exec) {
877 >    void joinPool(ExecutorService pool) {
878          try {
879 <            exec.shutdown();
880 <            assertTrue("ExecutorService did not terminate in a timely manner",
881 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
879 >            pool.shutdown();
880 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
881 >                try {
882 >                    threadFail("ExecutorService " + pool +
883 >                               " did not terminate in a timely manner");
884 >                } finally {
885 >                    // last resort, for the benefit of subsequent tests
886 >                    pool.shutdownNow();
887 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
888 >                }
889 >            }
890          } catch (SecurityException ok) {
891              // Allowed in case test doesn't have privs
892 <        } catch (InterruptedException ie) {
893 <            fail("Unexpected InterruptedException");
892 >        } catch (InterruptedException fail) {
893 >            threadFail("Unexpected InterruptedException");
894          }
895      }
896  
897 +    /** Like Runnable, but with the freedom to throw anything */
898 +    interface Action { public void run() throws Throwable; }
899 +
900 +    /**
901 +     * Runs all the given actions in parallel, failing if any fail.
902 +     * Useful for running multiple variants of tests that are
903 +     * necessarily individually slow because they must block.
904 +     */
905 +    void testInParallel(Action ... actions) {
906 +        ExecutorService pool = Executors.newCachedThreadPool();
907 +        try (PoolCleaner cleaner = cleaner(pool)) {
908 +            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
909 +            for (final Action action : actions)
910 +                futures.add(pool.submit(new CheckedRunnable() {
911 +                    public void realRun() throws Throwable { action.run();}}));
912 +            for (Future<?> future : futures)
913 +                try {
914 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
915 +                } catch (ExecutionException ex) {
916 +                    threadUnexpectedException(ex.getCause());
917 +                } catch (Exception ex) {
918 +                    threadUnexpectedException(ex);
919 +                }
920 +        }
921 +    }
922 +
923 +    /**
924 +     * A debugging tool to print stack traces of most threads, as jstack does.
925 +     * Uninteresting threads are filtered out.
926 +     */
927 +    static void dumpTestThreads() {
928 +        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
929 +        System.err.println("------ stacktrace dump start ------");
930 +        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
931 +            String name = info.getThreadName();
932 +            if ("Signal Dispatcher".equals(name))
933 +                continue;
934 +            if ("Reference Handler".equals(name)
935 +                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
936 +                continue;
937 +            if ("Finalizer".equals(name)
938 +                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
939 +                continue;
940 +            if ("checkForWedgedTest".equals(name))
941 +                continue;
942 +            System.err.print(info);
943 +        }
944 +        System.err.println("------ stacktrace dump end ------");
945 +    }
946 +
947 +    /**
948 +     * Checks that thread does not terminate within the default
949 +     * millisecond delay of {@code timeoutMillis()}.
950 +     */
951 +    void assertThreadStaysAlive(Thread thread) {
952 +        assertThreadStaysAlive(thread, timeoutMillis());
953 +    }
954 +
955 +    /**
956 +     * Checks that thread does not terminate within the given millisecond delay.
957 +     */
958 +    void assertThreadStaysAlive(Thread thread, long millis) {
959 +        try {
960 +            // No need to optimize the failing case via Thread.join.
961 +            delay(millis);
962 +            assertTrue(thread.isAlive());
963 +        } catch (InterruptedException fail) {
964 +            threadFail("Unexpected InterruptedException");
965 +        }
966 +    }
967 +
968 +    /**
969 +     * Checks that the threads do not terminate within the default
970 +     * millisecond delay of {@code timeoutMillis()}.
971 +     */
972 +    void assertThreadsStayAlive(Thread... threads) {
973 +        assertThreadsStayAlive(timeoutMillis(), threads);
974 +    }
975 +
976 +    /**
977 +     * Checks that the threads do not terminate within the given millisecond delay.
978 +     */
979 +    void assertThreadsStayAlive(long millis, Thread... threads) {
980 +        try {
981 +            // No need to optimize the failing case via Thread.join.
982 +            delay(millis);
983 +            for (Thread thread : threads)
984 +                assertTrue(thread.isAlive());
985 +        } catch (InterruptedException fail) {
986 +            threadFail("Unexpected InterruptedException");
987 +        }
988 +    }
989 +
990 +    /**
991 +     * Checks that future.get times out, with the default timeout of
992 +     * {@code timeoutMillis()}.
993 +     */
994 +    void assertFutureTimesOut(Future future) {
995 +        assertFutureTimesOut(future, timeoutMillis());
996 +    }
997 +
998 +    /**
999 +     * Checks that future.get times out, with the given millisecond timeout.
1000 +     */
1001 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
1002 +        long startTime = System.nanoTime();
1003 +        try {
1004 +            future.get(timeoutMillis, MILLISECONDS);
1005 +            shouldThrow();
1006 +        } catch (TimeoutException success) {
1007 +        } catch (Exception fail) {
1008 +            threadUnexpectedException(fail);
1009 +        } finally { future.cancel(true); }
1010 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1011 +    }
1012  
1013      /**
1014       * Fails with message "should throw exception".
# Line 494 | Line 1049 | public class JSR166TestCase extends Test
1049      public static final Integer m6  = new Integer(-6);
1050      public static final Integer m10 = new Integer(-10);
1051  
497
1052      /**
1053       * Runs Runnable r with a security policy that permits precisely
1054       * the specified permissions.  If there is no current security
# Line 506 | Line 1060 | public class JSR166TestCase extends Test
1060          SecurityManager sm = System.getSecurityManager();
1061          if (sm == null) {
1062              r.run();
1063 +        }
1064 +        runWithSecurityManagerWithPermissions(r, permissions);
1065 +    }
1066 +
1067 +    /**
1068 +     * Runs Runnable r with a security policy that permits precisely
1069 +     * the specified permissions.  If there is no current security
1070 +     * manager, a temporary one is set for the duration of the
1071 +     * Runnable.  We require that any security manager permit
1072 +     * getPolicy/setPolicy.
1073 +     */
1074 +    public void runWithSecurityManagerWithPermissions(Runnable r,
1075 +                                                      Permission... permissions) {
1076 +        SecurityManager sm = System.getSecurityManager();
1077 +        if (sm == null) {
1078              Policy savedPolicy = Policy.getPolicy();
1079              try {
1080                  Policy.setPolicy(permissivePolicy());
1081                  System.setSecurityManager(new SecurityManager());
1082 <                runWithPermissions(r, permissions);
1082 >                runWithSecurityManagerWithPermissions(r, permissions);
1083              } finally {
1084                  System.setSecurityManager(null);
1085                  Policy.setPolicy(savedPolicy);
# Line 558 | Line 1127 | public class JSR166TestCase extends Test
1127              return perms.implies(p);
1128          }
1129          public void refresh() {}
1130 +        public String toString() {
1131 +            List<Permission> ps = new ArrayList<Permission>();
1132 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1133 +                ps.add(e.nextElement());
1134 +            return "AdjustablePolicy with permissions " + ps;
1135 +        }
1136      }
1137  
1138      /**
# Line 585 | Line 1160 | public class JSR166TestCase extends Test
1160       */
1161      void sleep(long millis) {
1162          try {
1163 <            Thread.sleep(millis);
1164 <        } catch (InterruptedException ie) {
1163 >            delay(millis);
1164 >        } catch (InterruptedException fail) {
1165              AssertionFailedError afe =
1166                  new AssertionFailedError("Unexpected InterruptedException");
1167 <            afe.initCause(ie);
1167 >            afe.initCause(fail);
1168              throw afe;
1169          }
1170      }
1171  
1172      /**
1173 <     * Sleeps until the timeout has elapsed, or interrupted.
1174 <     * Does <em>NOT</em> throw InterruptedException.
1173 >     * Spin-waits up to the specified number of milliseconds for the given
1174 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1175 >     */
1176 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1177 >        long startTime = System.nanoTime();
1178 >        for (;;) {
1179 >            Thread.State s = thread.getState();
1180 >            if (s == Thread.State.BLOCKED ||
1181 >                s == Thread.State.WAITING ||
1182 >                s == Thread.State.TIMED_WAITING)
1183 >                return;
1184 >            else if (s == Thread.State.TERMINATED)
1185 >                fail("Unexpected thread termination");
1186 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1187 >                threadAssertTrue(thread.isAlive());
1188 >                return;
1189 >            }
1190 >            Thread.yield();
1191 >        }
1192 >    }
1193 >
1194 >    /**
1195 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1196 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
1197 >     */
1198 >    void waitForThreadToEnterWaitState(Thread thread) {
1199 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1200 >    }
1201 >
1202 >    /**
1203 >     * Returns the number of milliseconds since time given by
1204 >     * startNanoTime, which must have been previously returned from a
1205 >     * call to {@link System#nanoTime()}.
1206       */
1207 <    void sleepTillInterrupted(long timeoutMillis) {
1207 >    static long millisElapsedSince(long startNanoTime) {
1208 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1209 >    }
1210 >
1211 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1212 > //         long startTime = System.nanoTime();
1213 > //         try {
1214 > //             r.run();
1215 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1216 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1217 > //             throw new AssertionFailedError("did not return promptly");
1218 > //     }
1219 >
1220 > //     void assertTerminatesPromptly(Runnable r) {
1221 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1222 > //     }
1223 >
1224 >    /**
1225 >     * Checks that timed f.get() returns the expected value, and does not
1226 >     * wait for the timeout to elapse before returning.
1227 >     */
1228 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1229 >        long startTime = System.nanoTime();
1230          try {
1231 <            Thread.sleep(timeoutMillis);
1232 <        } catch (InterruptedException wakeup) {}
1231 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1232 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1233 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1234 >            throw new AssertionFailedError("timed get did not return promptly");
1235 >    }
1236 >
1237 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1238 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1239      }
1240  
1241      /**
# Line 622 | Line 1256 | public class JSR166TestCase extends Test
1256      void awaitTermination(Thread t, long timeoutMillis) {
1257          try {
1258              t.join(timeoutMillis);
1259 <        } catch (InterruptedException ie) {
1260 <            threadUnexpectedException(ie);
1259 >        } catch (InterruptedException fail) {
1260 >            threadUnexpectedException(fail);
1261          } finally {
1262 <            if (t.isAlive()) {
1262 >            if (t.getState() != Thread.State.TERMINATED) {
1263                  t.interrupt();
1264 <                fail("Test timed out");
1264 >                threadFail("timed out waiting for thread to terminate");
1265              }
1266          }
1267      }
1268  
1269 +    /**
1270 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1271 +     * terminate (using {@link Thread#join(long)}), else interrupts
1272 +     * the thread (in the hope that it may terminate later) and fails.
1273 +     */
1274 +    void awaitTermination(Thread t) {
1275 +        awaitTermination(t, LONG_DELAY_MS);
1276 +    }
1277 +
1278      // Some convenient Runnable classes
1279  
1280      public abstract class CheckedRunnable implements Runnable {
# Line 640 | Line 1283 | public class JSR166TestCase extends Test
1283          public final void run() {
1284              try {
1285                  realRun();
1286 <            } catch (Throwable t) {
1287 <                threadUnexpectedException(t);
1286 >            } catch (Throwable fail) {
1287 >                threadUnexpectedException(fail);
1288              }
1289          }
1290      }
# Line 694 | Line 1337 | public class JSR166TestCase extends Test
1337                  realRun();
1338                  threadShouldThrow("InterruptedException");
1339              } catch (InterruptedException success) {
1340 <            } catch (Throwable t) {
1341 <                threadUnexpectedException(t);
1340 >                threadAssertFalse(Thread.interrupted());
1341 >            } catch (Throwable fail) {
1342 >                threadUnexpectedException(fail);
1343              }
1344          }
1345      }
# Line 706 | Line 1350 | public class JSR166TestCase extends Test
1350          public final T call() {
1351              try {
1352                  return realCall();
1353 <            } catch (Throwable t) {
1354 <                threadUnexpectedException(t);
1353 >            } catch (Throwable fail) {
1354 >                threadUnexpectedException(fail);
1355                  return null;
1356              }
1357          }
# Line 723 | Line 1367 | public class JSR166TestCase extends Test
1367                  threadShouldThrow("InterruptedException");
1368                  return result;
1369              } catch (InterruptedException success) {
1370 <            } catch (Throwable t) {
1371 <                threadUnexpectedException(t);
1370 >                threadAssertFalse(Thread.interrupted());
1371 >            } catch (Throwable fail) {
1372 >                threadUnexpectedException(fail);
1373              }
1374              return null;
1375          }
# Line 741 | Line 1386 | public class JSR166TestCase extends Test
1386      public static final String TEST_STRING = "a test string";
1387  
1388      public static class StringTask implements Callable<String> {
1389 <        public String call() { return TEST_STRING; }
1389 >        final String value;
1390 >        public StringTask() { this(TEST_STRING); }
1391 >        public StringTask(String value) { this.value = value; }
1392 >        public String call() { return value; }
1393      }
1394  
1395      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 754 | Line 1402 | public class JSR166TestCase extends Test
1402              }};
1403      }
1404  
1405 +    public Runnable countDowner(final CountDownLatch latch) {
1406 +        return new CheckedRunnable() {
1407 +            public void realRun() throws InterruptedException {
1408 +                latch.countDown();
1409 +            }};
1410 +    }
1411 +
1412 +    class LatchAwaiter extends CheckedRunnable {
1413 +        static final int NEW = 0;
1414 +        static final int RUNNING = 1;
1415 +        static final int DONE = 2;
1416 +        final CountDownLatch latch;
1417 +        int state = NEW;
1418 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1419 +        public void realRun() throws InterruptedException {
1420 +            state = 1;
1421 +            await(latch);
1422 +            state = 2;
1423 +        }
1424 +    }
1425 +
1426 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1427 +        return new LatchAwaiter(latch);
1428 +    }
1429 +
1430 +    public void await(CountDownLatch latch) {
1431 +        try {
1432 +            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1433 +                fail("timed out waiting for CountDownLatch for "
1434 +                     + (LONG_DELAY_MS/1000) + " sec");
1435 +        } catch (Throwable fail) {
1436 +            threadUnexpectedException(fail);
1437 +        }
1438 +    }
1439 +
1440 +    public void await(Semaphore semaphore) {
1441 +        try {
1442 +            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1443 +                fail("timed out waiting for Semaphore for "
1444 +                     + (LONG_DELAY_MS/1000) + " sec");
1445 +        } catch (Throwable fail) {
1446 +            threadUnexpectedException(fail);
1447 +        }
1448 +    }
1449 +
1450 + //     /**
1451 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1452 + //      */
1453 + //     public void await(AtomicBoolean flag) {
1454 + //         await(flag, LONG_DELAY_MS);
1455 + //     }
1456 +
1457 + //     /**
1458 + //      * Spin-waits up to the specified timeout until flag becomes true.
1459 + //      */
1460 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1461 + //         long startTime = System.nanoTime();
1462 + //         while (!flag.get()) {
1463 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1464 + //                 throw new AssertionFailedError("timed out");
1465 + //             Thread.yield();
1466 + //         }
1467 + //     }
1468 +
1469      public static class NPETask implements Callable<String> {
1470          public String call() { throw new NullPointerException(); }
1471      }
# Line 764 | Line 1476 | public class JSR166TestCase extends Test
1476  
1477      public class ShortRunnable extends CheckedRunnable {
1478          protected void realRun() throws Throwable {
1479 <            Thread.sleep(SHORT_DELAY_MS);
1479 >            delay(SHORT_DELAY_MS);
1480          }
1481      }
1482  
1483      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1484          protected void realRun() throws InterruptedException {
1485 <            Thread.sleep(SHORT_DELAY_MS);
1485 >            delay(SHORT_DELAY_MS);
1486          }
1487      }
1488  
1489      public class SmallRunnable extends CheckedRunnable {
1490          protected void realRun() throws Throwable {
1491 <            Thread.sleep(SMALL_DELAY_MS);
1491 >            delay(SMALL_DELAY_MS);
1492          }
1493      }
1494  
1495      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1496          protected void realRun() {
1497              try {
1498 <                Thread.sleep(SMALL_DELAY_MS);
1498 >                delay(SMALL_DELAY_MS);
1499              } catch (InterruptedException ok) {}
1500          }
1501      }
1502  
1503      public class SmallCallable extends CheckedCallable {
1504          protected Object realCall() throws InterruptedException {
1505 <            Thread.sleep(SMALL_DELAY_MS);
1505 >            delay(SMALL_DELAY_MS);
1506              return Boolean.TRUE;
1507          }
1508      }
1509  
1510      public class MediumRunnable extends CheckedRunnable {
1511          protected void realRun() throws Throwable {
1512 <            Thread.sleep(MEDIUM_DELAY_MS);
1512 >            delay(MEDIUM_DELAY_MS);
1513          }
1514      }
1515  
1516      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1517          protected void realRun() throws InterruptedException {
1518 <            Thread.sleep(MEDIUM_DELAY_MS);
1518 >            delay(MEDIUM_DELAY_MS);
1519          }
1520      }
1521  
# Line 811 | Line 1523 | public class JSR166TestCase extends Test
1523          return new CheckedRunnable() {
1524              protected void realRun() {
1525                  try {
1526 <                    Thread.sleep(timeoutMillis);
1526 >                    delay(timeoutMillis);
1527                  } catch (InterruptedException ok) {}
1528              }};
1529      }
# Line 819 | Line 1531 | public class JSR166TestCase extends Test
1531      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1532          protected void realRun() {
1533              try {
1534 <                Thread.sleep(MEDIUM_DELAY_MS);
1534 >                delay(MEDIUM_DELAY_MS);
1535              } catch (InterruptedException ok) {}
1536          }
1537      }
# Line 827 | Line 1539 | public class JSR166TestCase extends Test
1539      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1540          protected void realRun() {
1541              try {
1542 <                Thread.sleep(LONG_DELAY_MS);
1542 >                delay(LONG_DELAY_MS);
1543              } catch (InterruptedException ok) {}
1544          }
1545      }
# Line 851 | Line 1563 | public class JSR166TestCase extends Test
1563                  public boolean isDone() { return done; }
1564                  public void run() {
1565                      try {
1566 <                        Thread.sleep(timeoutMillis);
1566 >                        delay(timeoutMillis);
1567                          done = true;
1568                      } catch (InterruptedException ok) {}
1569                  }
# Line 862 | Line 1574 | public class JSR166TestCase extends Test
1574          public volatile boolean done = false;
1575          public void run() {
1576              try {
1577 <                Thread.sleep(SHORT_DELAY_MS);
1577 >                delay(SHORT_DELAY_MS);
1578                  done = true;
1579              } catch (InterruptedException ok) {}
1580          }
# Line 872 | Line 1584 | public class JSR166TestCase extends Test
1584          public volatile boolean done = false;
1585          public void run() {
1586              try {
1587 <                Thread.sleep(SMALL_DELAY_MS);
1587 >                delay(SMALL_DELAY_MS);
1588                  done = true;
1589              } catch (InterruptedException ok) {}
1590          }
# Line 882 | Line 1594 | public class JSR166TestCase extends Test
1594          public volatile boolean done = false;
1595          public void run() {
1596              try {
1597 <                Thread.sleep(MEDIUM_DELAY_MS);
1597 >                delay(MEDIUM_DELAY_MS);
1598                  done = true;
1599              } catch (InterruptedException ok) {}
1600          }
# Line 892 | Line 1604 | public class JSR166TestCase extends Test
1604          public volatile boolean done = false;
1605          public void run() {
1606              try {
1607 <                Thread.sleep(LONG_DELAY_MS);
1607 >                delay(LONG_DELAY_MS);
1608                  done = true;
1609              } catch (InterruptedException ok) {}
1610          }
# Line 909 | Line 1621 | public class JSR166TestCase extends Test
1621          public volatile boolean done = false;
1622          public Object call() {
1623              try {
1624 <                Thread.sleep(SMALL_DELAY_MS);
1624 >                delay(SMALL_DELAY_MS);
1625                  done = true;
1626              } catch (InterruptedException ok) {}
1627              return Boolean.TRUE;
# Line 922 | Line 1634 | public class JSR166TestCase extends Test
1634      public abstract class CheckedRecursiveAction extends RecursiveAction {
1635          protected abstract void realCompute() throws Throwable;
1636  
1637 <        public final void compute() {
1637 >        @Override protected final void compute() {
1638              try {
1639                  realCompute();
1640 <            } catch (Throwable t) {
1641 <                threadUnexpectedException(t);
1640 >            } catch (Throwable fail) {
1641 >                threadUnexpectedException(fail);
1642              }
1643          }
1644      }
# Line 937 | Line 1649 | public class JSR166TestCase extends Test
1649      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1650          protected abstract T realCompute() throws Throwable;
1651  
1652 <        public final T compute() {
1652 >        @Override protected final T compute() {
1653              try {
1654                  return realCompute();
1655 <            } catch (Throwable t) {
1656 <                threadUnexpectedException(t);
1655 >            } catch (Throwable fail) {
1656 >                threadUnexpectedException(fail);
1657                  return null;
1658              }
1659          }
# Line 956 | Line 1668 | public class JSR166TestCase extends Test
1668      }
1669  
1670      /**
1671 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1672 <     * of throwing checked exceptions.
1671 >     * A CyclicBarrier that uses timed await and fails with
1672 >     * AssertionFailedErrors instead of throwing checked exceptions.
1673       */
1674      public class CheckedBarrier extends CyclicBarrier {
1675          public CheckedBarrier(int parties) { super(parties); }
1676  
1677          public int await() {
1678              try {
1679 <                return super.await();
1680 <            } catch (Exception e) {
1679 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1680 >            } catch (TimeoutException timedOut) {
1681 >                throw new AssertionFailedError("timed out");
1682 >            } catch (Exception fail) {
1683                  AssertionFailedError afe =
1684 <                    new AssertionFailedError("Unexpected exception: " + e);
1685 <                afe.initCause(e);
1684 >                    new AssertionFailedError("Unexpected exception: " + fail);
1685 >                afe.initCause(fail);
1686                  throw afe;
1687              }
1688          }
1689      }
1690  
1691 +    void checkEmpty(BlockingQueue q) {
1692 +        try {
1693 +            assertTrue(q.isEmpty());
1694 +            assertEquals(0, q.size());
1695 +            assertNull(q.peek());
1696 +            assertNull(q.poll());
1697 +            assertNull(q.poll(0, MILLISECONDS));
1698 +            assertEquals(q.toString(), "[]");
1699 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1700 +            assertFalse(q.iterator().hasNext());
1701 +            try {
1702 +                q.element();
1703 +                shouldThrow();
1704 +            } catch (NoSuchElementException success) {}
1705 +            try {
1706 +                q.iterator().next();
1707 +                shouldThrow();
1708 +            } catch (NoSuchElementException success) {}
1709 +            try {
1710 +                q.remove();
1711 +                shouldThrow();
1712 +            } catch (NoSuchElementException success) {}
1713 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1714 +    }
1715 +
1716 +    void assertSerialEquals(Object x, Object y) {
1717 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1718 +    }
1719 +
1720 +    void assertNotSerialEquals(Object x, Object y) {
1721 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1722 +    }
1723 +
1724 +    byte[] serialBytes(Object o) {
1725 +        try {
1726 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1727 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1728 +            oos.writeObject(o);
1729 +            oos.flush();
1730 +            oos.close();
1731 +            return bos.toByteArray();
1732 +        } catch (Throwable fail) {
1733 +            threadUnexpectedException(fail);
1734 +            return new byte[0];
1735 +        }
1736 +    }
1737 +
1738 +    @SuppressWarnings("unchecked")
1739 +    <T> T serialClone(T o) {
1740 +        try {
1741 +            ObjectInputStream ois = new ObjectInputStream
1742 +                (new ByteArrayInputStream(serialBytes(o)));
1743 +            T clone = (T) ois.readObject();
1744 +            assertSame(o.getClass(), clone.getClass());
1745 +            return clone;
1746 +        } catch (Throwable fail) {
1747 +            threadUnexpectedException(fail);
1748 +            return null;
1749 +        }
1750 +    }
1751 +
1752 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1753 +                             Runnable... throwingActions) {
1754 +        for (Runnable throwingAction : throwingActions) {
1755 +            boolean threw = false;
1756 +            try { throwingAction.run(); }
1757 +            catch (Throwable t) {
1758 +                threw = true;
1759 +                if (!expectedExceptionClass.isInstance(t)) {
1760 +                    AssertionFailedError afe =
1761 +                        new AssertionFailedError
1762 +                        ("Expected " + expectedExceptionClass.getName() +
1763 +                         ", got " + t.getClass().getName());
1764 +                    afe.initCause(t);
1765 +                    threadUnexpectedException(afe);
1766 +                }
1767 +            }
1768 +            if (!threw)
1769 +                shouldThrow(expectedExceptionClass.getName());
1770 +        }
1771 +    }
1772 +
1773 +    public void assertIteratorExhausted(Iterator<?> it) {
1774 +        try {
1775 +            it.next();
1776 +            shouldThrow();
1777 +        } catch (NoSuchElementException success) {}
1778 +        assertFalse(it.hasNext());
1779 +    }
1780   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines