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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines