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.109 by jsr166, Sun Jul 14 16:55:01 2013 UTC vs.
Revision 1.181 by jsr166, Mon Nov 9 06:06:54 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
87 < * isolation.</li>
115 > * cover multiple methods when they cannot be tested in isolation.
116   *
117 < * <li> The documentation style for testcases is to provide as javadoc
117 > * <li>The documentation style for testcases is to provide as javadoc
118   * a simple sentence or two describing the property that the testcase
119   * method purports to test. The javadocs do not say anything about how
120 < * the property is tested. To find out, read the code.</li>
120 > * the property is tested. To find out, read the code.
121   *
122 < * <li> These tests are "conformance tests", and do not attempt to
122 > * <li>These tests are "conformance tests", and do not attempt to
123   * test throughput, latency, scalability or other performance factors
124   * (see the separate "jtreg" tests for a set intended to check these
125   * for the most central aspects of functionality.) So, most tests use
126   * the smallest sensible numbers of threads, collection sizes, etc
127 < * needed to check basic conformance.</li>
127 > * needed to check basic conformance.
128   *
129   * <li>The test classes currently do not declare inclusion in
130   * any particular package to simplify things for people integrating
131 < * them in TCK test suites.</li>
131 > * them in TCK test suites.
132   *
133 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
134 < * runs all JSR166 unit tests.</li>
133 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
134 > * runs all JSR166 unit tests.
135   *
136   * </ul>
137   */
# Line 115 | Line 143 | public class JSR166TestCase extends Test
143          Boolean.getBoolean("jsr166.expensiveTests");
144  
145      /**
146 +     * If true, also run tests that are not part of the official tck
147 +     * because they test unspecified implementation details.
148 +     */
149 +    protected static final boolean testImplementationDetails =
150 +        Boolean.getBoolean("jsr166.testImplementationDetails");
151 +
152 +    /**
153       * If true, report on stdout all "slow" tests, that is, ones that
154       * take more than profileThreshold milliseconds to execute.
155       */
# Line 134 | Line 169 | public class JSR166TestCase extends Test
169      private static final int runsPerTest =
170          Integer.getInteger("jsr166.runsPerTest", 1);
171  
172 +    /**
173 +     * The number of repetitions of the test suite (for finding leaks?).
174 +     */
175 +    private static final int suiteRuns =
176 +        Integer.getInteger("jsr166.suiteRuns", 1);
177 +
178 +    /**
179 +     * The scaling factor to apply to standard delays used in tests.
180 +     */
181 +    private static final int delayFactor =
182 +        Integer.getInteger("jsr166.delay.factor", 1);
183 +
184 +    public JSR166TestCase() { super(); }
185 +    public JSR166TestCase(String name) { super(name); }
186 +
187 +    /**
188 +     * A filter for tests to run, matching strings of the form
189 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
190 +     * Usefully combined with jsr166.runsPerTest.
191 +     */
192 +    private static final Pattern methodFilter = methodFilter();
193 +
194 +    private static Pattern methodFilter() {
195 +        String regex = System.getProperty("jsr166.methodFilter");
196 +        return (regex == null) ? null : Pattern.compile(regex);
197 +    }
198 +
199 +    // Instrumentation to debug very rare, but very annoying hung test runs.
200 +    static volatile TestCase currentTestCase;
201 +    // static volatile int currentRun = 0;
202 +    static {
203 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
204 +            // Avoid spurious reports with enormous runsPerTest.
205 +            // A single test case run should never take more than 1 second.
206 +            // But let's cap it at the high end too ...
207 +            final int timeoutMinutes =
208 +                Math.min(15, Math.max(runsPerTest / 60, 1));
209 +            for (TestCase lastTestCase = currentTestCase;;) {
210 +                try { MINUTES.sleep(timeoutMinutes); }
211 +                catch (InterruptedException unexpected) { break; }
212 +                if (lastTestCase == currentTestCase) {
213 +                    System.err.printf(
214 +                        "Looks like we're stuck running test: %s%n",
215 +                        lastTestCase);
216 + //                     System.err.printf(
217 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
218 + //                         lastTestCase, currentRun, runsPerTest);
219 + //                     System.err.println("availableProcessors=" +
220 + //                         Runtime.getRuntime().availableProcessors());
221 + //                     System.err.printf("cpu model = %s%n", cpuModel());
222 +                    dumpTestThreads();
223 +                    // one stack dump is probably enough; more would be spam
224 +                    break;
225 +                }
226 +                lastTestCase = currentTestCase;
227 +            }}};
228 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
229 +        thread.setDaemon(true);
230 +        thread.start();
231 +    }
232 +
233 + //     public static String cpuModel() {
234 + //         try {
235 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
236 + //                 .matcher(new String(
237 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
238 + //             matcher.find();
239 + //             return matcher.group(1);
240 + //         } catch (Exception ex) { return null; }
241 + //     }
242 +
243 +    public void runBare() throws Throwable {
244 +        currentTestCase = this;
245 +        if (methodFilter == null
246 +            || methodFilter.matcher(toString()).find())
247 +            super.runBare();
248 +    }
249 +
250      protected void runTest() throws Throwable {
251          for (int i = 0; i < runsPerTest; i++) {
252 +            // currentRun = i;
253              if (profileTests)
254                  runTestProfiled();
255              else
# Line 144 | Line 258 | public class JSR166TestCase extends Test
258      }
259  
260      protected void runTestProfiled() throws Throwable {
261 <        long t0 = System.nanoTime();
262 <        try {
261 >        for (int i = 0; i < 2; i++) {
262 >            long startTime = System.nanoTime();
263              super.runTest();
264 <        } finally {
265 <            long elapsedMillis =
266 <                (System.nanoTime() - t0) / (1000L * 1000L);
267 <            if (elapsedMillis >= profileThreshold)
264 >            long elapsedMillis = millisElapsedSince(startTime);
265 >            if (elapsedMillis < profileThreshold)
266 >                break;
267 >            // Never report first run of any test; treat it as a
268 >            // warmup run, notably to trigger all needed classloading,
269 >            if (i > 0)
270                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
271          }
272      }
273  
274      /**
275       * Runs all JSR166 unit tests using junit.textui.TestRunner.
160     * Optional command line arg provides the number of iterations to
161     * repeat running the tests.
276       */
277      public static void main(String[] args) {
278 +        main(suite(), args);
279 +    }
280 +
281 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
282 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
283 +        long runTime;
284 +        public void startTest(Test test) {}
285 +        protected void printHeader(long runTime) {
286 +            this.runTime = runTime; // defer printing for later
287 +        }
288 +        protected void printFooter(TestResult result) {
289 +            if (result.wasSuccessful()) {
290 +                getWriter().println("OK (" + result.runCount() + " tests)"
291 +                    + "  Time: " + elapsedTimeAsString(runTime));
292 +            } else {
293 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
294 +                super.printFooter(result);
295 +            }
296 +        }
297 +    }
298 +
299 +    /**
300 +     * Returns a TestRunner that doesn't bother with unnecessary
301 +     * fluff, like printing a "." for each test case.
302 +     */
303 +    static junit.textui.TestRunner newPithyTestRunner() {
304 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
305 +        runner.setPrinter(new PithyResultPrinter(System.out));
306 +        return runner;
307 +    }
308 +
309 +    /**
310 +     * Runs all unit tests in the given test suite.
311 +     * Actual behavior influenced by jsr166.* system properties.
312 +     */
313 +    static void main(Test suite, String[] args) {
314          if (useSecurityManager) {
315              System.err.println("Setting a permissive security manager");
316              Policy.setPolicy(permissivePolicy());
317              System.setSecurityManager(new SecurityManager());
318          }
319 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
320 <
321 <        Test s = suite();
322 <        for (int i = 0; i < iters; ++i) {
173 <            junit.textui.TestRunner.run(s);
319 >        for (int i = 0; i < suiteRuns; i++) {
320 >            TestResult result = newPithyTestRunner().doRun(suite);
321 >            if (!result.wasSuccessful())
322 >                System.exit(1);
323              System.gc();
324              System.runFinalization();
325          }
177        System.exit(0);
326      }
327  
328      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 205 | Line 353 | public class JSR166TestCase extends Test
353      }
354  
355      public static final double JAVA_CLASS_VERSION;
356 +    public static final String JAVA_SPECIFICATION_VERSION;
357      static {
358          try {
359              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
360                  new java.security.PrivilegedAction<Double>() {
361                  public Double run() {
362                      return Double.valueOf(System.getProperty("java.class.version"));}});
363 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
364 +                new java.security.PrivilegedAction<String>() {
365 +                public String run() {
366 +                    return System.getProperty("java.specification.version");}});
367          } catch (Throwable t) {
368              throw new Error(t);
369          }
# Line 219 | Line 372 | public class JSR166TestCase extends Test
372      public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
373      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
374      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
375 +    public static boolean atLeastJava9() {
376 +        return JAVA_CLASS_VERSION >= 53.0
377 +            // As of 2015-09, java9 still uses 52.0 class file version
378 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
379 +    }
380 +    public static boolean atLeastJava10() {
381 +        return JAVA_CLASS_VERSION >= 54.0
382 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
383 +    }
384  
385      /**
386       * Collects all JSR166 unit tests as one suite.
# Line 232 | Line 394 | public class JSR166TestCase extends Test
394              RecursiveTaskTest.suite(),
395              LinkedTransferQueueTest.suite(),
396              PhaserTest.suite(),
235            SplittableRandomTest.suite(),
397              ThreadLocalRandomTest.suite(),
398              AbstractExecutorServiceTest.suite(),
399              AbstractQueueTest.suite(),
# Line 295 | Line 456 | public class JSR166TestCase extends Test
456          // Java8+ test classes
457          if (atLeastJava8()) {
458              String[] java8TestClassNames = {
459 +                "Atomic8Test",
460                  "CompletableFutureTest",
461                  "ConcurrentHashMap8Test",
462                  "CountedCompleterTest",
463                  "DoubleAccumulatorTest",
464                  "DoubleAdderTest",
465                  "ForkJoinPool8Test",
466 +                "ForkJoinTask8Test",
467                  "LongAccumulatorTest",
468                  "LongAdderTest",
469 +                "SplittableRandomTest",
470                  "StampedLockTest",
471 +                "SubmissionPublisherTest",
472 +                "ThreadLocalRandom8Test",
473              };
474              addNamedTestClasses(suite, java8TestClassNames);
475          }
476  
477 +        // Java9+ test classes
478 +        if (atLeastJava9()) {
479 +            String[] java9TestClassNames = {
480 +                // Currently empty, but expecting varhandle tests
481 +            };
482 +            addNamedTestClasses(suite, java9TestClassNames);
483 +        }
484 +
485          return suite;
486      }
487  
488 +    /** Returns list of junit-style test method names in given class. */
489 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
490 +        Method[] methods = testClass.getDeclaredMethods();
491 +        ArrayList<String> names = new ArrayList<String>(methods.length);
492 +        for (Method method : methods) {
493 +            if (method.getName().startsWith("test")
494 +                && Modifier.isPublic(method.getModifiers())
495 +                // method.getParameterCount() requires jdk8+
496 +                && method.getParameterTypes().length == 0) {
497 +                names.add(method.getName());
498 +            }
499 +        }
500 +        return names;
501 +    }
502 +
503 +    /**
504 +     * Returns junit-style testSuite for the given test class, but
505 +     * parameterized by passing extra data to each test.
506 +     */
507 +    public static <ExtraData> Test parameterizedTestSuite
508 +        (Class<? extends JSR166TestCase> testClass,
509 +         Class<ExtraData> dataClass,
510 +         ExtraData data) {
511 +        try {
512 +            TestSuite suite = new TestSuite();
513 +            Constructor c =
514 +                testClass.getDeclaredConstructor(dataClass, String.class);
515 +            for (String methodName : testMethodNames(testClass))
516 +                suite.addTest((Test) c.newInstance(data, methodName));
517 +            return suite;
518 +        } catch (Exception e) {
519 +            throw new Error(e);
520 +        }
521 +    }
522 +
523 +    /**
524 +     * Returns junit-style testSuite for the jdk8 extension of the
525 +     * given test class, but parameterized by passing extra data to
526 +     * each test.  Uses reflection to allow compilation in jdk7.
527 +     */
528 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
529 +        (Class<? extends JSR166TestCase> testClass,
530 +         Class<ExtraData> dataClass,
531 +         ExtraData data) {
532 +        if (atLeastJava8()) {
533 +            String name = testClass.getName();
534 +            String name8 = name.replaceAll("Test$", "8Test");
535 +            if (name.equals(name8)) throw new Error(name);
536 +            try {
537 +                return (Test)
538 +                    Class.forName(name8)
539 +                    .getMethod("testSuite", new Class[] { dataClass })
540 +                    .invoke(null, data);
541 +            } catch (Exception e) {
542 +                throw new Error(e);
543 +            }
544 +        } else {
545 +            return new TestSuite();
546 +        }
547 +    }
548 +
549      // Delays for timing-dependent tests, in milliseconds.
550  
551      public static long SHORT_DELAY_MS;
# Line 319 | Line 554 | public class JSR166TestCase extends Test
554      public static long LONG_DELAY_MS;
555  
556      /**
557 <     * Returns the shortest timed delay. This could
558 <     * be reimplemented to use for example a Property.
557 >     * Returns the shortest timed delay. This can be scaled up for
558 >     * slow machines using the jsr166.delay.factor system property.
559       */
560      protected long getShortDelay() {
561 <        return 50;
561 >        return 50 * delayFactor;
562      }
563  
564      /**
# Line 345 | Line 580 | public class JSR166TestCase extends Test
580      }
581  
582      /**
583 <     * Returns a new Date instance representing a time delayMillis
584 <     * milliseconds in the future.
583 >     * Returns a new Date instance representing a time at least
584 >     * delayMillis milliseconds in the future.
585       */
586      Date delayedDate(long delayMillis) {
587 <        return new Date(System.currentTimeMillis() + delayMillis);
587 >        // Add 1 because currentTimeMillis is known to round into the past.
588 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
589      }
590  
591      /**
# Line 365 | Line 601 | public class JSR166TestCase extends Test
601       * the same test have no effect.
602       */
603      public void threadRecordFailure(Throwable t) {
604 +        System.err.println(t);
605 +        dumpTestThreads();
606          threadFailure.compareAndSet(null, t);
607      }
608  
# Line 372 | Line 610 | public class JSR166TestCase extends Test
610          setDelays();
611      }
612  
613 +    void tearDownFail(String format, Object... args) {
614 +        String msg = toString() + ": " + String.format(format, args);
615 +        System.err.println(msg);
616 +        dumpTestThreads();
617 +        throw new AssertionFailedError(msg);
618 +    }
619 +
620      /**
621       * Extra checks that get done for all test cases.
622       *
# Line 399 | Line 644 | public class JSR166TestCase extends Test
644          }
645  
646          if (Thread.interrupted())
647 <            throw new AssertionFailedError("interrupt status set in main thread");
647 >            tearDownFail("interrupt status set in main thread");
648  
649          checkForkJoinPoolThreadLeaks();
650      }
651  
652      /**
653 <     * Find missing try { ... } finally { joinPool(e); }
653 >     * Finds missing PoolCleaners
654       */
655      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
656 <        Thread[] survivors = new Thread[5];
656 >        Thread[] survivors = new Thread[7];
657          int count = Thread.enumerate(survivors);
658          for (int i = 0; i < count; i++) {
659              Thread thread = survivors[i];
# Line 416 | Line 661 | public class JSR166TestCase extends Test
661              if (name.startsWith("ForkJoinPool-")) {
662                  // give thread some time to terminate
663                  thread.join(LONG_DELAY_MS);
664 <                if (!thread.isAlive()) continue;
665 <                thread.stop();
666 <                throw new AssertionFailedError
422 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
423 <                                   toString(), name));
664 >                if (thread.isAlive())
665 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
666 >                                 thread);
667              }
668          }
669 +
670 +        if (!ForkJoinPool.commonPool()
671 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
672 +            tearDownFail("ForkJoin common pool thread stuck");
673      }
674  
675      /**
# Line 435 | Line 682 | public class JSR166TestCase extends Test
682              fail(reason);
683          } catch (AssertionFailedError t) {
684              threadRecordFailure(t);
685 <            fail(reason);
685 >            throw t;
686          }
687      }
688  
# Line 503 | Line 750 | public class JSR166TestCase extends Test
750      public void threadAssertEquals(Object x, Object y) {
751          try {
752              assertEquals(x, y);
753 <        } catch (AssertionFailedError t) {
754 <            threadRecordFailure(t);
755 <            throw t;
756 <        } catch (Throwable t) {
757 <            threadUnexpectedException(t);
753 >        } catch (AssertionFailedError fail) {
754 >            threadRecordFailure(fail);
755 >            throw fail;
756 >        } catch (Throwable fail) {
757 >            threadUnexpectedException(fail);
758          }
759      }
760  
# Line 519 | Line 766 | public class JSR166TestCase extends Test
766      public void threadAssertSame(Object x, Object y) {
767          try {
768              assertSame(x, y);
769 <        } catch (AssertionFailedError t) {
770 <            threadRecordFailure(t);
771 <            throw t;
769 >        } catch (AssertionFailedError fail) {
770 >            threadRecordFailure(fail);
771 >            throw fail;
772          }
773      }
774  
# Line 562 | Line 809 | public class JSR166TestCase extends Test
809      /**
810       * Delays, via Thread.sleep, for the given millisecond delay, but
811       * if the sleep is shorter than specified, may re-sleep or yield
812 <     * until time elapses.
812 >     * until time elapses.  Ensures that the given time, as measured
813 >     * by System.nanoTime(), has elapsed.
814       */
815      static void delay(long millis) throws InterruptedException {
816 <        long startTime = System.nanoTime();
817 <        long ns = millis * 1000 * 1000;
818 <        for (;;) {
816 >        long nanos = millis * (1000 * 1000);
817 >        final long wakeupTime = System.nanoTime() + nanos;
818 >        do {
819              if (millis > 0L)
820                  Thread.sleep(millis);
821              else // too short to sleep
822                  Thread.yield();
823 <            long d = ns - (System.nanoTime() - startTime);
824 <            if (d > 0L)
825 <                millis = d / (1000 * 1000);
826 <            else
827 <                break;
823 >            nanos = wakeupTime - System.nanoTime();
824 >            millis = nanos / (1000 * 1000);
825 >        } while (nanos >= 0L);
826 >    }
827 >
828 >    /**
829 >     * Allows use of try-with-resources with per-test thread pools.
830 >     */
831 >    class PoolCleaner implements AutoCloseable {
832 >        private final ExecutorService pool;
833 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
834 >        public void close() { joinPool(pool); }
835 >    }
836 >
837 >    /**
838 >     * An extension of PoolCleaner that has an action to release the pool.
839 >     */
840 >    class PoolCleanerWithReleaser extends PoolCleaner {
841 >        private final Runnable releaser;
842 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
843 >            super(pool);
844 >            this.releaser = releaser;
845          }
846 +        public void close() {
847 +            try {
848 +                releaser.run();
849 +            } finally {
850 +                super.close();
851 +            }
852 +        }
853 +    }
854 +
855 +    PoolCleaner cleaner(ExecutorService pool) {
856 +        return new PoolCleaner(pool);
857 +    }
858 +
859 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
860 +        return new PoolCleanerWithReleaser(pool, releaser);
861 +    }
862 +
863 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
864 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
865 +    }
866 +
867 +    Runnable releaser(final CountDownLatch latch) {
868 +        return new Runnable() { public void run() {
869 +            do { latch.countDown(); }
870 +            while (latch.getCount() > 0);
871 +        }};
872      }
873  
874      /**
875       * Waits out termination of a thread pool or fails doing so.
876       */
877 <    void joinPool(ExecutorService exec) {
877 >    void joinPool(ExecutorService pool) {
878          try {
879 <            exec.shutdown();
880 <            assertTrue("ExecutorService did not terminate in a timely manner",
881 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
879 >            pool.shutdown();
880 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
881 >                try {
882 >                    threadFail("ExecutorService " + pool +
883 >                               " did not terminate in a timely manner");
884 >                } finally {
885 >                    // last resort, for the benefit of subsequent tests
886 >                    pool.shutdownNow();
887 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
888 >                }
889 >            }
890          } catch (SecurityException ok) {
891              // Allowed in case test doesn't have privs
892 <        } catch (InterruptedException ie) {
893 <            fail("Unexpected InterruptedException");
892 >        } catch (InterruptedException fail) {
893 >            threadFail("Unexpected InterruptedException");
894          }
895      }
896  
897 +    /** Like Runnable, but with the freedom to throw anything */
898 +    interface Action { public void run() throws Throwable; }
899 +
900      /**
901 <     * A debugging tool to print all stack traces, as jstack does.
901 >     * Runs all the given actions in parallel, failing if any fail.
902 >     * Useful for running multiple variants of tests that are
903 >     * necessarily individually slow because they must block.
904       */
905 <    static void printAllStackTraces() {
906 <        for (ThreadInfo info :
907 <                 ManagementFactory.getThreadMXBean()
908 <                 .dumpAllThreads(true, true))
905 >    void testInParallel(Action ... actions) {
906 >        ExecutorService pool = Executors.newCachedThreadPool();
907 >        try (PoolCleaner cleaner = cleaner(pool)) {
908 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
909 >            for (final Action action : actions)
910 >                futures.add(pool.submit(new CheckedRunnable() {
911 >                    public void realRun() throws Throwable { action.run();}}));
912 >            for (Future<?> future : futures)
913 >                try {
914 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
915 >                } catch (ExecutionException ex) {
916 >                    threadUnexpectedException(ex.getCause());
917 >                } catch (Exception ex) {
918 >                    threadUnexpectedException(ex);
919 >                }
920 >        }
921 >    }
922 >
923 >    /**
924 >     * A debugging tool to print stack traces of most threads, as jstack does.
925 >     * Uninteresting threads are filtered out.
926 >     */
927 >    static void dumpTestThreads() {
928 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
929 >        System.err.println("------ stacktrace dump start ------");
930 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
931 >            String name = info.getThreadName();
932 >            if ("Signal Dispatcher".equals(name))
933 >                continue;
934 >            if ("Reference Handler".equals(name)
935 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
936 >                continue;
937 >            if ("Finalizer".equals(name)
938 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
939 >                continue;
940 >            if ("checkForWedgedTest".equals(name))
941 >                continue;
942              System.err.print(info);
943 +        }
944 +        System.err.println("------ stacktrace dump end ------");
945      }
946  
947      /**
# Line 621 | Line 960 | public class JSR166TestCase extends Test
960              // No need to optimize the failing case via Thread.join.
961              delay(millis);
962              assertTrue(thread.isAlive());
963 <        } catch (InterruptedException ie) {
964 <            fail("Unexpected InterruptedException");
963 >        } catch (InterruptedException fail) {
964 >            threadFail("Unexpected InterruptedException");
965          }
966      }
967  
# Line 643 | Line 982 | public class JSR166TestCase extends Test
982              delay(millis);
983              for (Thread thread : threads)
984                  assertTrue(thread.isAlive());
985 <        } catch (InterruptedException ie) {
986 <            fail("Unexpected InterruptedException");
985 >        } catch (InterruptedException fail) {
986 >            threadFail("Unexpected InterruptedException");
987          }
988      }
989  
# Line 665 | Line 1004 | public class JSR166TestCase extends Test
1004              future.get(timeoutMillis, MILLISECONDS);
1005              shouldThrow();
1006          } catch (TimeoutException success) {
1007 <        } catch (Exception e) {
1008 <            threadUnexpectedException(e);
1007 >        } catch (Exception fail) {
1008 >            threadUnexpectedException(fail);
1009          } finally { future.cancel(true); }
1010          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1011      }
# Line 822 | Line 1161 | public class JSR166TestCase extends Test
1161      void sleep(long millis) {
1162          try {
1163              delay(millis);
1164 <        } catch (InterruptedException ie) {
1164 >        } catch (InterruptedException fail) {
1165              AssertionFailedError afe =
1166                  new AssertionFailedError("Unexpected InterruptedException");
1167 <            afe.initCause(ie);
1167 >            afe.initCause(fail);
1168              throw afe;
1169          }
1170      }
# Line 863 | Line 1202 | public class JSR166TestCase extends Test
1202      /**
1203       * Returns the number of milliseconds since time given by
1204       * startNanoTime, which must have been previously returned from a
1205 <     * call to {@link System.nanoTime()}.
1205 >     * call to {@link System#nanoTime()}.
1206       */
1207 <    long millisElapsedSince(long startNanoTime) {
1207 >    static long millisElapsedSince(long startNanoTime) {
1208          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1209      }
1210  
1211 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1212 + //         long startTime = System.nanoTime();
1213 + //         try {
1214 + //             r.run();
1215 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1216 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1217 + //             throw new AssertionFailedError("did not return promptly");
1218 + //     }
1219 +
1220 + //     void assertTerminatesPromptly(Runnable r) {
1221 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1222 + //     }
1223 +
1224 +    /**
1225 +     * Checks that timed f.get() returns the expected value, and does not
1226 +     * wait for the timeout to elapse before returning.
1227 +     */
1228 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1229 +        long startTime = System.nanoTime();
1230 +        try {
1231 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1232 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1233 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1234 +            throw new AssertionFailedError("timed get did not return promptly");
1235 +    }
1236 +
1237 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1238 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1239 +    }
1240 +
1241      /**
1242       * Returns a new started daemon Thread running the given runnable.
1243       */
# Line 887 | Line 1256 | public class JSR166TestCase extends Test
1256      void awaitTermination(Thread t, long timeoutMillis) {
1257          try {
1258              t.join(timeoutMillis);
1259 <        } catch (InterruptedException ie) {
1260 <            threadUnexpectedException(ie);
1259 >        } catch (InterruptedException fail) {
1260 >            threadUnexpectedException(fail);
1261          } finally {
1262              if (t.getState() != Thread.State.TERMINATED) {
1263                  t.interrupt();
1264 <                fail("Test timed out");
1264 >                threadFail("timed out waiting for thread to terminate");
1265              }
1266          }
1267      }
# Line 914 | Line 1283 | public class JSR166TestCase extends Test
1283          public final void run() {
1284              try {
1285                  realRun();
1286 <            } catch (Throwable t) {
1287 <                threadUnexpectedException(t);
1286 >            } catch (Throwable fail) {
1287 >                threadUnexpectedException(fail);
1288              }
1289          }
1290      }
# Line 969 | Line 1338 | public class JSR166TestCase extends Test
1338                  threadShouldThrow("InterruptedException");
1339              } catch (InterruptedException success) {
1340                  threadAssertFalse(Thread.interrupted());
1341 <            } catch (Throwable t) {
1342 <                threadUnexpectedException(t);
1341 >            } catch (Throwable fail) {
1342 >                threadUnexpectedException(fail);
1343              }
1344          }
1345      }
# Line 981 | Line 1350 | public class JSR166TestCase extends Test
1350          public final T call() {
1351              try {
1352                  return realCall();
1353 <            } catch (Throwable t) {
1354 <                threadUnexpectedException(t);
1353 >            } catch (Throwable fail) {
1354 >                threadUnexpectedException(fail);
1355                  return null;
1356              }
1357          }
# Line 999 | Line 1368 | public class JSR166TestCase extends Test
1368                  return result;
1369              } catch (InterruptedException success) {
1370                  threadAssertFalse(Thread.interrupted());
1371 <            } catch (Throwable t) {
1372 <                threadUnexpectedException(t);
1371 >            } catch (Throwable fail) {
1372 >                threadUnexpectedException(fail);
1373              }
1374              return null;
1375          }
# Line 1017 | Line 1386 | public class JSR166TestCase extends Test
1386      public static final String TEST_STRING = "a test string";
1387  
1388      public static class StringTask implements Callable<String> {
1389 <        public String call() { return TEST_STRING; }
1389 >        final String value;
1390 >        public StringTask() { this(TEST_STRING); }
1391 >        public StringTask(String value) { this.value = value; }
1392 >        public String call() { return value; }
1393      }
1394  
1395      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1030 | Line 1402 | public class JSR166TestCase extends Test
1402              }};
1403      }
1404  
1405 <    public Runnable awaiter(final CountDownLatch latch) {
1405 >    public Runnable countDowner(final CountDownLatch latch) {
1406          return new CheckedRunnable() {
1407              public void realRun() throws InterruptedException {
1408 <                await(latch);
1408 >                latch.countDown();
1409              }};
1410      }
1411  
1412 +    class LatchAwaiter extends CheckedRunnable {
1413 +        static final int NEW = 0;
1414 +        static final int RUNNING = 1;
1415 +        static final int DONE = 2;
1416 +        final CountDownLatch latch;
1417 +        int state = NEW;
1418 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1419 +        public void realRun() throws InterruptedException {
1420 +            state = 1;
1421 +            await(latch);
1422 +            state = 2;
1423 +        }
1424 +    }
1425 +
1426 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1427 +        return new LatchAwaiter(latch);
1428 +    }
1429 +
1430      public void await(CountDownLatch latch) {
1431          try {
1432 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1433 <        } catch (Throwable t) {
1434 <            threadUnexpectedException(t);
1432 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1433 >                fail("timed out waiting for CountDownLatch for "
1434 >                     + (LONG_DELAY_MS/1000) + " sec");
1435 >        } catch (Throwable fail) {
1436 >            threadUnexpectedException(fail);
1437          }
1438      }
1439  
1440      public void await(Semaphore semaphore) {
1441          try {
1442 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1443 <        } catch (Throwable t) {
1444 <            threadUnexpectedException(t);
1442 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1443 >                fail("timed out waiting for Semaphore for "
1444 >                     + (LONG_DELAY_MS/1000) + " sec");
1445 >        } catch (Throwable fail) {
1446 >            threadUnexpectedException(fail);
1447          }
1448      }
1449  
# Line 1243 | Line 1637 | public class JSR166TestCase extends Test
1637          @Override protected final void compute() {
1638              try {
1639                  realCompute();
1640 <            } catch (Throwable t) {
1641 <                threadUnexpectedException(t);
1640 >            } catch (Throwable fail) {
1641 >                threadUnexpectedException(fail);
1642              }
1643          }
1644      }
# Line 1258 | Line 1652 | public class JSR166TestCase extends Test
1652          @Override protected final T compute() {
1653              try {
1654                  return realCompute();
1655 <            } catch (Throwable t) {
1656 <                threadUnexpectedException(t);
1655 >            } catch (Throwable fail) {
1656 >                threadUnexpectedException(fail);
1657                  return null;
1658              }
1659          }
# Line 1283 | Line 1677 | public class JSR166TestCase extends Test
1677          public int await() {
1678              try {
1679                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1680 <            } catch (TimeoutException e) {
1680 >            } catch (TimeoutException timedOut) {
1681                  throw new AssertionFailedError("timed out");
1682 <            } catch (Exception e) {
1682 >            } catch (Exception fail) {
1683                  AssertionFailedError afe =
1684 <                    new AssertionFailedError("Unexpected exception: " + e);
1685 <                afe.initCause(e);
1684 >                    new AssertionFailedError("Unexpected exception: " + fail);
1685 >                afe.initCause(fail);
1686                  throw afe;
1687              }
1688          }
# Line 1316 | Line 1710 | public class JSR166TestCase extends Test
1710                  q.remove();
1711                  shouldThrow();
1712              } catch (NoSuchElementException success) {}
1713 <        } catch (InterruptedException ie) {
1320 <            threadUnexpectedException(ie);
1321 <        }
1713 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1714      }
1715  
1716      void assertSerialEquals(Object x, Object y) {
# Line 1337 | Line 1729 | public class JSR166TestCase extends Test
1729              oos.flush();
1730              oos.close();
1731              return bos.toByteArray();
1732 <        } catch (Throwable t) {
1733 <            threadUnexpectedException(t);
1732 >        } catch (Throwable fail) {
1733 >            threadUnexpectedException(fail);
1734              return new byte[0];
1735          }
1736      }
# Line 1351 | Line 1743 | public class JSR166TestCase extends Test
1743              T clone = (T) ois.readObject();
1744              assertSame(o.getClass(), clone.getClass());
1745              return clone;
1746 <        } catch (Throwable t) {
1747 <            threadUnexpectedException(t);
1746 >        } catch (Throwable fail) {
1747 >            threadUnexpectedException(fail);
1748              return null;
1749          }
1750      }
# Line 1377 | Line 1769 | public class JSR166TestCase extends Test
1769                  shouldThrow(expectedExceptionClass.getName());
1770          }
1771      }
1772 +
1773 +    public void assertIteratorExhausted(Iterator<?> it) {
1774 +        try {
1775 +            it.next();
1776 +            shouldThrow();
1777 +        } catch (NoSuchElementException success) {}
1778 +        assertFalse(it.hasNext());
1779 +    }
1780   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines