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.91 by jsr166, Thu Dec 8 18:54:46 2011 UTC vs.
Revision 1.172 by jsr166, Fri Oct 9 01:26:36 2015 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
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.util.Arrays;
18 < import java.util.Date;
19 < import java.util.NoSuchElementException;
20 < import java.util.PropertyPermission;
21 < import java.util.concurrent.*;
22 < import java.util.concurrent.atomic.AtomicBoolean;
23 < import java.util.concurrent.atomic.AtomicReference;
24 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
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 27 | 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 38 | 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 60 | 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 109 | 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 122 | 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) {
157 <            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          }
161        System.exit(0);
287      }
288  
289      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 174 | 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 243 | 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  
254
517      /**
518       * Returns the shortest timed delay. This could
519       * be reimplemented to use for example a Property.
# Line 279 | Line 541 | public class JSR166TestCase extends Test
541      }
542  
543      /**
544 <     * Returns a new Date instance representing a time delayMillis
545 <     * milliseconds in the future.
544 >     * Returns a new Date instance representing a time at least
545 >     * delayMillis milliseconds in the future.
546       */
547      Date delayedDate(long delayMillis) {
548 <        return new Date(System.currentTimeMillis() + 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 299 | 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 306 | 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       *
# Line 333 | Line 605 | public class JSR166TestCase extends Test
605          }
606  
607          if (Thread.interrupted())
608 <            throw new AssertionFailedError("interrupt status set in main thread");
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 346 | 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 414 | 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 430 | 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 473 | Line 770 | public class JSR166TestCase extends Test
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.
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 startTime = System.nanoTime();
778 <        long ns = millis * 1000 * 1000;
779 <        for (;;) {
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 <            long d = ns - (System.nanoTime() - startTime);
785 <            if (d > 0L)
786 <                millis = d / (1000 * 1000);
787 <            else
788 <                break;
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 <    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(2 * 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      /**
# Line 522 | Line 921 | public class JSR166TestCase extends Test
921              // No need to optimize the failing case via Thread.join.
922              delay(millis);
923              assertTrue(thread.isAlive());
924 <        } catch (InterruptedException ie) {
925 <            fail("Unexpected InterruptedException");
924 >        } catch (InterruptedException fail) {
925 >            threadFail("Unexpected InterruptedException");
926          }
927      }
928  
# Line 544 | Line 943 | public class JSR166TestCase extends Test
943              delay(millis);
944              for (Thread thread : threads)
945                  assertTrue(thread.isAlive());
946 <        } catch (InterruptedException ie) {
947 <            fail("Unexpected InterruptedException");
946 >        } catch (InterruptedException fail) {
947 >            threadFail("Unexpected InterruptedException");
948          }
949      }
950  
# Line 566 | Line 965 | public class JSR166TestCase extends Test
965              future.get(timeoutMillis, MILLISECONDS);
966              shouldThrow();
967          } catch (TimeoutException success) {
968 <        } catch (Exception e) {
969 <            threadUnexpectedException(e);
968 >        } catch (Exception fail) {
969 >            threadUnexpectedException(fail);
970          } finally { future.cancel(true); }
971          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
972      }
# Line 611 | 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  
614
1013      /**
1014       * Runs Runnable r with a security policy that permits precisely
1015       * the specified permissions.  If there is no current security
# Line 623 | 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 675 | 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 703 | Line 1122 | public class JSR166TestCase extends Test
1122      void sleep(long millis) {
1123          try {
1124              delay(millis);
1125 <        } catch (InterruptedException ie) {
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      }
# Line 744 | Line 1163 | public class JSR166TestCase extends Test
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  
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 768 | 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.getState() != Thread.State.TERMINATED) {
1224                  t.interrupt();
1225 <                fail("Test timed out");
1225 >                threadFail("Test timed out");
1226              }
1227          }
1228      }
# Line 795 | 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 850 | Line 1299 | public class JSR166TestCase extends Test
1299                  threadShouldThrow("InterruptedException");
1300              } catch (InterruptedException success) {
1301                  threadAssertFalse(Thread.interrupted());
1302 <            } catch (Throwable t) {
1303 <                threadUnexpectedException(t);
1302 >            } catch (Throwable fail) {
1303 >                threadUnexpectedException(fail);
1304              }
1305          }
1306      }
# Line 862 | 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 880 | Line 1329 | public class JSR166TestCase extends Test
1329                  return result;
1330              } catch (InterruptedException success) {
1331                  threadAssertFalse(Thread.interrupted());
1332 <            } catch (Throwable t) {
1333 <                threadUnexpectedException(t);
1332 >            } catch (Throwable fail) {
1333 >                threadUnexpectedException(fail);
1334              }
1335              return null;
1336          }
# Line 898 | 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 911 | Line 1363 | public class JSR166TestCase extends Test
1363              }};
1364      }
1365  
1366 <    public Runnable awaiter(final CountDownLatch latch) {
1366 >    public Runnable countDowner(final CountDownLatch latch) {
1367          return new CheckedRunnable() {
1368              public void realRun() throws InterruptedException {
1369 <                await(latch);
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 t) {
1395 <            threadUnexpectedException(t);
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 t) {
1403 <            threadUnexpectedException(t);
1402 >        } catch (Throwable fail) {
1403 >            threadUnexpectedException(fail);
1404          }
1405      }
1406  
# Line 1121 | 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 1136 | 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 1164 | Line 1634 | public class JSR166TestCase extends Test
1634          public int await() {
1635              try {
1636                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1637 <            } catch (TimeoutException e) {
1637 >            } catch (TimeoutException timedOut) {
1638                  throw new AssertionFailedError("timed out");
1639 <            } catch (Exception e) {
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          }
# Line 1197 | Line 1667 | public class JSR166TestCase extends Test
1667                  q.remove();
1668                  shouldThrow();
1669              } catch (NoSuchElementException success) {}
1670 <        } catch (InterruptedException ie) {
1201 <            threadUnexpectedException(ie);
1202 <        }
1670 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1671      }
1672  
1673      void assertSerialEquals(Object x, Object y) {
# Line 1218 | Line 1686 | public class JSR166TestCase extends Test
1686              oos.flush();
1687              oos.close();
1688              return bos.toByteArray();
1689 <        } catch (Throwable t) {
1690 <            threadUnexpectedException(t);
1689 >        } catch (Throwable fail) {
1690 >            threadUnexpectedException(fail);
1691              return new byte[0];
1692          }
1693      }
# Line 1232 | Line 1700 | public class JSR166TestCase extends Test
1700              T clone = (T) ois.readObject();
1701              assertSame(o.getClass(), clone.getClass());
1702              return clone;
1703 <        } catch (Throwable t) {
1704 <            threadUnexpectedException(t);
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