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.107 by jsr166, Sun Apr 21 06:19:58 2013 UTC vs.
Revision 1.179 by jsr166, Fri Oct 23 21:59:58 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.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;
28 + 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.*;
41 < import java.util.concurrent.atomic.AtomicBoolean;
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 static java.util.concurrent.TimeUnit.MILLISECONDS;
58 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
59 < import java.security.CodeSource;
60 < import java.security.Permission;
61 < import java.security.PermissionCollection;
62 < import java.security.Permissions;
63 < import java.security.Policy;
64 < import java.security.ProtectionDomain;
35 < import java.security.SecurityPermission;
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 44 | 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 66 | 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>
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 115 | 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 134 | Line 170 | public class JSR166TestCase extends Test
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 +            // A single test case run should never take more than 1 second.
201 +            // But let's cap it at the high end too ...
202 +            final int timeoutMinutes =
203 +                Math.min(15, Math.max(runsPerTest / 60, 1));
204 +            for (TestCase lastTestCase = currentTestCase;;) {
205 +                try { MINUTES.sleep(timeoutMinutes); }
206 +                catch (InterruptedException unexpected) { break; }
207 +                if (lastTestCase == currentTestCase) {
208 +                    System.err.printf(
209 +                        "Looks like we're stuck running test: %s%n",
210 +                        lastTestCase);
211 + //                     System.err.printf(
212 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
213 + //                         lastTestCase, currentRun, runsPerTest);
214 + //                     System.err.println("availableProcessors=" +
215 + //                         Runtime.getRuntime().availableProcessors());
216 + //                     System.err.printf("cpu model = %s%n", cpuModel());
217 +                    dumpTestThreads();
218 +                    // one stack dump is probably enough; more would be spam
219 +                    break;
220 +                }
221 +                lastTestCase = currentTestCase;
222 +            }}};
223 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
224 +        thread.setDaemon(true);
225 +        thread.start();
226 +    }
227 +
228 + //     public static String cpuModel() {
229 + //         try {
230 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
231 + //                 .matcher(new String(
232 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
233 + //             matcher.find();
234 + //             return matcher.group(1);
235 + //         } catch (Exception ex) { return null; }
236 + //     }
237 +
238 +    public void runBare() throws Throwable {
239 +        currentTestCase = this;
240 +        if (methodFilter == null
241 +            || methodFilter.matcher(toString()).find())
242 +            super.runBare();
243 +    }
244 +
245      protected void runTest() throws Throwable {
246          for (int i = 0; i < runsPerTest; i++) {
247 +            // currentRun = i;
248              if (profileTests)
249                  runTestProfiled();
250              else
# Line 144 | Line 253 | public class JSR166TestCase extends Test
253      }
254  
255      protected void runTestProfiled() throws Throwable {
256 <        long t0 = System.nanoTime();
257 <        try {
256 >        for (int i = 0; i < 2; i++) {
257 >            long startTime = System.nanoTime();
258              super.runTest();
259 <        } finally {
260 <            long elapsedMillis =
261 <                (System.nanoTime() - t0) / (1000L * 1000L);
262 <            if (elapsedMillis >= profileThreshold)
259 >            long elapsedMillis = millisElapsedSince(startTime);
260 >            if (elapsedMillis < profileThreshold)
261 >                break;
262 >            // Never report first run of any test; treat it as a
263 >            // warmup run, notably to trigger all needed classloading,
264 >            if (i > 0)
265                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
266          }
267      }
268  
269      /**
270       * Runs all JSR166 unit tests using junit.textui.TestRunner.
160     * Optional command line arg provides the number of iterations to
161     * repeat running the tests.
271       */
272      public static void main(String[] args) {
273 +        main(suite(), args);
274 +    }
275 +
276 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
277 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
278 +        long runTime;
279 +        public void startTest(Test test) {}
280 +        protected void printHeader(long runTime) {
281 +            this.runTime = runTime; // defer printing for later
282 +        }
283 +        protected void printFooter(TestResult result) {
284 +            if (result.wasSuccessful()) {
285 +                getWriter().println("OK (" + result.runCount() + " tests)"
286 +                    + "  Time: " + elapsedTimeAsString(runTime));
287 +            } else {
288 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
289 +                super.printFooter(result);
290 +            }
291 +        }
292 +    }
293 +
294 +    /**
295 +     * Returns a TestRunner that doesn't bother with unnecessary
296 +     * fluff, like printing a "." for each test case.
297 +     */
298 +    static junit.textui.TestRunner newPithyTestRunner() {
299 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
300 +        runner.setPrinter(new PithyResultPrinter(System.out));
301 +        return runner;
302 +    }
303 +
304 +    /**
305 +     * Runs all unit tests in the given test suite.
306 +     * Actual behavior influenced by jsr166.* system properties.
307 +     */
308 +    static void main(Test suite, String[] args) {
309          if (useSecurityManager) {
310              System.err.println("Setting a permissive security manager");
311              Policy.setPolicy(permissivePolicy());
312              System.setSecurityManager(new SecurityManager());
313          }
314 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
315 <
316 <        Test s = suite();
317 <        for (int i = 0; i < iters; ++i) {
173 <            junit.textui.TestRunner.run(s);
314 >        for (int i = 0; i < suiteRuns; i++) {
315 >            TestResult result = newPithyTestRunner().doRun(suite);
316 >            if (!result.wasSuccessful())
317 >                System.exit(1);
318              System.gc();
319              System.runFinalization();
320          }
177        System.exit(0);
321      }
322  
323      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 205 | Line 348 | public class JSR166TestCase extends Test
348      }
349  
350      public static final double JAVA_CLASS_VERSION;
351 +    public static final String JAVA_SPECIFICATION_VERSION;
352      static {
353          try {
354              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
355                  new java.security.PrivilegedAction<Double>() {
356                  public Double run() {
357                      return Double.valueOf(System.getProperty("java.class.version"));}});
358 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
359 +                new java.security.PrivilegedAction<String>() {
360 +                public String run() {
361 +                    return System.getProperty("java.specification.version");}});
362          } catch (Throwable t) {
363              throw new Error(t);
364          }
# Line 219 | Line 367 | public class JSR166TestCase extends Test
367      public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
368      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
369      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
370 +    public static boolean atLeastJava9() {
371 +        return JAVA_CLASS_VERSION >= 53.0
372 +            // As of 2015-09, java9 still uses 52.0 class file version
373 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
374 +    }
375 +    public static boolean atLeastJava10() {
376 +        return JAVA_CLASS_VERSION >= 54.0
377 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
378 +    }
379  
380      /**
381       * Collects all JSR166 unit tests as one suite.
# Line 294 | Line 451 | public class JSR166TestCase extends Test
451          // Java8+ test classes
452          if (atLeastJava8()) {
453              String[] java8TestClassNames = {
454 +                "Atomic8Test",
455                  "CompletableFutureTest",
456                  "ConcurrentHashMap8Test",
457                  "CountedCompleterTest",
458                  "DoubleAccumulatorTest",
459                  "DoubleAdderTest",
460                  "ForkJoinPool8Test",
461 +                "ForkJoinTask8Test",
462                  "LongAccumulatorTest",
463                  "LongAdderTest",
464 +                "SplittableRandomTest",
465                  "StampedLockTest",
466 +                "SubmissionPublisherTest",
467 +                "ThreadLocalRandom8Test",
468              };
469              addNamedTestClasses(suite, java8TestClassNames);
470          }
471  
472 +        // Java9+ test classes
473 +        if (atLeastJava9()) {
474 +            String[] java9TestClassNames = {
475 +                // Currently empty, but expecting varhandle tests
476 +            };
477 +            addNamedTestClasses(suite, java9TestClassNames);
478 +        }
479 +
480          return suite;
481      }
482  
483 +    /** Returns list of junit-style test method names in given class. */
484 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
485 +        Method[] methods = testClass.getDeclaredMethods();
486 +        ArrayList<String> names = new ArrayList<String>(methods.length);
487 +        for (Method method : methods) {
488 +            if (method.getName().startsWith("test")
489 +                && Modifier.isPublic(method.getModifiers())
490 +                // method.getParameterCount() requires jdk8+
491 +                && method.getParameterTypes().length == 0) {
492 +                names.add(method.getName());
493 +            }
494 +        }
495 +        return names;
496 +    }
497 +
498 +    /**
499 +     * Returns junit-style testSuite for the given test class, but
500 +     * parameterized by passing extra data to each test.
501 +     */
502 +    public static <ExtraData> Test parameterizedTestSuite
503 +        (Class<? extends JSR166TestCase> testClass,
504 +         Class<ExtraData> dataClass,
505 +         ExtraData data) {
506 +        try {
507 +            TestSuite suite = new TestSuite();
508 +            Constructor c =
509 +                testClass.getDeclaredConstructor(dataClass, String.class);
510 +            for (String methodName : testMethodNames(testClass))
511 +                suite.addTest((Test) c.newInstance(data, methodName));
512 +            return suite;
513 +        } catch (Exception e) {
514 +            throw new Error(e);
515 +        }
516 +    }
517 +
518 +    /**
519 +     * Returns junit-style testSuite for the jdk8 extension of the
520 +     * given test class, but parameterized by passing extra data to
521 +     * each test.  Uses reflection to allow compilation in jdk7.
522 +     */
523 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
524 +        (Class<? extends JSR166TestCase> testClass,
525 +         Class<ExtraData> dataClass,
526 +         ExtraData data) {
527 +        if (atLeastJava8()) {
528 +            String name = testClass.getName();
529 +            String name8 = name.replaceAll("Test$", "8Test");
530 +            if (name.equals(name8)) throw new Error(name);
531 +            try {
532 +                return (Test)
533 +                    Class.forName(name8)
534 +                    .getMethod("testSuite", new Class[] { dataClass })
535 +                    .invoke(null, data);
536 +            } catch (Exception e) {
537 +                throw new Error(e);
538 +            }
539 +        } else {
540 +            return new TestSuite();
541 +        }
542 +    }
543 +
544 +    // Delays for timing-dependent tests, in milliseconds.
545  
546      public static long SHORT_DELAY_MS;
547      public static long SMALL_DELAY_MS;
548      public static long MEDIUM_DELAY_MS;
549      public static long LONG_DELAY_MS;
550  
319
551      /**
552       * Returns the shortest timed delay. This could
553       * be reimplemented to use for example a Property.
# Line 344 | Line 575 | public class JSR166TestCase extends Test
575      }
576  
577      /**
578 <     * Returns a new Date instance representing a time delayMillis
579 <     * milliseconds in the future.
578 >     * Returns a new Date instance representing a time at least
579 >     * delayMillis milliseconds in the future.
580       */
581      Date delayedDate(long delayMillis) {
582 <        return new Date(System.currentTimeMillis() + delayMillis);
582 >        // Add 1 because currentTimeMillis is known to round into the past.
583 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
584      }
585  
586      /**
# Line 364 | Line 596 | public class JSR166TestCase extends Test
596       * the same test have no effect.
597       */
598      public void threadRecordFailure(Throwable t) {
599 +        System.err.println(t);
600 +        dumpTestThreads();
601          threadFailure.compareAndSet(null, t);
602      }
603  
# Line 371 | Line 605 | public class JSR166TestCase extends Test
605          setDelays();
606      }
607  
608 +    void tearDownFail(String format, Object... args) {
609 +        String msg = toString() + ": " + String.format(format, args);
610 +        System.err.println(msg);
611 +        dumpTestThreads();
612 +        throw new AssertionFailedError(msg);
613 +    }
614 +
615      /**
616       * Extra checks that get done for all test cases.
617       *
# Line 398 | Line 639 | public class JSR166TestCase extends Test
639          }
640  
641          if (Thread.interrupted())
642 <            throw new AssertionFailedError("interrupt status set in main thread");
642 >            tearDownFail("interrupt status set in main thread");
643  
644          checkForkJoinPoolThreadLeaks();
645      }
646  
647      /**
648 <     * Find missing try { ... } finally { joinPool(e); }
648 >     * Finds missing PoolCleaners
649       */
650      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
651 <        Thread[] survivors = new Thread[5];
651 >        Thread[] survivors = new Thread[7];
652          int count = Thread.enumerate(survivors);
653          for (int i = 0; i < count; i++) {
654              Thread thread = survivors[i];
# Line 415 | Line 656 | public class JSR166TestCase extends Test
656              if (name.startsWith("ForkJoinPool-")) {
657                  // give thread some time to terminate
658                  thread.join(LONG_DELAY_MS);
659 <                if (!thread.isAlive()) continue;
660 <                thread.stop();
661 <                throw new AssertionFailedError
421 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
422 <                                   toString(), name));
659 >                if (thread.isAlive())
660 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
661 >                                 thread);
662              }
663          }
664 +
665 +        if (!ForkJoinPool.commonPool()
666 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
667 +            tearDownFail("ForkJoin common pool thread stuck");
668      }
669  
670      /**
# Line 434 | Line 677 | public class JSR166TestCase extends Test
677              fail(reason);
678          } catch (AssertionFailedError t) {
679              threadRecordFailure(t);
680 <            fail(reason);
680 >            throw t;
681          }
682      }
683  
# Line 502 | Line 745 | public class JSR166TestCase extends Test
745      public void threadAssertEquals(Object x, Object y) {
746          try {
747              assertEquals(x, y);
748 <        } catch (AssertionFailedError t) {
749 <            threadRecordFailure(t);
750 <            throw t;
751 <        } catch (Throwable t) {
752 <            threadUnexpectedException(t);
748 >        } catch (AssertionFailedError fail) {
749 >            threadRecordFailure(fail);
750 >            throw fail;
751 >        } catch (Throwable fail) {
752 >            threadUnexpectedException(fail);
753          }
754      }
755  
# Line 518 | Line 761 | public class JSR166TestCase extends Test
761      public void threadAssertSame(Object x, Object y) {
762          try {
763              assertSame(x, y);
764 <        } catch (AssertionFailedError t) {
765 <            threadRecordFailure(t);
766 <            throw t;
764 >        } catch (AssertionFailedError fail) {
765 >            threadRecordFailure(fail);
766 >            throw fail;
767          }
768      }
769  
# Line 561 | Line 804 | public class JSR166TestCase extends Test
804      /**
805       * Delays, via Thread.sleep, for the given millisecond delay, but
806       * if the sleep is shorter than specified, may re-sleep or yield
807 <     * until time elapses.
807 >     * until time elapses.  Ensures that the given time, as measured
808 >     * by System.nanoTime(), has elapsed.
809       */
810      static void delay(long millis) throws InterruptedException {
811 <        long startTime = System.nanoTime();
812 <        long ns = millis * 1000 * 1000;
813 <        for (;;) {
811 >        long nanos = millis * (1000 * 1000);
812 >        final long wakeupTime = System.nanoTime() + nanos;
813 >        do {
814              if (millis > 0L)
815                  Thread.sleep(millis);
816              else // too short to sleep
817                  Thread.yield();
818 <            long d = ns - (System.nanoTime() - startTime);
819 <            if (d > 0L)
820 <                millis = d / (1000 * 1000);
821 <            else
822 <                break;
818 >            nanos = wakeupTime - System.nanoTime();
819 >            millis = nanos / (1000 * 1000);
820 >        } while (nanos >= 0L);
821 >    }
822 >
823 >    /**
824 >     * Allows use of try-with-resources with per-test thread pools.
825 >     */
826 >    class PoolCleaner implements AutoCloseable {
827 >        private final ExecutorService pool;
828 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
829 >        public void close() { joinPool(pool); }
830 >    }
831 >
832 >    /**
833 >     * An extension of PoolCleaner that has an action to release the pool.
834 >     */
835 >    class PoolCleanerWithReleaser extends PoolCleaner {
836 >        private final Runnable releaser;
837 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
838 >            super(pool);
839 >            this.releaser = releaser;
840 >        }
841 >        public void close() {
842 >            try {
843 >                releaser.run();
844 >            } finally {
845 >                super.close();
846 >            }
847          }
848      }
849  
850 +    PoolCleaner cleaner(ExecutorService pool) {
851 +        return new PoolCleaner(pool);
852 +    }
853 +
854 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
855 +        return new PoolCleanerWithReleaser(pool, releaser);
856 +    }
857 +
858 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
859 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
860 +    }
861 +
862 +    Runnable releaser(final CountDownLatch latch) {
863 +        return new Runnable() { public void run() {
864 +            do { latch.countDown(); }
865 +            while (latch.getCount() > 0);
866 +        }};
867 +    }
868 +
869      /**
870       * Waits out termination of a thread pool or fails doing so.
871       */
872 <    void joinPool(ExecutorService exec) {
872 >    void joinPool(ExecutorService pool) {
873          try {
874 <            exec.shutdown();
875 <            assertTrue("ExecutorService did not terminate in a timely manner",
876 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
874 >            pool.shutdown();
875 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
876 >                try {
877 >                    threadFail("ExecutorService " + pool +
878 >                               " did not terminate in a timely manner");
879 >                } finally {
880 >                    // last resort, for the benefit of subsequent tests
881 >                    pool.shutdownNow();
882 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
883 >                }
884 >            }
885          } catch (SecurityException ok) {
886              // Allowed in case test doesn't have privs
887 <        } catch (InterruptedException ie) {
888 <            fail("Unexpected InterruptedException");
887 >        } catch (InterruptedException fail) {
888 >            threadFail("Unexpected InterruptedException");
889 >        }
890 >    }
891 >
892 >    /** Like Runnable, but with the freedom to throw anything */
893 >    interface Action { public void run() throws Throwable; }
894 >
895 >    /**
896 >     * Runs all the given actions in parallel, failing if any fail.
897 >     * Useful for running multiple variants of tests that are
898 >     * necessarily individually slow because they must block.
899 >     */
900 >    void testInParallel(Action ... actions) {
901 >        ExecutorService pool = Executors.newCachedThreadPool();
902 >        try (PoolCleaner cleaner = cleaner(pool)) {
903 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
904 >            for (final Action action : actions)
905 >                futures.add(pool.submit(new CheckedRunnable() {
906 >                    public void realRun() throws Throwable { action.run();}}));
907 >            for (Future<?> future : futures)
908 >                try {
909 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
910 >                } catch (ExecutionException ex) {
911 >                    threadUnexpectedException(ex.getCause());
912 >                } catch (Exception ex) {
913 >                    threadUnexpectedException(ex);
914 >                }
915          }
916      }
917  
918      /**
919 <     * A debugging tool to print all stack traces, as jstack does.
919 >     * A debugging tool to print stack traces of most threads, as jstack does.
920 >     * Uninteresting threads are filtered out.
921       */
922 <    static void printAllStackTraces() {
923 <        for (ThreadInfo info :
924 <                 ManagementFactory.getThreadMXBean()
925 <                 .dumpAllThreads(true, true))
922 >    static void dumpTestThreads() {
923 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
924 >        System.err.println("------ stacktrace dump start ------");
925 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
926 >            String name = info.getThreadName();
927 >            if ("Signal Dispatcher".equals(name))
928 >                continue;
929 >            if ("Reference Handler".equals(name)
930 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
931 >                continue;
932 >            if ("Finalizer".equals(name)
933 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
934 >                continue;
935 >            if ("checkForWedgedTest".equals(name))
936 >                continue;
937              System.err.print(info);
938 +        }
939 +        System.err.println("------ stacktrace dump end ------");
940      }
941  
942      /**
# Line 620 | Line 955 | public class JSR166TestCase extends Test
955              // No need to optimize the failing case via Thread.join.
956              delay(millis);
957              assertTrue(thread.isAlive());
958 <        } catch (InterruptedException ie) {
959 <            fail("Unexpected InterruptedException");
958 >        } catch (InterruptedException fail) {
959 >            threadFail("Unexpected InterruptedException");
960          }
961      }
962  
# Line 642 | Line 977 | public class JSR166TestCase extends Test
977              delay(millis);
978              for (Thread thread : threads)
979                  assertTrue(thread.isAlive());
980 <        } catch (InterruptedException ie) {
981 <            fail("Unexpected InterruptedException");
980 >        } catch (InterruptedException fail) {
981 >            threadFail("Unexpected InterruptedException");
982          }
983      }
984  
# Line 664 | Line 999 | public class JSR166TestCase extends Test
999              future.get(timeoutMillis, MILLISECONDS);
1000              shouldThrow();
1001          } catch (TimeoutException success) {
1002 <        } catch (Exception e) {
1003 <            threadUnexpectedException(e);
1002 >        } catch (Exception fail) {
1003 >            threadUnexpectedException(fail);
1004          } finally { future.cancel(true); }
1005          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1006      }
# Line 709 | Line 1044 | public class JSR166TestCase extends Test
1044      public static final Integer m6  = new Integer(-6);
1045      public static final Integer m10 = new Integer(-10);
1046  
712
1047      /**
1048       * Runs Runnable r with a security policy that permits precisely
1049       * the specified permissions.  If there is no current security
# Line 822 | Line 1156 | public class JSR166TestCase extends Test
1156      void sleep(long millis) {
1157          try {
1158              delay(millis);
1159 <        } catch (InterruptedException ie) {
1159 >        } catch (InterruptedException fail) {
1160              AssertionFailedError afe =
1161                  new AssertionFailedError("Unexpected InterruptedException");
1162 <            afe.initCause(ie);
1162 >            afe.initCause(fail);
1163              throw afe;
1164          }
1165      }
# Line 863 | Line 1197 | public class JSR166TestCase extends Test
1197      /**
1198       * Returns the number of milliseconds since time given by
1199       * startNanoTime, which must have been previously returned from a
1200 <     * call to {@link System.nanoTime()}.
1200 >     * call to {@link System#nanoTime()}.
1201       */
1202 <    long millisElapsedSince(long startNanoTime) {
1202 >    static long millisElapsedSince(long startNanoTime) {
1203          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1204      }
1205  
1206 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1207 + //         long startTime = System.nanoTime();
1208 + //         try {
1209 + //             r.run();
1210 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1211 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1212 + //             throw new AssertionFailedError("did not return promptly");
1213 + //     }
1214 +
1215 + //     void assertTerminatesPromptly(Runnable r) {
1216 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1217 + //     }
1218 +
1219 +    /**
1220 +     * Checks that timed f.get() returns the expected value, and does not
1221 +     * wait for the timeout to elapse before returning.
1222 +     */
1223 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1224 +        long startTime = System.nanoTime();
1225 +        try {
1226 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1227 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1228 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1229 +            throw new AssertionFailedError("timed get did not return promptly");
1230 +    }
1231 +
1232 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1233 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1234 +    }
1235 +
1236      /**
1237       * Returns a new started daemon Thread running the given runnable.
1238       */
# Line 887 | Line 1251 | public class JSR166TestCase extends Test
1251      void awaitTermination(Thread t, long timeoutMillis) {
1252          try {
1253              t.join(timeoutMillis);
1254 <        } catch (InterruptedException ie) {
1255 <            threadUnexpectedException(ie);
1254 >        } catch (InterruptedException fail) {
1255 >            threadUnexpectedException(fail);
1256          } finally {
1257              if (t.getState() != Thread.State.TERMINATED) {
1258                  t.interrupt();
1259 <                fail("Test timed out");
1259 >                threadFail("timed out waiting for thread to terminate");
1260              }
1261          }
1262      }
# Line 914 | Line 1278 | public class JSR166TestCase extends Test
1278          public final void run() {
1279              try {
1280                  realRun();
1281 <            } catch (Throwable t) {
1282 <                threadUnexpectedException(t);
1281 >            } catch (Throwable fail) {
1282 >                threadUnexpectedException(fail);
1283              }
1284          }
1285      }
# Line 969 | Line 1333 | public class JSR166TestCase extends Test
1333                  threadShouldThrow("InterruptedException");
1334              } catch (InterruptedException success) {
1335                  threadAssertFalse(Thread.interrupted());
1336 <            } catch (Throwable t) {
1337 <                threadUnexpectedException(t);
1336 >            } catch (Throwable fail) {
1337 >                threadUnexpectedException(fail);
1338              }
1339          }
1340      }
# Line 981 | Line 1345 | public class JSR166TestCase extends Test
1345          public final T call() {
1346              try {
1347                  return realCall();
1348 <            } catch (Throwable t) {
1349 <                threadUnexpectedException(t);
1348 >            } catch (Throwable fail) {
1349 >                threadUnexpectedException(fail);
1350                  return null;
1351              }
1352          }
# Line 999 | Line 1363 | public class JSR166TestCase extends Test
1363                  return result;
1364              } catch (InterruptedException success) {
1365                  threadAssertFalse(Thread.interrupted());
1366 <            } catch (Throwable t) {
1367 <                threadUnexpectedException(t);
1366 >            } catch (Throwable fail) {
1367 >                threadUnexpectedException(fail);
1368              }
1369              return null;
1370          }
# Line 1017 | Line 1381 | public class JSR166TestCase extends Test
1381      public static final String TEST_STRING = "a test string";
1382  
1383      public static class StringTask implements Callable<String> {
1384 <        public String call() { return TEST_STRING; }
1384 >        final String value;
1385 >        public StringTask() { this(TEST_STRING); }
1386 >        public StringTask(String value) { this.value = value; }
1387 >        public String call() { return value; }
1388      }
1389  
1390      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1030 | Line 1397 | public class JSR166TestCase extends Test
1397              }};
1398      }
1399  
1400 <    public Runnable awaiter(final CountDownLatch latch) {
1400 >    public Runnable countDowner(final CountDownLatch latch) {
1401          return new CheckedRunnable() {
1402              public void realRun() throws InterruptedException {
1403 <                await(latch);
1403 >                latch.countDown();
1404              }};
1405      }
1406  
1407 +    class LatchAwaiter extends CheckedRunnable {
1408 +        static final int NEW = 0;
1409 +        static final int RUNNING = 1;
1410 +        static final int DONE = 2;
1411 +        final CountDownLatch latch;
1412 +        int state = NEW;
1413 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1414 +        public void realRun() throws InterruptedException {
1415 +            state = 1;
1416 +            await(latch);
1417 +            state = 2;
1418 +        }
1419 +    }
1420 +
1421 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1422 +        return new LatchAwaiter(latch);
1423 +    }
1424 +
1425      public void await(CountDownLatch latch) {
1426          try {
1427 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1428 <        } catch (Throwable t) {
1429 <            threadUnexpectedException(t);
1427 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1428 >                fail("timed out waiting for CountDownLatch for "
1429 >                     + (LONG_DELAY_MS/1000) + " sec");
1430 >        } catch (Throwable fail) {
1431 >            threadUnexpectedException(fail);
1432          }
1433      }
1434  
1435      public void await(Semaphore semaphore) {
1436          try {
1437 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1438 <        } catch (Throwable t) {
1439 <            threadUnexpectedException(t);
1437 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1438 >                fail("timed out waiting for Semaphore for "
1439 >                     + (LONG_DELAY_MS/1000) + " sec");
1440 >        } catch (Throwable fail) {
1441 >            threadUnexpectedException(fail);
1442          }
1443      }
1444  
# Line 1240 | Line 1629 | public class JSR166TestCase extends Test
1629      public abstract class CheckedRecursiveAction extends RecursiveAction {
1630          protected abstract void realCompute() throws Throwable;
1631  
1632 <        public final void compute() {
1632 >        @Override protected final void compute() {
1633              try {
1634                  realCompute();
1635 <            } catch (Throwable t) {
1636 <                threadUnexpectedException(t);
1635 >            } catch (Throwable fail) {
1636 >                threadUnexpectedException(fail);
1637              }
1638          }
1639      }
# Line 1255 | Line 1644 | public class JSR166TestCase extends Test
1644      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1645          protected abstract T realCompute() throws Throwable;
1646  
1647 <        public final T compute() {
1647 >        @Override protected final T compute() {
1648              try {
1649                  return realCompute();
1650 <            } catch (Throwable t) {
1651 <                threadUnexpectedException(t);
1650 >            } catch (Throwable fail) {
1651 >                threadUnexpectedException(fail);
1652                  return null;
1653              }
1654          }
# Line 1283 | Line 1672 | public class JSR166TestCase extends Test
1672          public int await() {
1673              try {
1674                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1675 <            } catch (TimeoutException e) {
1675 >            } catch (TimeoutException timedOut) {
1676                  throw new AssertionFailedError("timed out");
1677 <            } catch (Exception e) {
1677 >            } catch (Exception fail) {
1678                  AssertionFailedError afe =
1679 <                    new AssertionFailedError("Unexpected exception: " + e);
1680 <                afe.initCause(e);
1679 >                    new AssertionFailedError("Unexpected exception: " + fail);
1680 >                afe.initCause(fail);
1681                  throw afe;
1682              }
1683          }
# Line 1316 | Line 1705 | public class JSR166TestCase extends Test
1705                  q.remove();
1706                  shouldThrow();
1707              } catch (NoSuchElementException success) {}
1708 <        } catch (InterruptedException ie) {
1320 <            threadUnexpectedException(ie);
1321 <        }
1708 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1709      }
1710  
1711      void assertSerialEquals(Object x, Object y) {
# Line 1337 | Line 1724 | public class JSR166TestCase extends Test
1724              oos.flush();
1725              oos.close();
1726              return bos.toByteArray();
1727 <        } catch (Throwable t) {
1728 <            threadUnexpectedException(t);
1727 >        } catch (Throwable fail) {
1728 >            threadUnexpectedException(fail);
1729              return new byte[0];
1730          }
1731      }
# Line 1351 | Line 1738 | public class JSR166TestCase extends Test
1738              T clone = (T) ois.readObject();
1739              assertSame(o.getClass(), clone.getClass());
1740              return clone;
1741 <        } catch (Throwable t) {
1742 <            threadUnexpectedException(t);
1741 >        } catch (Throwable fail) {
1742 >            threadUnexpectedException(fail);
1743              return null;
1744          }
1745      }
# Line 1377 | Line 1764 | public class JSR166TestCase extends Test
1764                  shouldThrow(expectedExceptionClass.getName());
1765          }
1766      }
1767 +
1768 +    public void assertIteratorExhausted(Iterator<?> it) {
1769 +        try {
1770 +            it.next();
1771 +            shouldThrow();
1772 +        } catch (NoSuchElementException success) {}
1773 +        assertFalse(it.hasNext());
1774 +    }
1775   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines