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.67 by jsr166, Fri Oct 29 06:58:56 2010 UTC vs.
Revision 1.172 by jsr166, Fri Oct 9 01:26:36 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 19 | 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 30 | 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 52 | 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
116 < * isolation.</li>
116 > * isolation.
117   *
118 < * <li> The documentation style for testcases is to provide as javadoc
118 > * <li>The documentation style for testcases is to provide as javadoc
119   * a simple sentence or two describing the property that the testcase
120   * method purports to test. The javadocs do not say anything about how
121 < * the property is tested. To find out, read the code.</li>
121 > * the property is tested. To find out, read the code.
122   *
123 < * <li> These tests are "conformance tests", and do not attempt to
123 > * <li>These tests are "conformance tests", and do not attempt to
124   * test throughput, latency, scalability or other performance factors
125   * (see the separate "jtreg" tests for a set intended to check these
126   * for the most central aspects of functionality.) So, most tests use
127   * the smallest sensible numbers of threads, collection sizes, etc
128 < * needed to check basic conformance.</li>
128 > * needed to check basic conformance.
129   *
130   * <li>The test classes currently do not declare inclusion in
131   * any particular package to simplify things for people integrating
132 < * them in TCK test suites.</li>
132 > * them in TCK test suites.
133   *
134 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
135 < * runs all JSR166 unit tests.</li>
134 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
135 > * runs all JSR166 unit tests.
136   *
137   * </ul>
138   */
# Line 101 | Line 144 | public class JSR166TestCase extends Test
144          Boolean.getBoolean("jsr166.expensiveTests");
145  
146      /**
147 +     * If true, also run tests that are not part of the official tck
148 +     * because they test unspecified implementation details.
149 +     */
150 +    protected static final boolean testImplementationDetails =
151 +        Boolean.getBoolean("jsr166.testImplementationDetails");
152 +
153 +    /**
154       * If true, report on stdout all "slow" tests, that is, ones that
155       * take more than profileThreshold milliseconds to execute.
156       */
# Line 114 | Line 164 | public class JSR166TestCase extends Test
164      private static final long profileThreshold =
165          Long.getLong("jsr166.profileThreshold", 100);
166  
167 +    /**
168 +     * The number of repetitions per test (for tickling rare bugs).
169 +     */
170 +    private static final int runsPerTest =
171 +        Integer.getInteger("jsr166.runsPerTest", 1);
172 +
173 +    /**
174 +     * The number of repetitions of the test suite (for finding leaks?).
175 +     */
176 +    private static final int suiteRuns =
177 +        Integer.getInteger("jsr166.suiteRuns", 1);
178 +
179 +    public JSR166TestCase() { super(); }
180 +    public JSR166TestCase(String name) { super(name); }
181 +
182 +    /**
183 +     * A filter for tests to run, matching strings of the form
184 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
185 +     * Usefully combined with jsr166.runsPerTest.
186 +     */
187 +    private static final Pattern methodFilter = methodFilter();
188 +
189 +    private static Pattern methodFilter() {
190 +        String regex = System.getProperty("jsr166.methodFilter");
191 +        return (regex == null) ? null : Pattern.compile(regex);
192 +    }
193 +
194 +    // Instrumentation to debug very rare, but very annoying hung test runs.
195 +    static volatile TestCase currentTestCase;
196 +    static volatile int currentRun = 0;
197 +    static {
198 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
199 +            // avoid spurious reports with enormous runsPerTest
200 +            final int timeoutMinutes = Math.max(runsPerTest / 10, 1);
201 +            for (TestCase lastTestCase = currentTestCase;;) {
202 +                try { MINUTES.sleep(timeoutMinutes); }
203 +                catch (InterruptedException unexpected) { break; }
204 +                if (lastTestCase == currentTestCase) {
205 +                    System.err.printf(
206 +                        "Looks like we're stuck running test: %s (%d/%d)%n",
207 +                        lastTestCase, currentRun, runsPerTest);
208 +                    System.err.println("availableProcessors=" +
209 +                        Runtime.getRuntime().availableProcessors());
210 +                    System.err.printf("cpu model = %s%n", cpuModel());
211 +                    dumpTestThreads();
212 +                    // one stack dump is probably enough; more would be spam
213 +                    break;
214 +                }
215 +                lastTestCase = currentTestCase;
216 +            }}};
217 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
218 +        thread.setDaemon(true);
219 +        thread.start();
220 +    }
221 +
222 +    public static String cpuModel() {
223 +        try {
224 +            Matcher matcher = Pattern.compile("model name\\s*: (.*)")
225 +                .matcher(new String(
226 +                     Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
227 +            matcher.find();
228 +            return matcher.group(1);
229 +        } catch (Exception ex) { return null; }
230 +    }
231 +
232 +    public void runBare() throws Throwable {
233 +        currentTestCase = this;
234 +        if (methodFilter == null
235 +            || methodFilter.matcher(toString()).find())
236 +            super.runBare();
237 +    }
238 +
239      protected void runTest() throws Throwable {
240 <        if (profileTests)
241 <            runTestProfiled();
242 <        else
243 <            super.runTest();
240 >        for (int i = 0; i < runsPerTest; i++) {
241 >            currentRun = i;
242 >            if (profileTests)
243 >                runTestProfiled();
244 >            else
245 >                super.runTest();
246 >        }
247      }
248  
249      protected void runTestProfiled() throws Throwable {
250 <        long t0 = System.nanoTime();
251 <        try {
250 >        for (int i = 0; i < 2; i++) {
251 >            long startTime = System.nanoTime();
252              super.runTest();
253 <        } finally {
254 <            long elapsedMillis =
255 <                (System.nanoTime() - t0) / (1000L * 1000L);
256 <            if (elapsedMillis >= profileThreshold)
253 >            long elapsedMillis = millisElapsedSince(startTime);
254 >            if (elapsedMillis < profileThreshold)
255 >                break;
256 >            // Never report first run of any test; treat it as a
257 >            // warmup run, notably to trigger all needed classloading,
258 >            if (i > 0)
259                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
260          }
261      }
262  
263      /**
264 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
264 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
265       */
266      public static void main(String[] args) {
267 +        main(suite(), args);
268 +    }
269 +
270 +    /**
271 +     * Runs all unit tests in the given test suite.
272 +     * Actual behavior influenced by jsr166.* system properties.
273 +     */
274 +    static void main(Test suite, String[] args) {
275          if (useSecurityManager) {
276              System.err.println("Setting a permissive security manager");
277              Policy.setPolicy(permissivePolicy());
278              System.setSecurityManager(new SecurityManager());
279          }
280 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
281 <
282 <        Test s = suite();
283 <        for (int i = 0; i < iters; ++i) {
149 <            junit.textui.TestRunner.run(s);
280 >        for (int i = 0; i < suiteRuns; i++) {
281 >            TestResult result = junit.textui.TestRunner.run(suite);
282 >            if (!result.wasSuccessful())
283 >                System.exit(1);
284              System.gc();
285              System.runFinalization();
286          }
153        System.exit(0);
287      }
288  
289      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 166 | Line 299 | public class JSR166TestCase extends Test
299          return suite;
300      }
301  
302 +    public static void addNamedTestClasses(TestSuite suite,
303 +                                           String... testClassNames) {
304 +        for (String testClassName : testClassNames) {
305 +            try {
306 +                Class<?> testClass = Class.forName(testClassName);
307 +                Method m = testClass.getDeclaredMethod("suite",
308 +                                                       new Class<?>[0]);
309 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
310 +            } catch (Exception e) {
311 +                throw new Error("Missing test class", e);
312 +            }
313 +        }
314 +    }
315 +
316 +    public static final double JAVA_CLASS_VERSION;
317 +    public static final String JAVA_SPECIFICATION_VERSION;
318 +    static {
319 +        try {
320 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
321 +                new java.security.PrivilegedAction<Double>() {
322 +                public Double run() {
323 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
324 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
325 +                new java.security.PrivilegedAction<String>() {
326 +                public String run() {
327 +                    return System.getProperty("java.specification.version");}});
328 +        } catch (Throwable t) {
329 +            throw new Error(t);
330 +        }
331 +    }
332 +
333 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
334 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
335 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
336 +    public static boolean atLeastJava9() {
337 +        return JAVA_CLASS_VERSION >= 53.0
338 +            // As of 2015-09, java9 still uses 52.0 class file version
339 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
340 +    }
341 +    public static boolean atLeastJava10() {
342 +        return JAVA_CLASS_VERSION >= 54.0
343 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
344 +    }
345 +
346      /**
347       * Collects all JSR166 unit tests as one suite.
348       */
349      public static Test suite() {
350 <        return newTestSuite(
350 >        // Java7+ test classes
351 >        TestSuite suite = newTestSuite(
352              ForkJoinPoolTest.suite(),
353              ForkJoinTaskTest.suite(),
354              RecursiveActionTest.suite(),
# Line 235 | Line 413 | public class JSR166TestCase extends Test
413              TreeSetTest.suite(),
414              TreeSubMapTest.suite(),
415              TreeSubSetTest.suite());
416 +
417 +        // Java8+ test classes
418 +        if (atLeastJava8()) {
419 +            String[] java8TestClassNames = {
420 +                "Atomic8Test",
421 +                "CompletableFutureTest",
422 +                "ConcurrentHashMap8Test",
423 +                "CountedCompleterTest",
424 +                "DoubleAccumulatorTest",
425 +                "DoubleAdderTest",
426 +                "ForkJoinPool8Test",
427 +                "ForkJoinTask8Test",
428 +                "LongAccumulatorTest",
429 +                "LongAdderTest",
430 +                "SplittableRandomTest",
431 +                "StampedLockTest",
432 +                "SubmissionPublisherTest",
433 +                "ThreadLocalRandom8Test",
434 +            };
435 +            addNamedTestClasses(suite, java8TestClassNames);
436 +        }
437 +
438 +        // Java9+ test classes
439 +        if (atLeastJava9()) {
440 +            String[] java9TestClassNames = {
441 +                // Currently empty, but expecting varhandle tests
442 +            };
443 +            addNamedTestClasses(suite, java9TestClassNames);
444 +        }
445 +
446 +        return suite;
447 +    }
448 +
449 +    /** Returns list of junit-style test method names in given class. */
450 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
451 +        Method[] methods = testClass.getDeclaredMethods();
452 +        ArrayList<String> names = new ArrayList<String>(methods.length);
453 +        for (Method method : methods) {
454 +            if (method.getName().startsWith("test")
455 +                && Modifier.isPublic(method.getModifiers())
456 +                // method.getParameterCount() requires jdk8+
457 +                && method.getParameterTypes().length == 0) {
458 +                names.add(method.getName());
459 +            }
460 +        }
461 +        return names;
462      }
463  
464 +    /**
465 +     * Returns junit-style testSuite for the given test class, but
466 +     * parameterized by passing extra data to each test.
467 +     */
468 +    public static <ExtraData> Test parameterizedTestSuite
469 +        (Class<? extends JSR166TestCase> testClass,
470 +         Class<ExtraData> dataClass,
471 +         ExtraData data) {
472 +        try {
473 +            TestSuite suite = new TestSuite();
474 +            Constructor c =
475 +                testClass.getDeclaredConstructor(dataClass, String.class);
476 +            for (String methodName : testMethodNames(testClass))
477 +                suite.addTest((Test) c.newInstance(data, methodName));
478 +            return suite;
479 +        } catch (Exception e) {
480 +            throw new Error(e);
481 +        }
482 +    }
483 +
484 +    /**
485 +     * Returns junit-style testSuite for the jdk8 extension of the
486 +     * given test class, but parameterized by passing extra data to
487 +     * each test.  Uses reflection to allow compilation in jdk7.
488 +     */
489 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
490 +        (Class<? extends JSR166TestCase> testClass,
491 +         Class<ExtraData> dataClass,
492 +         ExtraData data) {
493 +        if (atLeastJava8()) {
494 +            String name = testClass.getName();
495 +            String name8 = name.replaceAll("Test$", "8Test");
496 +            if (name.equals(name8)) throw new Error(name);
497 +            try {
498 +                return (Test)
499 +                    Class.forName(name8)
500 +                    .getMethod("testSuite", new Class[] { dataClass })
501 +                    .invoke(null, data);
502 +            } catch (Exception e) {
503 +                throw new Error(e);
504 +            }
505 +        } else {
506 +            return new TestSuite();
507 +        }
508 +    }
509 +
510 +    // Delays for timing-dependent tests, in milliseconds.
511  
512      public static long SHORT_DELAY_MS;
513      public static long SMALL_DELAY_MS;
514      public static long MEDIUM_DELAY_MS;
515      public static long LONG_DELAY_MS;
516  
246
517      /**
518       * Returns the shortest timed delay. This could
519       * be reimplemented to use for example a Property.
# Line 252 | Line 522 | public class JSR166TestCase extends Test
522          return 50;
523      }
524  
255
525      /**
526       * Sets delays as multiples of SHORT_DELAY.
527       */
# Line 260 | Line 529 | public class JSR166TestCase extends Test
529          SHORT_DELAY_MS = getShortDelay();
530          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
531          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
532 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
532 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
533 >    }
534 >
535 >    /**
536 >     * Returns a timeout in milliseconds to be used in tests that
537 >     * verify that operations block or time out.
538 >     */
539 >    long timeoutMillis() {
540 >        return SHORT_DELAY_MS / 4;
541 >    }
542 >
543 >    /**
544 >     * Returns a new Date instance representing a time at least
545 >     * delayMillis milliseconds in the future.
546 >     */
547 >    Date delayedDate(long delayMillis) {
548 >        // Add 1 because currentTimeMillis is known to round into the past.
549 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
550      }
551  
552      /**
# Line 276 | Line 562 | public class JSR166TestCase extends Test
562       * the same test have no effect.
563       */
564      public void threadRecordFailure(Throwable t) {
565 +        System.err.println(t);
566 +        dumpTestThreads();
567          threadFailure.compareAndSet(null, t);
568      }
569  
# Line 283 | Line 571 | public class JSR166TestCase extends Test
571          setDelays();
572      }
573  
574 +    void tearDownFail(String format, Object... args) {
575 +        String msg = toString() + ": " + String.format(format, args);
576 +        System.err.println(msg);
577 +        dumpTestThreads();
578 +        throw new AssertionFailedError(msg);
579 +    }
580 +
581      /**
582 +     * Extra checks that get done for all test cases.
583 +     *
584       * Triggers test case failure if any thread assertions have failed,
585       * by rethrowing, in the test harness thread, any exception recorded
586       * earlier by threadRecordFailure.
587 +     *
588 +     * Triggers test case failure if interrupt status is set in the main thread.
589       */
590      public void tearDown() throws Exception {
591 <        Throwable t = threadFailure.get();
591 >        Throwable t = threadFailure.getAndSet(null);
592          if (t != null) {
593              if (t instanceof Error)
594                  throw (Error) t;
# Line 304 | Line 603 | public class JSR166TestCase extends Test
603                  throw afe;
604              }
605          }
606 +
607 +        if (Thread.interrupted())
608 +            tearDownFail("interrupt status set in main thread");
609 +
610 +        checkForkJoinPoolThreadLeaks();
611 +    }
612 +
613 +    /**
614 +     * Finds missing PoolCleaners
615 +     */
616 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
617 +        Thread[] survivors = new Thread[7];
618 +        int count = Thread.enumerate(survivors);
619 +        for (int i = 0; i < count; i++) {
620 +            Thread thread = survivors[i];
621 +            String name = thread.getName();
622 +            if (name.startsWith("ForkJoinPool-")) {
623 +                // give thread some time to terminate
624 +                thread.join(LONG_DELAY_MS);
625 +                if (thread.isAlive())
626 +                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
627 +                                 thread);
628 +            }
629 +        }
630 +
631 +        if (!ForkJoinPool.commonPool()
632 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
633 +            tearDownFail("ForkJoin common pool thread stuck");
634      }
635  
636      /**
# Line 316 | Line 643 | public class JSR166TestCase extends Test
643              fail(reason);
644          } catch (AssertionFailedError t) {
645              threadRecordFailure(t);
646 <            fail(reason);
646 >            throw t;
647          }
648      }
649  
# Line 384 | Line 711 | public class JSR166TestCase extends Test
711      public void threadAssertEquals(Object x, Object y) {
712          try {
713              assertEquals(x, y);
714 <        } catch (AssertionFailedError t) {
715 <            threadRecordFailure(t);
716 <            throw t;
717 <        } catch (Throwable t) {
718 <            threadUnexpectedException(t);
714 >        } catch (AssertionFailedError fail) {
715 >            threadRecordFailure(fail);
716 >            throw fail;
717 >        } catch (Throwable fail) {
718 >            threadUnexpectedException(fail);
719          }
720      }
721  
# Line 400 | Line 727 | public class JSR166TestCase extends Test
727      public void threadAssertSame(Object x, Object y) {
728          try {
729              assertSame(x, y);
730 <        } catch (AssertionFailedError t) {
731 <            threadRecordFailure(t);
732 <            throw t;
730 >        } catch (AssertionFailedError fail) {
731 >            threadRecordFailure(fail);
732 >            throw fail;
733          }
734      }
735  
# Line 435 | Line 762 | public class JSR166TestCase extends Test
762          else {
763              AssertionFailedError afe =
764                  new AssertionFailedError("unexpected exception: " + t);
765 <            t.initCause(t);
765 >            afe.initCause(t);
766              throw afe;
767          }
768      }
769  
770      /**
771 +     * Delays, via Thread.sleep, for the given millisecond delay, but
772 +     * if the sleep is shorter than specified, may re-sleep or yield
773 +     * until time elapses.  Ensures that the given time, as measured
774 +     * by System.nanoTime(), has elapsed.
775 +     */
776 +    static void delay(long millis) throws InterruptedException {
777 +        long nanos = millis * (1000 * 1000);
778 +        final long wakeupTime = System.nanoTime() + nanos;
779 +        do {
780 +            if (millis > 0L)
781 +                Thread.sleep(millis);
782 +            else // too short to sleep
783 +                Thread.yield();
784 +            nanos = wakeupTime - System.nanoTime();
785 +            millis = nanos / (1000 * 1000);
786 +        } while (nanos >= 0L);
787 +    }
788 +
789 +    /**
790 +     * Allows use of try-with-resources with per-test thread pools.
791 +     */
792 +    class PoolCleaner implements AutoCloseable {
793 +        private final ExecutorService pool;
794 +        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
795 +        public void close() { joinPool(pool); }
796 +    }
797 +
798 +    /**
799 +     * An extension of PoolCleaner that has an action to release the pool.
800 +     */
801 +    class PoolCleanerWithReleaser extends PoolCleaner {
802 +        private final Runnable releaser;
803 +        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
804 +            super(pool);
805 +            this.releaser = releaser;
806 +        }
807 +        public void close() {
808 +            try {
809 +                releaser.run();
810 +            } finally {
811 +                super.close();
812 +            }
813 +        }
814 +    }
815 +
816 +    PoolCleaner cleaner(ExecutorService pool) {
817 +        return new PoolCleaner(pool);
818 +    }
819 +
820 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
821 +        return new PoolCleanerWithReleaser(pool, releaser);
822 +    }
823 +
824 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
825 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
826 +    }
827 +
828 +    Runnable releaser(final CountDownLatch latch) {
829 +        return new Runnable() { public void run() {
830 +            do { latch.countDown(); }
831 +            while (latch.getCount() > 0);
832 +        }};
833 +    }
834 +
835 +    /**
836       * Waits out termination of a thread pool or fails doing so.
837       */
838 <    public void joinPool(ExecutorService exec) {
838 >    void joinPool(ExecutorService pool) {
839          try {
840 <            exec.shutdown();
841 <            assertTrue("ExecutorService did not terminate in a timely manner",
842 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
840 >            pool.shutdown();
841 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
842 >                try {
843 >                    threadFail("ExecutorService " + pool +
844 >                               " did not terminate in a timely manner");
845 >                } finally {
846 >                    // last resort, for the benefit of subsequent tests
847 >                    pool.shutdownNow();
848 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
849 >                }
850 >            }
851          } catch (SecurityException ok) {
852              // Allowed in case test doesn't have privs
853 <        } catch (InterruptedException ie) {
854 <            fail("Unexpected InterruptedException");
853 >        } catch (InterruptedException fail) {
854 >            threadFail("Unexpected InterruptedException");
855 >        }
856 >    }
857 >
858 >    /** Like Runnable, but with the freedom to throw anything */
859 >    interface Action { public void run() throws Throwable; }
860 >
861 >    /**
862 >     * Runs all the given actions in parallel, failing if any fail.
863 >     * Useful for running multiple variants of tests that are
864 >     * necessarily individually slow because they must block.
865 >     */
866 >    void testInParallel(Action ... actions) {
867 >        ExecutorService pool = Executors.newCachedThreadPool();
868 >        try (PoolCleaner cleaner = cleaner(pool)) {
869 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
870 >            for (final Action action : actions)
871 >                futures.add(pool.submit(new CheckedRunnable() {
872 >                    public void realRun() throws Throwable { action.run();}}));
873 >            for (Future<?> future : futures)
874 >                try {
875 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
876 >                } catch (ExecutionException ex) {
877 >                    threadUnexpectedException(ex.getCause());
878 >                } catch (Exception ex) {
879 >                    threadUnexpectedException(ex);
880 >                }
881 >        }
882 >    }
883 >
884 >    /**
885 >     * A debugging tool to print stack traces of most threads, as jstack does.
886 >     * Uninteresting threads are filtered out.
887 >     */
888 >    static void dumpTestThreads() {
889 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
890 >        System.err.println("------ stacktrace dump start ------");
891 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
892 >            String name = info.getThreadName();
893 >            if ("Signal Dispatcher".equals(name))
894 >                continue;
895 >            if ("Reference Handler".equals(name)
896 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
897 >                continue;
898 >            if ("Finalizer".equals(name)
899 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
900 >                continue;
901 >            if ("checkForWedgedTest".equals(name))
902 >                continue;
903 >            System.err.print(info);
904 >        }
905 >        System.err.println("------ stacktrace dump end ------");
906 >    }
907 >
908 >    /**
909 >     * Checks that thread does not terminate within the default
910 >     * millisecond delay of {@code timeoutMillis()}.
911 >     */
912 >    void assertThreadStaysAlive(Thread thread) {
913 >        assertThreadStaysAlive(thread, timeoutMillis());
914 >    }
915 >
916 >    /**
917 >     * Checks that thread does not terminate within the given millisecond delay.
918 >     */
919 >    void assertThreadStaysAlive(Thread thread, long millis) {
920 >        try {
921 >            // No need to optimize the failing case via Thread.join.
922 >            delay(millis);
923 >            assertTrue(thread.isAlive());
924 >        } catch (InterruptedException fail) {
925 >            threadFail("Unexpected InterruptedException");
926 >        }
927 >    }
928 >
929 >    /**
930 >     * Checks that the threads do not terminate within the default
931 >     * millisecond delay of {@code timeoutMillis()}.
932 >     */
933 >    void assertThreadsStayAlive(Thread... threads) {
934 >        assertThreadsStayAlive(timeoutMillis(), threads);
935 >    }
936 >
937 >    /**
938 >     * Checks that the threads do not terminate within the given millisecond delay.
939 >     */
940 >    void assertThreadsStayAlive(long millis, Thread... threads) {
941 >        try {
942 >            // No need to optimize the failing case via Thread.join.
943 >            delay(millis);
944 >            for (Thread thread : threads)
945 >                assertTrue(thread.isAlive());
946 >        } catch (InterruptedException fail) {
947 >            threadFail("Unexpected InterruptedException");
948          }
949      }
950  
951 +    /**
952 +     * Checks that future.get times out, with the default timeout of
953 +     * {@code timeoutMillis()}.
954 +     */
955 +    void assertFutureTimesOut(Future future) {
956 +        assertFutureTimesOut(future, timeoutMillis());
957 +    }
958 +
959 +    /**
960 +     * Checks that future.get times out, with the given millisecond timeout.
961 +     */
962 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
963 +        long startTime = System.nanoTime();
964 +        try {
965 +            future.get(timeoutMillis, MILLISECONDS);
966 +            shouldThrow();
967 +        } catch (TimeoutException success) {
968 +        } catch (Exception fail) {
969 +            threadUnexpectedException(fail);
970 +        } finally { future.cancel(true); }
971 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
972 +    }
973  
974      /**
975       * Fails with message "should throw exception".
# Line 495 | Line 1010 | public class JSR166TestCase extends Test
1010      public static final Integer m6  = new Integer(-6);
1011      public static final Integer m10 = new Integer(-10);
1012  
498
1013      /**
1014       * Runs Runnable r with a security policy that permits precisely
1015       * the specified permissions.  If there is no current security
# Line 507 | Line 1021 | public class JSR166TestCase extends Test
1021          SecurityManager sm = System.getSecurityManager();
1022          if (sm == null) {
1023              r.run();
1024 +        }
1025 +        runWithSecurityManagerWithPermissions(r, permissions);
1026 +    }
1027 +
1028 +    /**
1029 +     * Runs Runnable r with a security policy that permits precisely
1030 +     * the specified permissions.  If there is no current security
1031 +     * manager, a temporary one is set for the duration of the
1032 +     * Runnable.  We require that any security manager permit
1033 +     * getPolicy/setPolicy.
1034 +     */
1035 +    public void runWithSecurityManagerWithPermissions(Runnable r,
1036 +                                                      Permission... permissions) {
1037 +        SecurityManager sm = System.getSecurityManager();
1038 +        if (sm == null) {
1039              Policy savedPolicy = Policy.getPolicy();
1040              try {
1041                  Policy.setPolicy(permissivePolicy());
1042                  System.setSecurityManager(new SecurityManager());
1043 <                runWithPermissions(r, permissions);
1043 >                runWithSecurityManagerWithPermissions(r, permissions);
1044              } finally {
1045                  System.setSecurityManager(null);
1046                  Policy.setPolicy(savedPolicy);
# Line 559 | Line 1088 | public class JSR166TestCase extends Test
1088              return perms.implies(p);
1089          }
1090          public void refresh() {}
1091 +        public String toString() {
1092 +            List<Permission> ps = new ArrayList<Permission>();
1093 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1094 +                ps.add(e.nextElement());
1095 +            return "AdjustablePolicy with permissions " + ps;
1096 +        }
1097      }
1098  
1099      /**
# Line 586 | Line 1121 | public class JSR166TestCase extends Test
1121       */
1122      void sleep(long millis) {
1123          try {
1124 <            Thread.sleep(millis);
1125 <        } catch (InterruptedException ie) {
1124 >            delay(millis);
1125 >        } catch (InterruptedException fail) {
1126              AssertionFailedError afe =
1127                  new AssertionFailedError("Unexpected InterruptedException");
1128 <            afe.initCause(ie);
1128 >            afe.initCause(fail);
1129              throw afe;
1130          }
1131      }
1132  
1133      /**
1134 <     * Sleeps until the timeout has elapsed, or interrupted.
600 <     * Does <em>NOT</em> throw InterruptedException.
601 <     */
602 <    void sleepTillInterrupted(long timeoutMillis) {
603 <        try {
604 <            Thread.sleep(timeoutMillis);
605 <        } catch (InterruptedException wakeup) {}
606 <    }
607 <
608 <    /**
609 <     * Waits up to the specified number of milliseconds for the given
1134 >     * Spin-waits up to the specified number of milliseconds for the given
1135       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1136       */
1137      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1138 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
614 <        long t0 = System.nanoTime();
1138 >        long startTime = System.nanoTime();
1139          for (;;) {
1140              Thread.State s = thread.getState();
1141              if (s == Thread.State.BLOCKED ||
# Line 620 | Line 1144 | public class JSR166TestCase extends Test
1144                  return;
1145              else if (s == Thread.State.TERMINATED)
1146                  fail("Unexpected thread termination");
1147 <            else if (System.nanoTime() - t0 > timeoutNanos) {
1147 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1148                  threadAssertTrue(thread.isAlive());
1149                  return;
1150              }
# Line 629 | Line 1153 | public class JSR166TestCase extends Test
1153      }
1154  
1155      /**
1156 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1157 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
1158 +     */
1159 +    void waitForThreadToEnterWaitState(Thread thread) {
1160 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1161 +    }
1162 +
1163 +    /**
1164       * Returns the number of milliseconds since time given by
1165       * startNanoTime, which must have been previously returned from a
1166 <     * call to {@link System.nanoTime()}.
1166 >     * call to {@link System#nanoTime()}.
1167       */
1168 <    long millisElapsedSince(long startNanoTime) {
1168 >    static long millisElapsedSince(long startNanoTime) {
1169          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1170      }
1171 <    
1171 >
1172 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1173 > //         long startTime = System.nanoTime();
1174 > //         try {
1175 > //             r.run();
1176 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1177 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1178 > //             throw new AssertionFailedError("did not return promptly");
1179 > //     }
1180 >
1181 > //     void assertTerminatesPromptly(Runnable r) {
1182 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1183 > //     }
1184 >
1185 >    /**
1186 >     * Checks that timed f.get() returns the expected value, and does not
1187 >     * wait for the timeout to elapse before returning.
1188 >     */
1189 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1190 >        long startTime = System.nanoTime();
1191 >        try {
1192 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1193 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1194 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1195 >            throw new AssertionFailedError("timed get did not return promptly");
1196 >    }
1197 >
1198 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1199 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1200 >    }
1201 >
1202      /**
1203       * Returns a new started daemon Thread running the given runnable.
1204       */
# Line 655 | Line 1217 | public class JSR166TestCase extends Test
1217      void awaitTermination(Thread t, long timeoutMillis) {
1218          try {
1219              t.join(timeoutMillis);
1220 <        } catch (InterruptedException ie) {
1221 <            threadUnexpectedException(ie);
1220 >        } catch (InterruptedException fail) {
1221 >            threadUnexpectedException(fail);
1222          } finally {
1223 <            if (t.isAlive()) {
1223 >            if (t.getState() != Thread.State.TERMINATED) {
1224                  t.interrupt();
1225 <                fail("Test timed out");
1225 >                threadFail("Test timed out");
1226              }
1227          }
1228      }
1229  
1230 +    /**
1231 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1232 +     * terminate (using {@link Thread#join(long)}), else interrupts
1233 +     * the thread (in the hope that it may terminate later) and fails.
1234 +     */
1235 +    void awaitTermination(Thread t) {
1236 +        awaitTermination(t, LONG_DELAY_MS);
1237 +    }
1238 +
1239      // Some convenient Runnable classes
1240  
1241      public abstract class CheckedRunnable implements Runnable {
# Line 673 | Line 1244 | public class JSR166TestCase extends Test
1244          public final void run() {
1245              try {
1246                  realRun();
1247 <            } catch (Throwable t) {
1248 <                threadUnexpectedException(t);
1247 >            } catch (Throwable fail) {
1248 >                threadUnexpectedException(fail);
1249              }
1250          }
1251      }
# Line 727 | Line 1298 | public class JSR166TestCase extends Test
1298                  realRun();
1299                  threadShouldThrow("InterruptedException");
1300              } catch (InterruptedException success) {
1301 <            } catch (Throwable t) {
1302 <                threadUnexpectedException(t);
1301 >                threadAssertFalse(Thread.interrupted());
1302 >            } catch (Throwable fail) {
1303 >                threadUnexpectedException(fail);
1304              }
1305          }
1306      }
# Line 739 | Line 1311 | public class JSR166TestCase extends Test
1311          public final T call() {
1312              try {
1313                  return realCall();
1314 <            } catch (Throwable t) {
1315 <                threadUnexpectedException(t);
1314 >            } catch (Throwable fail) {
1315 >                threadUnexpectedException(fail);
1316                  return null;
1317              }
1318          }
# Line 756 | Line 1328 | public class JSR166TestCase extends Test
1328                  threadShouldThrow("InterruptedException");
1329                  return result;
1330              } catch (InterruptedException success) {
1331 <            } catch (Throwable t) {
1332 <                threadUnexpectedException(t);
1331 >                threadAssertFalse(Thread.interrupted());
1332 >            } catch (Throwable fail) {
1333 >                threadUnexpectedException(fail);
1334              }
1335              return null;
1336          }
# Line 774 | Line 1347 | public class JSR166TestCase extends Test
1347      public static final String TEST_STRING = "a test string";
1348  
1349      public static class StringTask implements Callable<String> {
1350 <        public String call() { return TEST_STRING; }
1350 >        final String value;
1351 >        public StringTask() { this(TEST_STRING); }
1352 >        public StringTask(String value) { this.value = value; }
1353 >        public String call() { return value; }
1354      }
1355  
1356      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 787 | Line 1363 | public class JSR166TestCase extends Test
1363              }};
1364      }
1365  
1366 +    public Runnable countDowner(final CountDownLatch latch) {
1367 +        return new CheckedRunnable() {
1368 +            public void realRun() throws InterruptedException {
1369 +                latch.countDown();
1370 +            }};
1371 +    }
1372 +
1373 +    class LatchAwaiter extends CheckedRunnable {
1374 +        static final int NEW = 0;
1375 +        static final int RUNNING = 1;
1376 +        static final int DONE = 2;
1377 +        final CountDownLatch latch;
1378 +        int state = NEW;
1379 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1380 +        public void realRun() throws InterruptedException {
1381 +            state = 1;
1382 +            await(latch);
1383 +            state = 2;
1384 +        }
1385 +    }
1386 +
1387 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1388 +        return new LatchAwaiter(latch);
1389 +    }
1390 +
1391 +    public void await(CountDownLatch latch) {
1392 +        try {
1393 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1394 +        } catch (Throwable fail) {
1395 +            threadUnexpectedException(fail);
1396 +        }
1397 +    }
1398 +
1399 +    public void await(Semaphore semaphore) {
1400 +        try {
1401 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1402 +        } catch (Throwable fail) {
1403 +            threadUnexpectedException(fail);
1404 +        }
1405 +    }
1406 +
1407 + //     /**
1408 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1409 + //      */
1410 + //     public void await(AtomicBoolean flag) {
1411 + //         await(flag, LONG_DELAY_MS);
1412 + //     }
1413 +
1414 + //     /**
1415 + //      * Spin-waits up to the specified timeout until flag becomes true.
1416 + //      */
1417 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1418 + //         long startTime = System.nanoTime();
1419 + //         while (!flag.get()) {
1420 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1421 + //                 throw new AssertionFailedError("timed out");
1422 + //             Thread.yield();
1423 + //         }
1424 + //     }
1425 +
1426      public static class NPETask implements Callable<String> {
1427          public String call() { throw new NullPointerException(); }
1428      }
# Line 797 | Line 1433 | public class JSR166TestCase extends Test
1433  
1434      public class ShortRunnable extends CheckedRunnable {
1435          protected void realRun() throws Throwable {
1436 <            Thread.sleep(SHORT_DELAY_MS);
1436 >            delay(SHORT_DELAY_MS);
1437          }
1438      }
1439  
1440      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1441          protected void realRun() throws InterruptedException {
1442 <            Thread.sleep(SHORT_DELAY_MS);
1442 >            delay(SHORT_DELAY_MS);
1443          }
1444      }
1445  
1446      public class SmallRunnable extends CheckedRunnable {
1447          protected void realRun() throws Throwable {
1448 <            Thread.sleep(SMALL_DELAY_MS);
1448 >            delay(SMALL_DELAY_MS);
1449          }
1450      }
1451  
1452      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1453          protected void realRun() {
1454              try {
1455 <                Thread.sleep(SMALL_DELAY_MS);
1455 >                delay(SMALL_DELAY_MS);
1456              } catch (InterruptedException ok) {}
1457          }
1458      }
1459  
1460      public class SmallCallable extends CheckedCallable {
1461          protected Object realCall() throws InterruptedException {
1462 <            Thread.sleep(SMALL_DELAY_MS);
1462 >            delay(SMALL_DELAY_MS);
1463              return Boolean.TRUE;
1464          }
1465      }
1466  
1467      public class MediumRunnable extends CheckedRunnable {
1468          protected void realRun() throws Throwable {
1469 <            Thread.sleep(MEDIUM_DELAY_MS);
1469 >            delay(MEDIUM_DELAY_MS);
1470          }
1471      }
1472  
1473      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1474          protected void realRun() throws InterruptedException {
1475 <            Thread.sleep(MEDIUM_DELAY_MS);
1475 >            delay(MEDIUM_DELAY_MS);
1476          }
1477      }
1478  
# Line 844 | Line 1480 | public class JSR166TestCase extends Test
1480          return new CheckedRunnable() {
1481              protected void realRun() {
1482                  try {
1483 <                    Thread.sleep(timeoutMillis);
1483 >                    delay(timeoutMillis);
1484                  } catch (InterruptedException ok) {}
1485              }};
1486      }
# Line 852 | Line 1488 | public class JSR166TestCase extends Test
1488      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1489          protected void realRun() {
1490              try {
1491 <                Thread.sleep(MEDIUM_DELAY_MS);
1491 >                delay(MEDIUM_DELAY_MS);
1492              } catch (InterruptedException ok) {}
1493          }
1494      }
# Line 860 | Line 1496 | public class JSR166TestCase extends Test
1496      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1497          protected void realRun() {
1498              try {
1499 <                Thread.sleep(LONG_DELAY_MS);
1499 >                delay(LONG_DELAY_MS);
1500              } catch (InterruptedException ok) {}
1501          }
1502      }
# Line 884 | Line 1520 | public class JSR166TestCase extends Test
1520                  public boolean isDone() { return done; }
1521                  public void run() {
1522                      try {
1523 <                        Thread.sleep(timeoutMillis);
1523 >                        delay(timeoutMillis);
1524                          done = true;
1525                      } catch (InterruptedException ok) {}
1526                  }
# Line 895 | Line 1531 | public class JSR166TestCase extends Test
1531          public volatile boolean done = false;
1532          public void run() {
1533              try {
1534 <                Thread.sleep(SHORT_DELAY_MS);
1534 >                delay(SHORT_DELAY_MS);
1535                  done = true;
1536              } catch (InterruptedException ok) {}
1537          }
# Line 905 | Line 1541 | public class JSR166TestCase extends Test
1541          public volatile boolean done = false;
1542          public void run() {
1543              try {
1544 <                Thread.sleep(SMALL_DELAY_MS);
1544 >                delay(SMALL_DELAY_MS);
1545                  done = true;
1546              } catch (InterruptedException ok) {}
1547          }
# Line 915 | Line 1551 | public class JSR166TestCase extends Test
1551          public volatile boolean done = false;
1552          public void run() {
1553              try {
1554 <                Thread.sleep(MEDIUM_DELAY_MS);
1554 >                delay(MEDIUM_DELAY_MS);
1555                  done = true;
1556              } catch (InterruptedException ok) {}
1557          }
# Line 925 | Line 1561 | public class JSR166TestCase extends Test
1561          public volatile boolean done = false;
1562          public void run() {
1563              try {
1564 <                Thread.sleep(LONG_DELAY_MS);
1564 >                delay(LONG_DELAY_MS);
1565                  done = true;
1566              } catch (InterruptedException ok) {}
1567          }
# Line 942 | Line 1578 | public class JSR166TestCase extends Test
1578          public volatile boolean done = false;
1579          public Object call() {
1580              try {
1581 <                Thread.sleep(SMALL_DELAY_MS);
1581 >                delay(SMALL_DELAY_MS);
1582                  done = true;
1583              } catch (InterruptedException ok) {}
1584              return Boolean.TRUE;
# Line 955 | Line 1591 | public class JSR166TestCase extends Test
1591      public abstract class CheckedRecursiveAction extends RecursiveAction {
1592          protected abstract void realCompute() throws Throwable;
1593  
1594 <        public final void compute() {
1594 >        @Override protected final void compute() {
1595              try {
1596                  realCompute();
1597 <            } catch (Throwable t) {
1598 <                threadUnexpectedException(t);
1597 >            } catch (Throwable fail) {
1598 >                threadUnexpectedException(fail);
1599              }
1600          }
1601      }
# Line 970 | Line 1606 | public class JSR166TestCase extends Test
1606      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1607          protected abstract T realCompute() throws Throwable;
1608  
1609 <        public final T compute() {
1609 >        @Override protected final T compute() {
1610              try {
1611                  return realCompute();
1612 <            } catch (Throwable t) {
1613 <                threadUnexpectedException(t);
1612 >            } catch (Throwable fail) {
1613 >                threadUnexpectedException(fail);
1614                  return null;
1615              }
1616          }
# Line 989 | Line 1625 | public class JSR166TestCase extends Test
1625      }
1626  
1627      /**
1628 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1629 <     * of throwing checked exceptions.
1628 >     * A CyclicBarrier that uses timed await and fails with
1629 >     * AssertionFailedErrors instead of throwing checked exceptions.
1630       */
1631      public class CheckedBarrier extends CyclicBarrier {
1632          public CheckedBarrier(int parties) { super(parties); }
1633  
1634          public int await() {
1635              try {
1636 <                return super.await();
1637 <            } catch (Exception e) {
1636 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1637 >            } catch (TimeoutException timedOut) {
1638 >                throw new AssertionFailedError("timed out");
1639 >            } catch (Exception fail) {
1640                  AssertionFailedError afe =
1641 <                    new AssertionFailedError("Unexpected exception: " + e);
1642 <                afe.initCause(e);
1641 >                    new AssertionFailedError("Unexpected exception: " + fail);
1642 >                afe.initCause(fail);
1643                  throw afe;
1644              }
1645          }
1646      }
1647  
1648 +    void checkEmpty(BlockingQueue q) {
1649 +        try {
1650 +            assertTrue(q.isEmpty());
1651 +            assertEquals(0, q.size());
1652 +            assertNull(q.peek());
1653 +            assertNull(q.poll());
1654 +            assertNull(q.poll(0, MILLISECONDS));
1655 +            assertEquals(q.toString(), "[]");
1656 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1657 +            assertFalse(q.iterator().hasNext());
1658 +            try {
1659 +                q.element();
1660 +                shouldThrow();
1661 +            } catch (NoSuchElementException success) {}
1662 +            try {
1663 +                q.iterator().next();
1664 +                shouldThrow();
1665 +            } catch (NoSuchElementException success) {}
1666 +            try {
1667 +                q.remove();
1668 +                shouldThrow();
1669 +            } catch (NoSuchElementException success) {}
1670 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1671 +    }
1672 +
1673 +    void assertSerialEquals(Object x, Object y) {
1674 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1675 +    }
1676 +
1677 +    void assertNotSerialEquals(Object x, Object y) {
1678 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1679 +    }
1680 +
1681 +    byte[] serialBytes(Object o) {
1682 +        try {
1683 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1684 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1685 +            oos.writeObject(o);
1686 +            oos.flush();
1687 +            oos.close();
1688 +            return bos.toByteArray();
1689 +        } catch (Throwable fail) {
1690 +            threadUnexpectedException(fail);
1691 +            return new byte[0];
1692 +        }
1693 +    }
1694 +
1695 +    @SuppressWarnings("unchecked")
1696 +    <T> T serialClone(T o) {
1697 +        try {
1698 +            ObjectInputStream ois = new ObjectInputStream
1699 +                (new ByteArrayInputStream(serialBytes(o)));
1700 +            T clone = (T) ois.readObject();
1701 +            assertSame(o.getClass(), clone.getClass());
1702 +            return clone;
1703 +        } catch (Throwable fail) {
1704 +            threadUnexpectedException(fail);
1705 +            return null;
1706 +        }
1707 +    }
1708 +
1709 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1710 +                             Runnable... throwingActions) {
1711 +        for (Runnable throwingAction : throwingActions) {
1712 +            boolean threw = false;
1713 +            try { throwingAction.run(); }
1714 +            catch (Throwable t) {
1715 +                threw = true;
1716 +                if (!expectedExceptionClass.isInstance(t)) {
1717 +                    AssertionFailedError afe =
1718 +                        new AssertionFailedError
1719 +                        ("Expected " + expectedExceptionClass.getName() +
1720 +                         ", got " + t.getClass().getName());
1721 +                    afe.initCause(t);
1722 +                    threadUnexpectedException(afe);
1723 +                }
1724 +            }
1725 +            if (!threw)
1726 +                shouldThrow(expectedExceptionClass.getName());
1727 +        }
1728 +    }
1729 +
1730 +    public void assertIteratorExhausted(Iterator<?> it) {
1731 +        try {
1732 +            it.next();
1733 +            shouldThrow();
1734 +        } catch (NoSuchElementException success) {}
1735 +        assertFalse(it.hasNext());
1736 +    }
1737   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines