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.132 by jsr166, Mon Apr 27 06:01:31 2015 UTC vs.
Revision 1.207 by jsr166, Thu Nov 3 20:41:32 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
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;
# Line 15 | Line 26 | 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;
# Line 25 | Line 41 | import java.security.ProtectionDomain;
41   import java.security.SecurityPermission;
42   import java.util.ArrayList;
43   import java.util.Arrays;
44 + import java.util.Collections;
45   import java.util.Date;
46   import java.util.Enumeration;
47   import java.util.Iterator;
# Line 35 | Line 52 | import java.util.concurrent.BlockingQueu
52   import java.util.concurrent.Callable;
53   import java.util.concurrent.CountDownLatch;
54   import java.util.concurrent.CyclicBarrier;
55 + import java.util.concurrent.ExecutionException;
56 + import java.util.concurrent.Executors;
57   import java.util.concurrent.ExecutorService;
58 + import java.util.concurrent.ForkJoinPool;
59   import java.util.concurrent.Future;
60   import java.util.concurrent.RecursiveAction;
61   import java.util.concurrent.RecursiveTask;
62   import java.util.concurrent.RejectedExecutionHandler;
63   import java.util.concurrent.Semaphore;
64 + import java.util.concurrent.SynchronousQueue;
65   import java.util.concurrent.ThreadFactory;
66 + import java.util.concurrent.ThreadLocalRandom;
67   import java.util.concurrent.ThreadPoolExecutor;
68   import java.util.concurrent.TimeoutException;
69 + import java.util.concurrent.atomic.AtomicBoolean;
70   import java.util.concurrent.atomic.AtomicReference;
71 + import java.util.regex.Matcher;
72   import java.util.regex.Pattern;
73  
74   import junit.framework.AssertionFailedError;
# Line 63 | Line 87 | import junit.framework.TestSuite;
87   *
88   * <ol>
89   *
90 < * <li> All assertions in code running in generated threads must use
90 > * <li>All assertions in code running in generated threads must use
91   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
92   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
93   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
94   * particularly recommended) for other code to use these forms too.
95   * Only the most typically used JUnit assertion methods are defined
96 < * this way, but enough to live with.</li>
96 > * this way, but enough to live with.
97   *
98 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
98 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
99   * to invoke {@code super.setUp} and {@code super.tearDown} within
100   * them. These methods are used to clear and check for thread
101 < * assertion failures.</li>
101 > * assertion failures.
102   *
103   * <li>All delays and timeouts must use one of the constants {@code
104   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 85 | Line 109 | import junit.framework.TestSuite;
109   * is always discriminable as larger than SHORT and smaller than
110   * MEDIUM.  And so on. These constants are set to conservative values,
111   * but even so, if there is ever any doubt, they can all be increased
112 < * in one spot to rerun tests on slower platforms.</li>
112 > * in one spot to rerun tests on slower platforms.
113   *
114 < * <li> All threads generated must be joined inside each test case
114 > * <li>All threads generated must be joined inside each test case
115   * method (or {@code fail} to do so) before returning from the
116   * method. The {@code joinPool} method can be used to do this when
117 < * using Executors.</li>
117 > * using Executors.
118   *
119   * </ol>
120   *
121   * <p><b>Other notes</b>
122   * <ul>
123   *
124 < * <li> Usually, there is one testcase method per JSR166 method
124 > * <li>Usually, there is one testcase method per JSR166 method
125   * covering "normal" operation, and then as many exception-testing
126   * methods as there are exceptions the method can throw. Sometimes
127   * there are multiple tests per JSR166 method when the different
128   * "normal" behaviors differ significantly. And sometimes testcases
129 < * cover multiple methods when they cannot be tested in
106 < * isolation.</li>
129 > * cover multiple methods when they cannot be tested in isolation.
130   *
131 < * <li> The documentation style for testcases is to provide as javadoc
131 > * <li>The documentation style for testcases is to provide as javadoc
132   * a simple sentence or two describing the property that the testcase
133   * method purports to test. The javadocs do not say anything about how
134 < * the property is tested. To find out, read the code.</li>
134 > * the property is tested. To find out, read the code.
135   *
136 < * <li> These tests are "conformance tests", and do not attempt to
136 > * <li>These tests are "conformance tests", and do not attempt to
137   * test throughput, latency, scalability or other performance factors
138   * (see the separate "jtreg" tests for a set intended to check these
139   * for the most central aspects of functionality.) So, most tests use
140   * the smallest sensible numbers of threads, collection sizes, etc
141 < * needed to check basic conformance.</li>
141 > * needed to check basic conformance.
142   *
143   * <li>The test classes currently do not declare inclusion in
144   * any particular package to simplify things for people integrating
145 < * them in TCK test suites.</li>
145 > * them in TCK test suites.
146   *
147 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
148 < * runs all JSR166 unit tests.</li>
147 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
148 > * runs all JSR166 unit tests.
149   *
150   * </ul>
151   */
# Line 167 | Line 190 | public class JSR166TestCase extends Test
190          Integer.getInteger("jsr166.suiteRuns", 1);
191  
192      /**
193 +     * Returns the value of the system property, or NaN if not defined.
194 +     */
195 +    private static float systemPropertyValue(String name) {
196 +        String floatString = System.getProperty(name);
197 +        if (floatString == null)
198 +            return Float.NaN;
199 +        try {
200 +            return Float.parseFloat(floatString);
201 +        } catch (NumberFormatException ex) {
202 +            throw new IllegalArgumentException(
203 +                String.format("Bad float value in system property %s=%s",
204 +                              name, floatString));
205 +        }
206 +    }
207 +
208 +    /**
209 +     * The scaling factor to apply to standard delays used in tests.
210 +     * May be initialized from any of:
211 +     * - the "jsr166.delay.factor" system property
212 +     * - the "test.timeout.factor" system property (as used by jtreg)
213 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
214 +     * - hard-coded fuzz factor when using a known slowpoke VM
215 +     */
216 +    private static final float delayFactor = delayFactor();
217 +
218 +    private static float delayFactor() {
219 +        float x;
220 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
221 +            return x;
222 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
223 +            return x;
224 +        String prop = System.getProperty("java.vm.version");
225 +        if (prop != null && prop.matches(".*debug.*"))
226 +            return 4.0f; // How much slower is fastdebug than product?!
227 +        return 1.0f;
228 +    }
229 +
230 +    public JSR166TestCase() { super(); }
231 +    public JSR166TestCase(String name) { super(name); }
232 +
233 +    /**
234       * A filter for tests to run, matching strings of the form
235       * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
236       * Usefully combined with jsr166.runsPerTest.
# Line 178 | Line 242 | public class JSR166TestCase extends Test
242          return (regex == null) ? null : Pattern.compile(regex);
243      }
244  
245 <    protected void runTest() throws Throwable {
245 >    // Instrumentation to debug very rare, but very annoying hung test runs.
246 >    static volatile TestCase currentTestCase;
247 >    // static volatile int currentRun = 0;
248 >    static {
249 >        Runnable checkForWedgedTest = new Runnable() { public void run() {
250 >            // Avoid spurious reports with enormous runsPerTest.
251 >            // A single test case run should never take more than 1 second.
252 >            // But let's cap it at the high end too ...
253 >            final int timeoutMinutes =
254 >                Math.min(15, Math.max(runsPerTest / 60, 1));
255 >            for (TestCase lastTestCase = currentTestCase;;) {
256 >                try { MINUTES.sleep(timeoutMinutes); }
257 >                catch (InterruptedException unexpected) { break; }
258 >                if (lastTestCase == currentTestCase) {
259 >                    System.err.printf(
260 >                        "Looks like we're stuck running test: %s%n",
261 >                        lastTestCase);
262 > //                     System.err.printf(
263 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
264 > //                         lastTestCase, currentRun, runsPerTest);
265 > //                     System.err.println("availableProcessors=" +
266 > //                         Runtime.getRuntime().availableProcessors());
267 > //                     System.err.printf("cpu model = %s%n", cpuModel());
268 >                    dumpTestThreads();
269 >                    // one stack dump is probably enough; more would be spam
270 >                    break;
271 >                }
272 >                lastTestCase = currentTestCase;
273 >            }}};
274 >        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
275 >        thread.setDaemon(true);
276 >        thread.start();
277 >    }
278 >
279 > //     public static String cpuModel() {
280 > //         try {
281 > //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
282 > //                 .matcher(new String(
283 > //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
284 > //             matcher.find();
285 > //             return matcher.group(1);
286 > //         } catch (Exception ex) { return null; }
287 > //     }
288 >
289 >    public void runBare() throws Throwable {
290 >        currentTestCase = this;
291          if (methodFilter == null
292 <            || methodFilter.matcher(toString()).find()) {
293 <            for (int i = 0; i < runsPerTest; i++) {
294 <                if (profileTests)
295 <                    runTestProfiled();
296 <                else
297 <                    super.runTest();
298 <            }
292 >            || methodFilter.matcher(toString()).find())
293 >            super.runBare();
294 >    }
295 >
296 >    protected void runTest() throws Throwable {
297 >        for (int i = 0; i < runsPerTest; i++) {
298 >            // currentRun = i;
299 >            if (profileTests)
300 >                runTestProfiled();
301 >            else
302 >                super.runTest();
303          }
304      }
305  
306      protected void runTestProfiled() throws Throwable {
307 <        // Warmup run, notably to trigger all needed classloading.
308 <        super.runTest();
196 <        long t0 = System.nanoTime();
197 <        try {
307 >        for (int i = 0; i < 2; i++) {
308 >            long startTime = System.nanoTime();
309              super.runTest();
310 <        } finally {
311 <            long elapsedMillis = millisElapsedSince(t0);
312 <            if (elapsedMillis >= profileThreshold)
310 >            long elapsedMillis = millisElapsedSince(startTime);
311 >            if (elapsedMillis < profileThreshold)
312 >                break;
313 >            // Never report first run of any test; treat it as a
314 >            // warmup run, notably to trigger all needed classloading,
315 >            if (i > 0)
316                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
317          }
318      }
# Line 210 | Line 324 | public class JSR166TestCase extends Test
324          main(suite(), args);
325      }
326  
327 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
328 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
329 +        long runTime;
330 +        public void startTest(Test test) {}
331 +        protected void printHeader(long runTime) {
332 +            this.runTime = runTime; // defer printing for later
333 +        }
334 +        protected void printFooter(TestResult result) {
335 +            if (result.wasSuccessful()) {
336 +                getWriter().println("OK (" + result.runCount() + " tests)"
337 +                    + "  Time: " + elapsedTimeAsString(runTime));
338 +            } else {
339 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
340 +                super.printFooter(result);
341 +            }
342 +        }
343 +    }
344 +
345 +    /**
346 +     * Returns a TestRunner that doesn't bother with unnecessary
347 +     * fluff, like printing a "." for each test case.
348 +     */
349 +    static junit.textui.TestRunner newPithyTestRunner() {
350 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
351 +        runner.setPrinter(new PithyResultPrinter(System.out));
352 +        return runner;
353 +    }
354 +
355      /**
356       * Runs all unit tests in the given test suite.
357       * Actual behavior influenced by jsr166.* system properties.
# Line 221 | Line 363 | public class JSR166TestCase extends Test
363              System.setSecurityManager(new SecurityManager());
364          }
365          for (int i = 0; i < suiteRuns; i++) {
366 <            TestResult result = junit.textui.TestRunner.run(suite);
366 >            TestResult result = newPithyTestRunner().doRun(suite);
367              if (!result.wasSuccessful())
368                  System.exit(1);
369              System.gc();
# Line 276 | Line 418 | public class JSR166TestCase extends Test
418      public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
419      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
420      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
421 <    public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
421 >    public static boolean atLeastJava9() {
422 >        return JAVA_CLASS_VERSION >= 53.0
423 >            // As of 2015-09, java9 still uses 52.0 class file version
424 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
425 >    }
426 >    public static boolean atLeastJava10() {
427 >        return JAVA_CLASS_VERSION >= 54.0
428 >            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
429 >    }
430  
431      /**
432       * Collects all JSR166 unit tests as one suite.
# Line 297 | Line 447 | public class JSR166TestCase extends Test
447              AbstractQueuedLongSynchronizerTest.suite(),
448              ArrayBlockingQueueTest.suite(),
449              ArrayDequeTest.suite(),
450 +            ArrayListTest.suite(),
451              AtomicBooleanTest.suite(),
452              AtomicIntegerArrayTest.suite(),
453              AtomicIntegerFieldUpdaterTest.suite(),
# Line 319 | Line 470 | public class JSR166TestCase extends Test
470              CopyOnWriteArrayListTest.suite(),
471              CopyOnWriteArraySetTest.suite(),
472              CountDownLatchTest.suite(),
473 +            CountedCompleterTest.suite(),
474              CyclicBarrierTest.suite(),
475              DelayQueueTest.suite(),
476              EntryTest.suite(),
# Line 347 | Line 499 | public class JSR166TestCase extends Test
499              TreeMapTest.suite(),
500              TreeSetTest.suite(),
501              TreeSubMapTest.suite(),
502 <            TreeSubSetTest.suite());
502 >            TreeSubSetTest.suite(),
503 >            VectorTest.suite());
504  
505          // Java8+ test classes
506          if (atLeastJava8()) {
507              String[] java8TestClassNames = {
508 +                "ArrayDeque8Test",
509                  "Atomic8Test",
510                  "CompletableFutureTest",
511                  "ConcurrentHashMap8Test",
512 <                "CountedCompleterTest",
512 >                "CountedCompleter8Test",
513                  "DoubleAccumulatorTest",
514                  "DoubleAdderTest",
515                  "ForkJoinPool8Test",
# Line 364 | Line 518 | public class JSR166TestCase extends Test
518                  "LongAdderTest",
519                  "SplittableRandomTest",
520                  "StampedLockTest",
521 +                "SubmissionPublisherTest",
522                  "ThreadLocalRandom8Test",
523 +                "TimeUnit8Test",
524              };
525              addNamedTestClasses(suite, java8TestClassNames);
526          }
# Line 372 | Line 528 | public class JSR166TestCase extends Test
528          // Java9+ test classes
529          if (atLeastJava9()) {
530              String[] java9TestClassNames = {
531 <                "ThreadPoolExecutor9Test",
531 >                "AtomicBoolean9Test",
532 >                "AtomicInteger9Test",
533 >                "AtomicIntegerArray9Test",
534 >                "AtomicLong9Test",
535 >                "AtomicLongArray9Test",
536 >                "AtomicReference9Test",
537 >                "AtomicReferenceArray9Test",
538 >                "ExecutorCompletionService9Test",
539              };
540              addNamedTestClasses(suite, java9TestClassNames);
541          }
# Line 380 | Line 543 | public class JSR166TestCase extends Test
543          return suite;
544      }
545  
546 +    /** Returns list of junit-style test method names in given class. */
547 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
548 +        Method[] methods = testClass.getDeclaredMethods();
549 +        ArrayList<String> names = new ArrayList<String>(methods.length);
550 +        for (Method method : methods) {
551 +            if (method.getName().startsWith("test")
552 +                && Modifier.isPublic(method.getModifiers())
553 +                // method.getParameterCount() requires jdk8+
554 +                && method.getParameterTypes().length == 0) {
555 +                names.add(method.getName());
556 +            }
557 +        }
558 +        return names;
559 +    }
560 +
561 +    /**
562 +     * Returns junit-style testSuite for the given test class, but
563 +     * parameterized by passing extra data to each test.
564 +     */
565 +    public static <ExtraData> Test parameterizedTestSuite
566 +        (Class<? extends JSR166TestCase> testClass,
567 +         Class<ExtraData> dataClass,
568 +         ExtraData data) {
569 +        try {
570 +            TestSuite suite = new TestSuite();
571 +            Constructor c =
572 +                testClass.getDeclaredConstructor(dataClass, String.class);
573 +            for (String methodName : testMethodNames(testClass))
574 +                suite.addTest((Test) c.newInstance(data, methodName));
575 +            return suite;
576 +        } catch (Exception e) {
577 +            throw new Error(e);
578 +        }
579 +    }
580 +
581 +    /**
582 +     * Returns junit-style testSuite for the jdk8 extension of the
583 +     * given test class, but parameterized by passing extra data to
584 +     * each test.  Uses reflection to allow compilation in jdk7.
585 +     */
586 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
587 +        (Class<? extends JSR166TestCase> testClass,
588 +         Class<ExtraData> dataClass,
589 +         ExtraData data) {
590 +        if (atLeastJava8()) {
591 +            String name = testClass.getName();
592 +            String name8 = name.replaceAll("Test$", "8Test");
593 +            if (name.equals(name8)) throw new Error(name);
594 +            try {
595 +                return (Test)
596 +                    Class.forName(name8)
597 +                    .getMethod("testSuite", new Class[] { dataClass })
598 +                    .invoke(null, data);
599 +            } catch (Exception e) {
600 +                throw new Error(e);
601 +            }
602 +        } else {
603 +            return new TestSuite();
604 +        }
605 +    }
606 +
607      // Delays for timing-dependent tests, in milliseconds.
608  
609      public static long SHORT_DELAY_MS;
# Line 388 | Line 612 | public class JSR166TestCase extends Test
612      public static long LONG_DELAY_MS;
613  
614      /**
615 <     * Returns the shortest timed delay. This could
616 <     * be reimplemented to use for example a Property.
615 >     * Returns the shortest timed delay. This can be scaled up for
616 >     * slow machines using the jsr166.delay.factor system property,
617 >     * or via jtreg's -timeoutFactor: flag.
618 >     * http://openjdk.java.net/jtreg/command-help.html
619       */
620      protected long getShortDelay() {
621 <        return 50;
621 >        return (long) (50 * delayFactor);
622      }
623  
624      /**
# Line 414 | Line 640 | public class JSR166TestCase extends Test
640      }
641  
642      /**
643 <     * Returns a new Date instance representing a time delayMillis
644 <     * milliseconds in the future.
643 >     * Returns a new Date instance representing a time at least
644 >     * delayMillis milliseconds in the future.
645       */
646      Date delayedDate(long delayMillis) {
647 <        return new Date(System.currentTimeMillis() + delayMillis);
647 >        // Add 1 because currentTimeMillis is known to round into the past.
648 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
649      }
650  
651      /**
# Line 434 | Line 661 | public class JSR166TestCase extends Test
661       * the same test have no effect.
662       */
663      public void threadRecordFailure(Throwable t) {
664 +        System.err.println(t);
665 +        dumpTestThreads();
666          threadFailure.compareAndSet(null, t);
667      }
668  
# Line 441 | Line 670 | public class JSR166TestCase extends Test
670          setDelays();
671      }
672  
673 +    void tearDownFail(String format, Object... args) {
674 +        String msg = toString() + ": " + String.format(format, args);
675 +        System.err.println(msg);
676 +        dumpTestThreads();
677 +        throw new AssertionFailedError(msg);
678 +    }
679 +
680      /**
681       * Extra checks that get done for all test cases.
682       *
# Line 468 | Line 704 | public class JSR166TestCase extends Test
704          }
705  
706          if (Thread.interrupted())
707 <            throw new AssertionFailedError("interrupt status set in main thread");
707 >            tearDownFail("interrupt status set in main thread");
708  
709          checkForkJoinPoolThreadLeaks();
710      }
711  
712      /**
713 <     * Finds missing try { ... } finally { joinPool(e); }
713 >     * Finds missing PoolCleaners
714       */
715      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
716 <        Thread[] survivors = new Thread[5];
716 >        Thread[] survivors = new Thread[7];
717          int count = Thread.enumerate(survivors);
718          for (int i = 0; i < count; i++) {
719              Thread thread = survivors[i];
# Line 485 | Line 721 | public class JSR166TestCase extends Test
721              if (name.startsWith("ForkJoinPool-")) {
722                  // give thread some time to terminate
723                  thread.join(LONG_DELAY_MS);
724 <                if (!thread.isAlive()) continue;
725 <                thread.stop();
726 <                throw new AssertionFailedError
491 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
492 <                                   toString(), name));
724 >                if (thread.isAlive())
725 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
726 >                                 thread);
727              }
728          }
729 +
730 +        if (!ForkJoinPool.commonPool()
731 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
732 +            tearDownFail("ForkJoin common pool thread stuck");
733      }
734  
735      /**
# Line 504 | Line 742 | public class JSR166TestCase extends Test
742              fail(reason);
743          } catch (AssertionFailedError t) {
744              threadRecordFailure(t);
745 <            fail(reason);
745 >            throw t;
746          }
747      }
748  
# Line 631 | Line 869 | public class JSR166TestCase extends Test
869      /**
870       * Delays, via Thread.sleep, for the given millisecond delay, but
871       * if the sleep is shorter than specified, may re-sleep or yield
872 <     * until time elapses.
872 >     * until time elapses.  Ensures that the given time, as measured
873 >     * by System.nanoTime(), has elapsed.
874       */
875      static void delay(long millis) throws InterruptedException {
876 <        long startTime = System.nanoTime();
877 <        long ns = millis * 1000 * 1000;
878 <        for (;;) {
876 >        long nanos = millis * (1000 * 1000);
877 >        final long wakeupTime = System.nanoTime() + nanos;
878 >        do {
879              if (millis > 0L)
880                  Thread.sleep(millis);
881              else // too short to sleep
882                  Thread.yield();
883 <            long d = ns - (System.nanoTime() - startTime);
884 <            if (d > 0L)
885 <                millis = d / (1000 * 1000);
886 <            else
887 <                break;
883 >            nanos = wakeupTime - System.nanoTime();
884 >            millis = nanos / (1000 * 1000);
885 >        } while (nanos >= 0L);
886 >    }
887 >
888 >    /**
889 >     * Allows use of try-with-resources with per-test thread pools.
890 >     */
891 >    class PoolCleaner implements AutoCloseable {
892 >        private final ExecutorService pool;
893 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
894 >        public void close() { joinPool(pool); }
895 >    }
896 >
897 >    /**
898 >     * An extension of PoolCleaner that has an action to release the pool.
899 >     */
900 >    class PoolCleanerWithReleaser extends PoolCleaner {
901 >        private final Runnable releaser;
902 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
903 >            super(pool);
904 >            this.releaser = releaser;
905 >        }
906 >        public void close() {
907 >            try {
908 >                releaser.run();
909 >            } finally {
910 >                super.close();
911 >            }
912          }
913      }
914  
915 +    PoolCleaner cleaner(ExecutorService pool) {
916 +        return new PoolCleaner(pool);
917 +    }
918 +
919 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
920 +        return new PoolCleanerWithReleaser(pool, releaser);
921 +    }
922 +
923 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
924 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
925 +    }
926 +
927 +    Runnable releaser(final CountDownLatch latch) {
928 +        return new Runnable() { public void run() {
929 +            do { latch.countDown(); }
930 +            while (latch.getCount() > 0);
931 +        }};
932 +    }
933 +
934 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
935 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
936 +    }
937 +
938 +    Runnable releaser(final AtomicBoolean flag) {
939 +        return new Runnable() { public void run() { flag.set(true); }};
940 +    }
941 +
942      /**
943       * Waits out termination of a thread pool or fails doing so.
944       */
945 <    void joinPool(ExecutorService exec) {
945 >    void joinPool(ExecutorService pool) {
946          try {
947 <            exec.shutdown();
948 <            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
949 <                fail("ExecutorService " + exec +
950 <                     " did not terminate in a timely manner");
947 >            pool.shutdown();
948 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
949 >                try {
950 >                    threadFail("ExecutorService " + pool +
951 >                               " did not terminate in a timely manner");
952 >                } finally {
953 >                    // last resort, for the benefit of subsequent tests
954 >                    pool.shutdownNow();
955 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
956 >                }
957 >            }
958          } catch (SecurityException ok) {
959              // Allowed in case test doesn't have privs
960          } catch (InterruptedException fail) {
961 <            fail("Unexpected InterruptedException");
961 >            threadFail("Unexpected InterruptedException");
962          }
963      }
964  
965      /**
966 <     * A debugging tool to print all stack traces, as jstack does.
966 >     * Like Runnable, but with the freedom to throw anything.
967 >     * junit folks had the same idea:
968 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
969       */
970 <    static void printAllStackTraces() {
971 <        for (ThreadInfo info :
972 <                 ManagementFactory.getThreadMXBean()
973 <                 .dumpAllThreads(true, true))
970 >    interface Action { public void run() throws Throwable; }
971 >
972 >    /**
973 >     * Runs all the given actions in parallel, failing if any fail.
974 >     * Useful for running multiple variants of tests that are
975 >     * necessarily individually slow because they must block.
976 >     */
977 >    void testInParallel(Action ... actions) {
978 >        ExecutorService pool = Executors.newCachedThreadPool();
979 >        try (PoolCleaner cleaner = cleaner(pool)) {
980 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
981 >            for (final Action action : actions)
982 >                futures.add(pool.submit(new CheckedRunnable() {
983 >                    public void realRun() throws Throwable { action.run();}}));
984 >            for (Future<?> future : futures)
985 >                try {
986 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
987 >                } catch (ExecutionException ex) {
988 >                    threadUnexpectedException(ex.getCause());
989 >                } catch (Exception ex) {
990 >                    threadUnexpectedException(ex);
991 >                }
992 >        }
993 >    }
994 >
995 >    /**
996 >     * A debugging tool to print stack traces of most threads, as jstack does.
997 >     * Uninteresting threads are filtered out.
998 >     */
999 >    static void dumpTestThreads() {
1000 >        SecurityManager sm = System.getSecurityManager();
1001 >        if (sm != null) {
1002 >            try {
1003 >                System.setSecurityManager(null);
1004 >            } catch (SecurityException giveUp) {
1005 >                return;
1006 >            }
1007 >        }
1008 >
1009 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1010 >        System.err.println("------ stacktrace dump start ------");
1011 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1012 >            final String name = info.getThreadName();
1013 >            String lockName;
1014 >            if ("Signal Dispatcher".equals(name))
1015 >                continue;
1016 >            if ("Reference Handler".equals(name)
1017 >                && (lockName = info.getLockName()) != null
1018 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1019 >                continue;
1020 >            if ("Finalizer".equals(name)
1021 >                && (lockName = info.getLockName()) != null
1022 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1023 >                continue;
1024 >            if ("checkForWedgedTest".equals(name))
1025 >                continue;
1026              System.err.print(info);
1027 +        }
1028 +        System.err.println("------ stacktrace dump end ------");
1029 +
1030 +        if (sm != null) System.setSecurityManager(sm);
1031      }
1032  
1033      /**
# Line 692 | Line 1047 | public class JSR166TestCase extends Test
1047              delay(millis);
1048              assertTrue(thread.isAlive());
1049          } catch (InterruptedException fail) {
1050 <            fail("Unexpected InterruptedException");
1050 >            threadFail("Unexpected InterruptedException");
1051          }
1052      }
1053  
# Line 714 | Line 1069 | public class JSR166TestCase extends Test
1069              for (Thread thread : threads)
1070                  assertTrue(thread.isAlive());
1071          } catch (InterruptedException fail) {
1072 <            fail("Unexpected InterruptedException");
1072 >            threadFail("Unexpected InterruptedException");
1073          }
1074      }
1075  
# Line 889 | Line 1244 | public class JSR166TestCase extends Test
1244       * Sleeps until the given time has elapsed.
1245       * Throws AssertionFailedError if interrupted.
1246       */
1247 <    void sleep(long millis) {
1247 >    static void sleep(long millis) {
1248          try {
1249              delay(millis);
1250          } catch (InterruptedException fail) {
# Line 905 | Line 1260 | public class JSR166TestCase extends Test
1260       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1261       */
1262      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1263 <        long startTime = System.nanoTime();
1263 >        long startTime = 0L;
1264          for (;;) {
1265              Thread.State s = thread.getState();
1266              if (s == Thread.State.BLOCKED ||
# Line 914 | Line 1269 | public class JSR166TestCase extends Test
1269                  return;
1270              else if (s == Thread.State.TERMINATED)
1271                  fail("Unexpected thread termination");
1272 +            else if (startTime == 0L)
1273 +                startTime = System.nanoTime();
1274              else if (millisElapsedSince(startTime) > timeoutMillis) {
1275                  threadAssertTrue(thread.isAlive());
1276                  return;
# Line 992 | Line 1349 | public class JSR166TestCase extends Test
1349          } finally {
1350              if (t.getState() != Thread.State.TERMINATED) {
1351                  t.interrupt();
1352 <                fail("Test timed out");
1352 >                threadFail("timed out waiting for thread to terminate");
1353              }
1354          }
1355      }
# Line 1117 | Line 1474 | public class JSR166TestCase extends Test
1474      public static final String TEST_STRING = "a test string";
1475  
1476      public static class StringTask implements Callable<String> {
1477 <        public String call() { return TEST_STRING; }
1477 >        final String value;
1478 >        public StringTask() { this(TEST_STRING); }
1479 >        public StringTask(String value) { this.value = value; }
1480 >        public String call() { return value; }
1481      }
1482  
1483      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1130 | Line 1490 | public class JSR166TestCase extends Test
1490              }};
1491      }
1492  
1493 <    public Runnable awaiter(final CountDownLatch latch) {
1493 >    public Runnable countDowner(final CountDownLatch latch) {
1494          return new CheckedRunnable() {
1495              public void realRun() throws InterruptedException {
1496 <                await(latch);
1496 >                latch.countDown();
1497              }};
1498      }
1499  
1500 <    public void await(CountDownLatch latch) {
1500 >    class LatchAwaiter extends CheckedRunnable {
1501 >        static final int NEW = 0;
1502 >        static final int RUNNING = 1;
1503 >        static final int DONE = 2;
1504 >        final CountDownLatch latch;
1505 >        int state = NEW;
1506 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1507 >        public void realRun() throws InterruptedException {
1508 >            state = 1;
1509 >            await(latch);
1510 >            state = 2;
1511 >        }
1512 >    }
1513 >
1514 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1515 >        return new LatchAwaiter(latch);
1516 >    }
1517 >
1518 >    public void await(CountDownLatch latch, long timeoutMillis) {
1519          try {
1520 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1520 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1521 >                fail("timed out waiting for CountDownLatch for "
1522 >                     + (timeoutMillis/1000) + " sec");
1523          } catch (Throwable fail) {
1524              threadUnexpectedException(fail);
1525          }
1526      }
1527  
1528 +    public void await(CountDownLatch latch) {
1529 +        await(latch, LONG_DELAY_MS);
1530 +    }
1531 +
1532      public void await(Semaphore semaphore) {
1533          try {
1534 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1534 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1535 >                fail("timed out waiting for Semaphore for "
1536 >                     + (LONG_DELAY_MS/1000) + " sec");
1537          } catch (Throwable fail) {
1538              threadUnexpectedException(fail);
1539          }
# Line 1377 | Line 1763 | public class JSR166TestCase extends Test
1763       * A CyclicBarrier that uses timed await and fails with
1764       * AssertionFailedErrors instead of throwing checked exceptions.
1765       */
1766 <    public class CheckedBarrier extends CyclicBarrier {
1766 >    public static class CheckedBarrier extends CyclicBarrier {
1767          public CheckedBarrier(int parties) { super(parties); }
1768  
1769          public int await() {
# Line 1483 | Line 1869 | public class JSR166TestCase extends Test
1869          } catch (NoSuchElementException success) {}
1870          assertFalse(it.hasNext());
1871      }
1872 +
1873 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1874 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1875 +    }
1876 +
1877 +    public Runnable runnableThrowing(final RuntimeException ex) {
1878 +        return new Runnable() { public void run() { throw ex; }};
1879 +    }
1880 +
1881 +    /** A reusable thread pool to be shared by tests. */
1882 +    static final ExecutorService cachedThreadPool =
1883 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1884 +                               1000L, MILLISECONDS,
1885 +                               new SynchronousQueue<Runnable>());
1886 +
1887 +    static <T> void shuffle(T[] array) {
1888 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1889 +    }
1890   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines