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.108 by jsr166, Mon Jun 3 18:20:05 2013 UTC vs.
Revision 1.199 by jsr166, Sat Aug 6 16:24:05 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > /*
10 > * @test
11 > * @summary JSR-166 tck tests
12 > * @modules java.management
13 > * @build *
14 > * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
15 > * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
16 > * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -Djava.util.secureRandomSeed=true JSR166TestCase
17 > */
18 >
19 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
20 > import static java.util.concurrent.TimeUnit.MINUTES;
21 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
22 >
23   import java.io.ByteArrayInputStream;
24   import java.io.ByteArrayOutputStream;
25   import java.io.ObjectInputStream;
26   import java.io.ObjectOutputStream;
27   import java.lang.management.ManagementFactory;
28   import java.lang.management.ThreadInfo;
29 + import java.lang.management.ThreadMXBean;
30 + import java.lang.reflect.Constructor;
31   import java.lang.reflect.Method;
32 + import java.lang.reflect.Modifier;
33 + import java.nio.file.Files;
34 + import java.nio.file.Paths;
35 + import java.security.CodeSource;
36 + import java.security.Permission;
37 + import java.security.PermissionCollection;
38 + import java.security.Permissions;
39 + import java.security.Policy;
40 + import java.security.ProtectionDomain;
41 + import java.security.SecurityPermission;
42   import java.util.ArrayList;
43   import java.util.Arrays;
44   import java.util.Date;
45   import java.util.Enumeration;
46 + import java.util.Iterator;
47   import java.util.List;
48   import java.util.NoSuchElementException;
49   import java.util.PropertyPermission;
50 < import java.util.concurrent.*;
50 > import java.util.concurrent.BlockingQueue;
51 > import java.util.concurrent.Callable;
52 > import java.util.concurrent.CountDownLatch;
53 > import java.util.concurrent.CyclicBarrier;
54 > import java.util.concurrent.ExecutionException;
55 > import java.util.concurrent.Executors;
56 > import java.util.concurrent.ExecutorService;
57 > import java.util.concurrent.ForkJoinPool;
58 > import java.util.concurrent.Future;
59 > import java.util.concurrent.RecursiveAction;
60 > import java.util.concurrent.RecursiveTask;
61 > import java.util.concurrent.RejectedExecutionHandler;
62 > import java.util.concurrent.Semaphore;
63 > import java.util.concurrent.SynchronousQueue;
64 > import java.util.concurrent.ThreadFactory;
65 > import java.util.concurrent.ThreadPoolExecutor;
66 > import java.util.concurrent.TimeoutException;
67   import java.util.concurrent.atomic.AtomicBoolean;
68   import java.util.concurrent.atomic.AtomicReference;
69 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
70 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
71 < import java.security.CodeSource;
72 < import java.security.Permission;
73 < import java.security.PermissionCollection;
74 < import java.security.Permissions;
75 < import java.security.Policy;
76 < import java.security.ProtectionDomain;
35 < import java.security.SecurityPermission;
69 > import java.util.regex.Matcher;
70 > import java.util.regex.Pattern;
71 >
72 > import junit.framework.AssertionFailedError;
73 > import junit.framework.Test;
74 > import junit.framework.TestCase;
75 > import junit.framework.TestResult;
76 > import junit.framework.TestSuite;
77  
78   /**
79   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 44 | Line 85 | import java.security.SecurityPermission;
85   *
86   * <ol>
87   *
88 < * <li> All assertions in code running in generated threads must use
88 > * <li>All assertions in code running in generated threads must use
89   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
90   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
91   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
92   * particularly recommended) for other code to use these forms too.
93   * Only the most typically used JUnit assertion methods are defined
94 < * this way, but enough to live with.</li>
94 > * this way, but enough to live with.
95   *
96 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
96 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
97   * to invoke {@code super.setUp} and {@code super.tearDown} within
98   * them. These methods are used to clear and check for thread
99 < * assertion failures.</li>
99 > * assertion failures.
100   *
101   * <li>All delays and timeouts must use one of the constants {@code
102   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 66 | Line 107 | import java.security.SecurityPermission;
107   * is always discriminable as larger than SHORT and smaller than
108   * MEDIUM.  And so on. These constants are set to conservative values,
109   * but even so, if there is ever any doubt, they can all be increased
110 < * in one spot to rerun tests on slower platforms.</li>
110 > * in one spot to rerun tests on slower platforms.
111   *
112 < * <li> All threads generated must be joined inside each test case
112 > * <li>All threads generated must be joined inside each test case
113   * method (or {@code fail} to do so) before returning from the
114   * method. The {@code joinPool} method can be used to do this when
115 < * using Executors.</li>
115 > * using Executors.
116   *
117   * </ol>
118   *
119   * <p><b>Other notes</b>
120   * <ul>
121   *
122 < * <li> Usually, there is one testcase method per JSR166 method
122 > * <li>Usually, there is one testcase method per JSR166 method
123   * covering "normal" operation, and then as many exception-testing
124   * methods as there are exceptions the method can throw. Sometimes
125   * there are multiple tests per JSR166 method when the different
126   * "normal" behaviors differ significantly. And sometimes testcases
127 < * cover multiple methods when they cannot be tested in
87 < * isolation.</li>
127 > * cover multiple methods when they cannot be tested in isolation.
128   *
129 < * <li> The documentation style for testcases is to provide as javadoc
129 > * <li>The documentation style for testcases is to provide as javadoc
130   * a simple sentence or two describing the property that the testcase
131   * method purports to test. The javadocs do not say anything about how
132 < * the property is tested. To find out, read the code.</li>
132 > * the property is tested. To find out, read the code.
133   *
134 < * <li> These tests are "conformance tests", and do not attempt to
134 > * <li>These tests are "conformance tests", and do not attempt to
135   * test throughput, latency, scalability or other performance factors
136   * (see the separate "jtreg" tests for a set intended to check these
137   * for the most central aspects of functionality.) So, most tests use
138   * the smallest sensible numbers of threads, collection sizes, etc
139 < * needed to check basic conformance.</li>
139 > * needed to check basic conformance.
140   *
141   * <li>The test classes currently do not declare inclusion in
142   * any particular package to simplify things for people integrating
143 < * them in TCK test suites.</li>
143 > * them in TCK test suites.
144   *
145 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
146 < * runs all JSR166 unit tests.</li>
145 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
146 > * runs all JSR166 unit tests.
147   *
148   * </ul>
149   */
# Line 115 | Line 155 | public class JSR166TestCase extends Test
155          Boolean.getBoolean("jsr166.expensiveTests");
156  
157      /**
158 +     * If true, also run tests that are not part of the official tck
159 +     * because they test unspecified implementation details.
160 +     */
161 +    protected static final boolean testImplementationDetails =
162 +        Boolean.getBoolean("jsr166.testImplementationDetails");
163 +
164 +    /**
165       * If true, report on stdout all "slow" tests, that is, ones that
166       * take more than profileThreshold milliseconds to execute.
167       */
# Line 134 | Line 181 | public class JSR166TestCase extends Test
181      private static final int runsPerTest =
182          Integer.getInteger("jsr166.runsPerTest", 1);
183  
184 +    /**
185 +     * The number of repetitions of the test suite (for finding leaks?).
186 +     */
187 +    private static final int suiteRuns =
188 +        Integer.getInteger("jsr166.suiteRuns", 1);
189 +
190 +    /**
191 +     * Returns the value of the system property, or NaN if not defined.
192 +     */
193 +    private static float systemPropertyValue(String name) {
194 +        String floatString = System.getProperty(name);
195 +        if (floatString == null)
196 +            return Float.NaN;
197 +        try {
198 +            return Float.parseFloat(floatString);
199 +        } catch (NumberFormatException ex) {
200 +            throw new IllegalArgumentException(
201 +                String.format("Bad float value in system property %s=%s",
202 +                              name, floatString));
203 +        }
204 +    }
205 +
206 +    /**
207 +     * The scaling factor to apply to standard delays used in tests.
208 +     * May be initialized from any of:
209 +     * - the "jsr166.delay.factor" system property
210 +     * - the "test.timeout.factor" system property (as used by jtreg)
211 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
212 +     * - hard-coded fuzz factor when using a known slowpoke VM
213 +     */
214 +    private static final float delayFactor = delayFactor();
215 +
216 +    private static float delayFactor() {
217 +        float x;
218 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
219 +            return x;
220 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
221 +            return x;
222 +        String prop = System.getProperty("java.vm.version");
223 +        if (prop != null && prop.matches(".*debug.*"))
224 +            return 4.0f; // How much slower is fastdebug than product?!
225 +        return 1.0f;
226 +    }
227 +
228 +    public JSR166TestCase() { super(); }
229 +    public JSR166TestCase(String name) { super(name); }
230 +
231 +    /**
232 +     * A filter for tests to run, matching strings of the form
233 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
234 +     * Usefully combined with jsr166.runsPerTest.
235 +     */
236 +    private static final Pattern methodFilter = methodFilter();
237 +
238 +    private static Pattern methodFilter() {
239 +        String regex = System.getProperty("jsr166.methodFilter");
240 +        return (regex == null) ? null : Pattern.compile(regex);
241 +    }
242 +
243 +    // Instrumentation to debug very rare, but very annoying hung test runs.
244 +    static volatile TestCase currentTestCase;
245 +    // static volatile int currentRun = 0;
246 +    static {
247 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
248 +            // Avoid spurious reports with enormous runsPerTest.
249 +            // A single test case run should never take more than 1 second.
250 +            // But let's cap it at the high end too ...
251 +            final int timeoutMinutes =
252 +                Math.min(15, Math.max(runsPerTest / 60, 1));
253 +            for (TestCase lastTestCase = currentTestCase;;) {
254 +                try { MINUTES.sleep(timeoutMinutes); }
255 +                catch (InterruptedException unexpected) { break; }
256 +                if (lastTestCase == currentTestCase) {
257 +                    System.err.printf(
258 +                        "Looks like we're stuck running test: %s%n",
259 +                        lastTestCase);
260 + //                     System.err.printf(
261 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
262 + //                         lastTestCase, currentRun, runsPerTest);
263 + //                     System.err.println("availableProcessors=" +
264 + //                         Runtime.getRuntime().availableProcessors());
265 + //                     System.err.printf("cpu model = %s%n", cpuModel());
266 +                    dumpTestThreads();
267 +                    // one stack dump is probably enough; more would be spam
268 +                    break;
269 +                }
270 +                lastTestCase = currentTestCase;
271 +            }}};
272 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
273 +        thread.setDaemon(true);
274 +        thread.start();
275 +    }
276 +
277 + //     public static String cpuModel() {
278 + //         try {
279 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
280 + //                 .matcher(new String(
281 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
282 + //             matcher.find();
283 + //             return matcher.group(1);
284 + //         } catch (Exception ex) { return null; }
285 + //     }
286 +
287 +    public void runBare() throws Throwable {
288 +        currentTestCase = this;
289 +        if (methodFilter == null
290 +            || methodFilter.matcher(toString()).find())
291 +            super.runBare();
292 +    }
293 +
294      protected void runTest() throws Throwable {
295          for (int i = 0; i < runsPerTest; i++) {
296 +            // currentRun = i;
297              if (profileTests)
298                  runTestProfiled();
299              else
# Line 144 | Line 302 | public class JSR166TestCase extends Test
302      }
303  
304      protected void runTestProfiled() throws Throwable {
305 <        long t0 = System.nanoTime();
306 <        try {
305 >        for (int i = 0; i < 2; i++) {
306 >            long startTime = System.nanoTime();
307              super.runTest();
308 <        } finally {
309 <            long elapsedMillis =
310 <                (System.nanoTime() - t0) / (1000L * 1000L);
311 <            if (elapsedMillis >= profileThreshold)
308 >            long elapsedMillis = millisElapsedSince(startTime);
309 >            if (elapsedMillis < profileThreshold)
310 >                break;
311 >            // Never report first run of any test; treat it as a
312 >            // warmup run, notably to trigger all needed classloading,
313 >            if (i > 0)
314                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
315          }
316      }
317  
318      /**
319       * 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.
320       */
321      public static void main(String[] args) {
322 +        main(suite(), args);
323 +    }
324 +
325 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
326 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
327 +        long runTime;
328 +        public void startTest(Test test) {}
329 +        protected void printHeader(long runTime) {
330 +            this.runTime = runTime; // defer printing for later
331 +        }
332 +        protected void printFooter(TestResult result) {
333 +            if (result.wasSuccessful()) {
334 +                getWriter().println("OK (" + result.runCount() + " tests)"
335 +                    + "  Time: " + elapsedTimeAsString(runTime));
336 +            } else {
337 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
338 +                super.printFooter(result);
339 +            }
340 +        }
341 +    }
342 +
343 +    /**
344 +     * Returns a TestRunner that doesn't bother with unnecessary
345 +     * fluff, like printing a "." for each test case.
346 +     */
347 +    static junit.textui.TestRunner newPithyTestRunner() {
348 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
349 +        runner.setPrinter(new PithyResultPrinter(System.out));
350 +        return runner;
351 +    }
352 +
353 +    /**
354 +     * Runs all unit tests in the given test suite.
355 +     * Actual behavior influenced by jsr166.* system properties.
356 +     */
357 +    static void main(Test suite, String[] args) {
358          if (useSecurityManager) {
359              System.err.println("Setting a permissive security manager");
360              Policy.setPolicy(permissivePolicy());
361              System.setSecurityManager(new SecurityManager());
362          }
363 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
364 <
365 <        Test s = suite();
366 <        for (int i = 0; i < iters; ++i) {
173 <            junit.textui.TestRunner.run(s);
363 >        for (int i = 0; i < suiteRuns; i++) {
364 >            TestResult result = newPithyTestRunner().doRun(suite);
365 >            if (!result.wasSuccessful())
366 >                System.exit(1);
367              System.gc();
368              System.runFinalization();
369          }
177        System.exit(0);
370      }
371  
372      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 205 | Line 397 | public class JSR166TestCase extends Test
397      }
398  
399      public static final double JAVA_CLASS_VERSION;
400 +    public static final String JAVA_SPECIFICATION_VERSION;
401      static {
402          try {
403              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
404                  new java.security.PrivilegedAction<Double>() {
405                  public Double run() {
406                      return Double.valueOf(System.getProperty("java.class.version"));}});
407 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
408 +                new java.security.PrivilegedAction<String>() {
409 +                public String run() {
410 +                    return System.getProperty("java.specification.version");}});
411          } catch (Throwable t) {
412              throw new Error(t);
413          }
# Line 219 | Line 416 | public class JSR166TestCase extends Test
416      public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
417      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
418      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
419 +    public static boolean atLeastJava9() {
420 +        return JAVA_CLASS_VERSION >= 53.0
421 +            // As of 2015-09, java9 still uses 52.0 class file version
422 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
423 +    }
424 +    public static boolean atLeastJava10() {
425 +        return JAVA_CLASS_VERSION >= 54.0
426 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
427 +    }
428  
429      /**
430       * Collects all JSR166 unit tests as one suite.
# Line 294 | Line 500 | public class JSR166TestCase extends Test
500          // Java8+ test classes
501          if (atLeastJava8()) {
502              String[] java8TestClassNames = {
503 +                "Atomic8Test",
504                  "CompletableFutureTest",
505                  "ConcurrentHashMap8Test",
506                  "CountedCompleterTest",
507                  "DoubleAccumulatorTest",
508                  "DoubleAdderTest",
509                  "ForkJoinPool8Test",
510 +                "ForkJoinTask8Test",
511                  "LongAccumulatorTest",
512                  "LongAdderTest",
513 +                "SplittableRandomTest",
514                  "StampedLockTest",
515 +                "SubmissionPublisherTest",
516 +                "ThreadLocalRandom8Test",
517 +                "TimeUnit8Test",
518              };
519              addNamedTestClasses(suite, java8TestClassNames);
520          }
521  
522 +        // Java9+ test classes
523 +        if (atLeastJava9()) {
524 +            String[] java9TestClassNames = {
525 +                "AtomicBoolean9Test",
526 +                "AtomicInteger9Test",
527 +                "AtomicIntegerArray9Test",
528 +                "AtomicLong9Test",
529 +                "AtomicLongArray9Test",
530 +                "AtomicReference9Test",
531 +                "AtomicReferenceArray9Test",
532 +                "ExecutorCompletionService9Test",
533 +            };
534 +            addNamedTestClasses(suite, java9TestClassNames);
535 +        }
536 +
537          return suite;
538      }
539  
540 +    /** Returns list of junit-style test method names in given class. */
541 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
542 +        Method[] methods = testClass.getDeclaredMethods();
543 +        ArrayList<String> names = new ArrayList<String>(methods.length);
544 +        for (Method method : methods) {
545 +            if (method.getName().startsWith("test")
546 +                && Modifier.isPublic(method.getModifiers())
547 +                // method.getParameterCount() requires jdk8+
548 +                && method.getParameterTypes().length == 0) {
549 +                names.add(method.getName());
550 +            }
551 +        }
552 +        return names;
553 +    }
554 +
555 +    /**
556 +     * Returns junit-style testSuite for the given test class, but
557 +     * parameterized by passing extra data to each test.
558 +     */
559 +    public static <ExtraData> Test parameterizedTestSuite
560 +        (Class<? extends JSR166TestCase> testClass,
561 +         Class<ExtraData> dataClass,
562 +         ExtraData data) {
563 +        try {
564 +            TestSuite suite = new TestSuite();
565 +            Constructor c =
566 +                testClass.getDeclaredConstructor(dataClass, String.class);
567 +            for (String methodName : testMethodNames(testClass))
568 +                suite.addTest((Test) c.newInstance(data, methodName));
569 +            return suite;
570 +        } catch (Exception e) {
571 +            throw new Error(e);
572 +        }
573 +    }
574 +
575 +    /**
576 +     * Returns junit-style testSuite for the jdk8 extension of the
577 +     * given test class, but parameterized by passing extra data to
578 +     * each test.  Uses reflection to allow compilation in jdk7.
579 +     */
580 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
581 +        (Class<? extends JSR166TestCase> testClass,
582 +         Class<ExtraData> dataClass,
583 +         ExtraData data) {
584 +        if (atLeastJava8()) {
585 +            String name = testClass.getName();
586 +            String name8 = name.replaceAll("Test$", "8Test");
587 +            if (name.equals(name8)) throw new Error(name);
588 +            try {
589 +                return (Test)
590 +                    Class.forName(name8)
591 +                    .getMethod("testSuite", new Class[] { dataClass })
592 +                    .invoke(null, data);
593 +            } catch (Exception e) {
594 +                throw new Error(e);
595 +            }
596 +        } else {
597 +            return new TestSuite();
598 +        }
599 +    }
600 +
601 +    // Delays for timing-dependent tests, in milliseconds.
602  
603      public static long SHORT_DELAY_MS;
604      public static long SMALL_DELAY_MS;
605      public static long MEDIUM_DELAY_MS;
606      public static long LONG_DELAY_MS;
607  
319
608      /**
609 <     * Returns the shortest timed delay. This could
610 <     * be reimplemented to use for example a Property.
609 >     * Returns the shortest timed delay. This can be scaled up for
610 >     * slow machines using the jsr166.delay.factor system property,
611 >     * or via jtreg's -timeoutFactor: flag.
612 >     * http://openjdk.java.net/jtreg/command-help.html
613       */
614      protected long getShortDelay() {
615 <        return 50;
615 >        return (long) (50 * delayFactor);
616      }
617  
618      /**
# Line 344 | Line 634 | public class JSR166TestCase extends Test
634      }
635  
636      /**
637 <     * Returns a new Date instance representing a time delayMillis
638 <     * milliseconds in the future.
637 >     * Returns a new Date instance representing a time at least
638 >     * delayMillis milliseconds in the future.
639       */
640      Date delayedDate(long delayMillis) {
641 <        return new Date(System.currentTimeMillis() + delayMillis);
641 >        // Add 1 because currentTimeMillis is known to round into the past.
642 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
643      }
644  
645      /**
# Line 364 | Line 655 | public class JSR166TestCase extends Test
655       * the same test have no effect.
656       */
657      public void threadRecordFailure(Throwable t) {
658 +        System.err.println(t);
659 +        dumpTestThreads();
660          threadFailure.compareAndSet(null, t);
661      }
662  
# Line 371 | Line 664 | public class JSR166TestCase extends Test
664          setDelays();
665      }
666  
667 +    void tearDownFail(String format, Object... args) {
668 +        String msg = toString() + ": " + String.format(format, args);
669 +        System.err.println(msg);
670 +        dumpTestThreads();
671 +        throw new AssertionFailedError(msg);
672 +    }
673 +
674      /**
675       * Extra checks that get done for all test cases.
676       *
# Line 398 | Line 698 | public class JSR166TestCase extends Test
698          }
699  
700          if (Thread.interrupted())
701 <            throw new AssertionFailedError("interrupt status set in main thread");
701 >            tearDownFail("interrupt status set in main thread");
702  
703          checkForkJoinPoolThreadLeaks();
704      }
705  
706      /**
707 <     * Find missing try { ... } finally { joinPool(e); }
707 >     * Finds missing PoolCleaners
708       */
709      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
710 <        Thread[] survivors = new Thread[5];
710 >        Thread[] survivors = new Thread[7];
711          int count = Thread.enumerate(survivors);
712          for (int i = 0; i < count; i++) {
713              Thread thread = survivors[i];
# Line 415 | Line 715 | public class JSR166TestCase extends Test
715              if (name.startsWith("ForkJoinPool-")) {
716                  // give thread some time to terminate
717                  thread.join(LONG_DELAY_MS);
718 <                if (!thread.isAlive()) continue;
719 <                thread.stop();
720 <                throw new AssertionFailedError
421 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
422 <                                   toString(), name));
718 >                if (thread.isAlive())
719 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
720 >                                 thread);
721              }
722          }
723 +
724 +        if (!ForkJoinPool.commonPool()
725 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
726 +            tearDownFail("ForkJoin common pool thread stuck");
727      }
728  
729      /**
# Line 434 | Line 736 | public class JSR166TestCase extends Test
736              fail(reason);
737          } catch (AssertionFailedError t) {
738              threadRecordFailure(t);
739 <            fail(reason);
739 >            throw t;
740          }
741      }
742  
# Line 502 | Line 804 | public class JSR166TestCase extends Test
804      public void threadAssertEquals(Object x, Object y) {
805          try {
806              assertEquals(x, y);
807 <        } catch (AssertionFailedError t) {
808 <            threadRecordFailure(t);
809 <            throw t;
810 <        } catch (Throwable t) {
811 <            threadUnexpectedException(t);
807 >        } catch (AssertionFailedError fail) {
808 >            threadRecordFailure(fail);
809 >            throw fail;
810 >        } catch (Throwable fail) {
811 >            threadUnexpectedException(fail);
812          }
813      }
814  
# Line 518 | Line 820 | public class JSR166TestCase extends Test
820      public void threadAssertSame(Object x, Object y) {
821          try {
822              assertSame(x, y);
823 <        } catch (AssertionFailedError t) {
824 <            threadRecordFailure(t);
825 <            throw t;
823 >        } catch (AssertionFailedError fail) {
824 >            threadRecordFailure(fail);
825 >            throw fail;
826          }
827      }
828  
# Line 561 | Line 863 | public class JSR166TestCase extends Test
863      /**
864       * Delays, via Thread.sleep, for the given millisecond delay, but
865       * if the sleep is shorter than specified, may re-sleep or yield
866 <     * until time elapses.
866 >     * until time elapses.  Ensures that the given time, as measured
867 >     * by System.nanoTime(), has elapsed.
868       */
869      static void delay(long millis) throws InterruptedException {
870 <        long startTime = System.nanoTime();
871 <        long ns = millis * 1000 * 1000;
872 <        for (;;) {
870 >        long nanos = millis * (1000 * 1000);
871 >        final long wakeupTime = System.nanoTime() + nanos;
872 >        do {
873              if (millis > 0L)
874                  Thread.sleep(millis);
875              else // too short to sleep
876                  Thread.yield();
877 <            long d = ns - (System.nanoTime() - startTime);
878 <            if (d > 0L)
879 <                millis = d / (1000 * 1000);
880 <            else
881 <                break;
877 >            nanos = wakeupTime - System.nanoTime();
878 >            millis = nanos / (1000 * 1000);
879 >        } while (nanos >= 0L);
880 >    }
881 >
882 >    /**
883 >     * Allows use of try-with-resources with per-test thread pools.
884 >     */
885 >    class PoolCleaner implements AutoCloseable {
886 >        private final ExecutorService pool;
887 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
888 >        public void close() { joinPool(pool); }
889 >    }
890 >
891 >    /**
892 >     * An extension of PoolCleaner that has an action to release the pool.
893 >     */
894 >    class PoolCleanerWithReleaser extends PoolCleaner {
895 >        private final Runnable releaser;
896 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
897 >            super(pool);
898 >            this.releaser = releaser;
899 >        }
900 >        public void close() {
901 >            try {
902 >                releaser.run();
903 >            } finally {
904 >                super.close();
905 >            }
906          }
907      }
908  
909 +    PoolCleaner cleaner(ExecutorService pool) {
910 +        return new PoolCleaner(pool);
911 +    }
912 +
913 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
914 +        return new PoolCleanerWithReleaser(pool, releaser);
915 +    }
916 +
917 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
918 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
919 +    }
920 +
921 +    Runnable releaser(final CountDownLatch latch) {
922 +        return new Runnable() { public void run() {
923 +            do { latch.countDown(); }
924 +            while (latch.getCount() > 0);
925 +        }};
926 +    }
927 +
928 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
929 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
930 +    }
931 +
932 +    Runnable releaser(final AtomicBoolean flag) {
933 +        return new Runnable() { public void run() { flag.set(true); }};
934 +    }
935 +
936      /**
937       * Waits out termination of a thread pool or fails doing so.
938       */
939 <    void joinPool(ExecutorService exec) {
939 >    void joinPool(ExecutorService pool) {
940          try {
941 <            exec.shutdown();
942 <            assertTrue("ExecutorService did not terminate in a timely manner",
943 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
941 >            pool.shutdown();
942 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
943 >                try {
944 >                    threadFail("ExecutorService " + pool +
945 >                               " did not terminate in a timely manner");
946 >                } finally {
947 >                    // last resort, for the benefit of subsequent tests
948 >                    pool.shutdownNow();
949 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
950 >                }
951 >            }
952          } catch (SecurityException ok) {
953              // Allowed in case test doesn't have privs
954 <        } catch (InterruptedException ie) {
955 <            fail("Unexpected InterruptedException");
954 >        } catch (InterruptedException fail) {
955 >            threadFail("Unexpected InterruptedException");
956          }
957      }
958  
959      /**
960 <     * A debugging tool to print all stack traces, as jstack does.
960 >     * Like Runnable, but with the freedom to throw anything.
961 >     * junit folks had the same idea:
962 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
963 >     */
964 >    interface Action { public void run() throws Throwable; }
965 >
966 >    /**
967 >     * Runs all the given actions in parallel, failing if any fail.
968 >     * Useful for running multiple variants of tests that are
969 >     * necessarily individually slow because they must block.
970       */
971 <    static void printAllStackTraces() {
972 <        for (ThreadInfo info :
973 <                 ManagementFactory.getThreadMXBean()
974 <                 .dumpAllThreads(true, true))
971 >    void testInParallel(Action ... actions) {
972 >        ExecutorService pool = Executors.newCachedThreadPool();
973 >        try (PoolCleaner cleaner = cleaner(pool)) {
974 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
975 >            for (final Action action : actions)
976 >                futures.add(pool.submit(new CheckedRunnable() {
977 >                    public void realRun() throws Throwable { action.run();}}));
978 >            for (Future<?> future : futures)
979 >                try {
980 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
981 >                } catch (ExecutionException ex) {
982 >                    threadUnexpectedException(ex.getCause());
983 >                } catch (Exception ex) {
984 >                    threadUnexpectedException(ex);
985 >                }
986 >        }
987 >    }
988 >
989 >    /**
990 >     * A debugging tool to print stack traces of most threads, as jstack does.
991 >     * Uninteresting threads are filtered out.
992 >     */
993 >    static void dumpTestThreads() {
994 >        SecurityManager sm = System.getSecurityManager();
995 >        if (sm != null) {
996 >            try {
997 >                System.setSecurityManager(null);
998 >            } catch (SecurityException giveUp) {
999 >                return;
1000 >            }
1001 >        }
1002 >
1003 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1004 >        System.err.println("------ stacktrace dump start ------");
1005 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1006 >            String name = info.getThreadName();
1007 >            if ("Signal Dispatcher".equals(name))
1008 >                continue;
1009 >            if ("Reference Handler".equals(name)
1010 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1011 >                continue;
1012 >            if ("Finalizer".equals(name)
1013 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1014 >                continue;
1015 >            if ("checkForWedgedTest".equals(name))
1016 >                continue;
1017              System.err.print(info);
1018 +        }
1019 +        System.err.println("------ stacktrace dump end ------");
1020 +
1021 +        if (sm != null) System.setSecurityManager(sm);
1022      }
1023  
1024      /**
# Line 620 | Line 1037 | public class JSR166TestCase extends Test
1037              // No need to optimize the failing case via Thread.join.
1038              delay(millis);
1039              assertTrue(thread.isAlive());
1040 <        } catch (InterruptedException ie) {
1041 <            fail("Unexpected InterruptedException");
1040 >        } catch (InterruptedException fail) {
1041 >            threadFail("Unexpected InterruptedException");
1042          }
1043      }
1044  
# Line 642 | Line 1059 | public class JSR166TestCase extends Test
1059              delay(millis);
1060              for (Thread thread : threads)
1061                  assertTrue(thread.isAlive());
1062 <        } catch (InterruptedException ie) {
1063 <            fail("Unexpected InterruptedException");
1062 >        } catch (InterruptedException fail) {
1063 >            threadFail("Unexpected InterruptedException");
1064          }
1065      }
1066  
# Line 664 | Line 1081 | public class JSR166TestCase extends Test
1081              future.get(timeoutMillis, MILLISECONDS);
1082              shouldThrow();
1083          } catch (TimeoutException success) {
1084 <        } catch (Exception e) {
1085 <            threadUnexpectedException(e);
1084 >        } catch (Exception fail) {
1085 >            threadUnexpectedException(fail);
1086          } finally { future.cancel(true); }
1087          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1088      }
# Line 709 | Line 1126 | public class JSR166TestCase extends Test
1126      public static final Integer m6  = new Integer(-6);
1127      public static final Integer m10 = new Integer(-10);
1128  
712
1129      /**
1130       * Runs Runnable r with a security policy that permits precisely
1131       * the specified permissions.  If there is no current security
# Line 822 | Line 1238 | public class JSR166TestCase extends Test
1238      void sleep(long millis) {
1239          try {
1240              delay(millis);
1241 <        } catch (InterruptedException ie) {
1241 >        } catch (InterruptedException fail) {
1242              AssertionFailedError afe =
1243                  new AssertionFailedError("Unexpected InterruptedException");
1244 <            afe.initCause(ie);
1244 >            afe.initCause(fail);
1245              throw afe;
1246          }
1247      }
# Line 835 | Line 1251 | public class JSR166TestCase extends Test
1251       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1252       */
1253      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1254 <        long startTime = System.nanoTime();
1254 >        long startTime = 0L;
1255          for (;;) {
1256              Thread.State s = thread.getState();
1257              if (s == Thread.State.BLOCKED ||
# Line 844 | Line 1260 | public class JSR166TestCase extends Test
1260                  return;
1261              else if (s == Thread.State.TERMINATED)
1262                  fail("Unexpected thread termination");
1263 +            else if (startTime == 0L)
1264 +                startTime = System.nanoTime();
1265              else if (millisElapsedSince(startTime) > timeoutMillis) {
1266                  threadAssertTrue(thread.isAlive());
1267                  return;
# Line 863 | Line 1281 | public class JSR166TestCase extends Test
1281      /**
1282       * Returns the number of milliseconds since time given by
1283       * startNanoTime, which must have been previously returned from a
1284 <     * call to {@link System.nanoTime()}.
1284 >     * call to {@link System#nanoTime()}.
1285       */
1286 <    long millisElapsedSince(long startNanoTime) {
1286 >    static long millisElapsedSince(long startNanoTime) {
1287          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1288      }
1289  
1290 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1291 + //         long startTime = System.nanoTime();
1292 + //         try {
1293 + //             r.run();
1294 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1295 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1296 + //             throw new AssertionFailedError("did not return promptly");
1297 + //     }
1298 +
1299 + //     void assertTerminatesPromptly(Runnable r) {
1300 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1301 + //     }
1302 +
1303 +    /**
1304 +     * Checks that timed f.get() returns the expected value, and does not
1305 +     * wait for the timeout to elapse before returning.
1306 +     */
1307 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1308 +        long startTime = System.nanoTime();
1309 +        try {
1310 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1311 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1312 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1313 +            throw new AssertionFailedError("timed get did not return promptly");
1314 +    }
1315 +
1316 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1317 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1318 +    }
1319 +
1320      /**
1321       * Returns a new started daemon Thread running the given runnable.
1322       */
# Line 887 | Line 1335 | public class JSR166TestCase extends Test
1335      void awaitTermination(Thread t, long timeoutMillis) {
1336          try {
1337              t.join(timeoutMillis);
1338 <        } catch (InterruptedException ie) {
1339 <            threadUnexpectedException(ie);
1338 >        } catch (InterruptedException fail) {
1339 >            threadUnexpectedException(fail);
1340          } finally {
1341              if (t.getState() != Thread.State.TERMINATED) {
1342                  t.interrupt();
1343 <                fail("Test timed out");
1343 >                threadFail("timed out waiting for thread to terminate");
1344              }
1345          }
1346      }
# Line 914 | Line 1362 | public class JSR166TestCase extends Test
1362          public final void run() {
1363              try {
1364                  realRun();
1365 <            } catch (Throwable t) {
1366 <                threadUnexpectedException(t);
1365 >            } catch (Throwable fail) {
1366 >                threadUnexpectedException(fail);
1367              }
1368          }
1369      }
# Line 969 | Line 1417 | public class JSR166TestCase extends Test
1417                  threadShouldThrow("InterruptedException");
1418              } catch (InterruptedException success) {
1419                  threadAssertFalse(Thread.interrupted());
1420 <            } catch (Throwable t) {
1421 <                threadUnexpectedException(t);
1420 >            } catch (Throwable fail) {
1421 >                threadUnexpectedException(fail);
1422              }
1423          }
1424      }
# Line 981 | Line 1429 | public class JSR166TestCase extends Test
1429          public final T call() {
1430              try {
1431                  return realCall();
1432 <            } catch (Throwable t) {
1433 <                threadUnexpectedException(t);
1432 >            } catch (Throwable fail) {
1433 >                threadUnexpectedException(fail);
1434                  return null;
1435              }
1436          }
# Line 999 | Line 1447 | public class JSR166TestCase extends Test
1447                  return result;
1448              } catch (InterruptedException success) {
1449                  threadAssertFalse(Thread.interrupted());
1450 <            } catch (Throwable t) {
1451 <                threadUnexpectedException(t);
1450 >            } catch (Throwable fail) {
1451 >                threadUnexpectedException(fail);
1452              }
1453              return null;
1454          }
# Line 1017 | Line 1465 | public class JSR166TestCase extends Test
1465      public static final String TEST_STRING = "a test string";
1466  
1467      public static class StringTask implements Callable<String> {
1468 <        public String call() { return TEST_STRING; }
1468 >        final String value;
1469 >        public StringTask() { this(TEST_STRING); }
1470 >        public StringTask(String value) { this.value = value; }
1471 >        public String call() { return value; }
1472      }
1473  
1474      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1030 | Line 1481 | public class JSR166TestCase extends Test
1481              }};
1482      }
1483  
1484 <    public Runnable awaiter(final CountDownLatch latch) {
1484 >    public Runnable countDowner(final CountDownLatch latch) {
1485          return new CheckedRunnable() {
1486              public void realRun() throws InterruptedException {
1487 <                await(latch);
1487 >                latch.countDown();
1488              }};
1489      }
1490  
1491 <    public void await(CountDownLatch latch) {
1491 >    class LatchAwaiter extends CheckedRunnable {
1492 >        static final int NEW = 0;
1493 >        static final int RUNNING = 1;
1494 >        static final int DONE = 2;
1495 >        final CountDownLatch latch;
1496 >        int state = NEW;
1497 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1498 >        public void realRun() throws InterruptedException {
1499 >            state = 1;
1500 >            await(latch);
1501 >            state = 2;
1502 >        }
1503 >    }
1504 >
1505 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1506 >        return new LatchAwaiter(latch);
1507 >    }
1508 >
1509 >    public void await(CountDownLatch latch, long timeoutMillis) {
1510          try {
1511 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1512 <        } catch (Throwable t) {
1513 <            threadUnexpectedException(t);
1511 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1512 >                fail("timed out waiting for CountDownLatch for "
1513 >                     + (timeoutMillis/1000) + " sec");
1514 >        } catch (Throwable fail) {
1515 >            threadUnexpectedException(fail);
1516          }
1517      }
1518  
1519 +    public void await(CountDownLatch latch) {
1520 +        await(latch, LONG_DELAY_MS);
1521 +    }
1522 +
1523      public void await(Semaphore semaphore) {
1524          try {
1525 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1526 <        } catch (Throwable t) {
1527 <            threadUnexpectedException(t);
1525 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1526 >                fail("timed out waiting for Semaphore for "
1527 >                     + (LONG_DELAY_MS/1000) + " sec");
1528 >        } catch (Throwable fail) {
1529 >            threadUnexpectedException(fail);
1530          }
1531      }
1532  
# Line 1243 | Line 1720 | public class JSR166TestCase extends Test
1720          @Override protected final void compute() {
1721              try {
1722                  realCompute();
1723 <            } catch (Throwable t) {
1724 <                threadUnexpectedException(t);
1723 >            } catch (Throwable fail) {
1724 >                threadUnexpectedException(fail);
1725              }
1726          }
1727      }
# Line 1258 | Line 1735 | public class JSR166TestCase extends Test
1735          @Override protected final T compute() {
1736              try {
1737                  return realCompute();
1738 <            } catch (Throwable t) {
1739 <                threadUnexpectedException(t);
1738 >            } catch (Throwable fail) {
1739 >                threadUnexpectedException(fail);
1740                  return null;
1741              }
1742          }
# Line 1283 | Line 1760 | public class JSR166TestCase extends Test
1760          public int await() {
1761              try {
1762                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1763 <            } catch (TimeoutException e) {
1763 >            } catch (TimeoutException timedOut) {
1764                  throw new AssertionFailedError("timed out");
1765 <            } catch (Exception e) {
1765 >            } catch (Exception fail) {
1766                  AssertionFailedError afe =
1767 <                    new AssertionFailedError("Unexpected exception: " + e);
1768 <                afe.initCause(e);
1767 >                    new AssertionFailedError("Unexpected exception: " + fail);
1768 >                afe.initCause(fail);
1769                  throw afe;
1770              }
1771          }
# Line 1316 | Line 1793 | public class JSR166TestCase extends Test
1793                  q.remove();
1794                  shouldThrow();
1795              } catch (NoSuchElementException success) {}
1796 <        } catch (InterruptedException ie) {
1320 <            threadUnexpectedException(ie);
1321 <        }
1796 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1797      }
1798  
1799      void assertSerialEquals(Object x, Object y) {
# Line 1337 | Line 1812 | public class JSR166TestCase extends Test
1812              oos.flush();
1813              oos.close();
1814              return bos.toByteArray();
1815 <        } catch (Throwable t) {
1816 <            threadUnexpectedException(t);
1815 >        } catch (Throwable fail) {
1816 >            threadUnexpectedException(fail);
1817              return new byte[0];
1818          }
1819      }
# Line 1351 | Line 1826 | public class JSR166TestCase extends Test
1826              T clone = (T) ois.readObject();
1827              assertSame(o.getClass(), clone.getClass());
1828              return clone;
1829 <        } catch (Throwable t) {
1830 <            threadUnexpectedException(t);
1829 >        } catch (Throwable fail) {
1830 >            threadUnexpectedException(fail);
1831              return null;
1832          }
1833      }
# Line 1377 | Line 1852 | public class JSR166TestCase extends Test
1852                  shouldThrow(expectedExceptionClass.getName());
1853          }
1854      }
1855 +
1856 +    public void assertIteratorExhausted(Iterator<?> it) {
1857 +        try {
1858 +            it.next();
1859 +            shouldThrow();
1860 +        } catch (NoSuchElementException success) {}
1861 +        assertFalse(it.hasNext());
1862 +    }
1863 +
1864 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1865 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1866 +    }
1867 +
1868 +    public Runnable runnableThrowing(final RuntimeException ex) {
1869 +        return new Runnable() { public void run() { throw ex; }};
1870 +    }
1871 +
1872 +    /** A reusable thread pool to be shared by tests. */
1873 +    static final ExecutorService cachedThreadPool =
1874 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1875 +                               1000L, MILLISECONDS,
1876 +                               new SynchronousQueue<Runnable>());
1877 +
1878   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines