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.100 by jsr166, Wed Feb 6 16:55:50 2013 UTC vs.
Revision 1.185 by jsr166, Mon Feb 22 19:36:59 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 > */
16 >
17 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
18 > import static java.util.concurrent.TimeUnit.MINUTES;
19 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
20 >
21   import java.io.ByteArrayInputStream;
22   import java.io.ByteArrayOutputStream;
23   import java.io.ObjectInputStream;
24   import java.io.ObjectOutputStream;
25   import java.lang.management.ManagementFactory;
26   import java.lang.management.ThreadInfo;
27 + import java.lang.management.ThreadMXBean;
28 + import java.lang.reflect.Constructor;
29   import java.lang.reflect.Method;
30 + import java.lang.reflect.Modifier;
31 + import java.nio.file.Files;
32 + import java.nio.file.Paths;
33 + import java.security.CodeSource;
34 + import java.security.Permission;
35 + import java.security.PermissionCollection;
36 + import java.security.Permissions;
37 + import java.security.Policy;
38 + import java.security.ProtectionDomain;
39 + import java.security.SecurityPermission;
40   import java.util.ArrayList;
41   import java.util.Arrays;
42   import java.util.Date;
43   import java.util.Enumeration;
44 + import java.util.Iterator;
45   import java.util.List;
46   import java.util.NoSuchElementException;
47   import java.util.PropertyPermission;
48 < import java.util.concurrent.*;
48 > import java.util.concurrent.BlockingQueue;
49 > import java.util.concurrent.Callable;
50 > import java.util.concurrent.CountDownLatch;
51 > import java.util.concurrent.CyclicBarrier;
52 > import java.util.concurrent.ExecutionException;
53 > import java.util.concurrent.Executors;
54 > import java.util.concurrent.ExecutorService;
55 > import java.util.concurrent.ForkJoinPool;
56 > import java.util.concurrent.Future;
57 > import java.util.concurrent.RecursiveAction;
58 > import java.util.concurrent.RecursiveTask;
59 > import java.util.concurrent.RejectedExecutionHandler;
60 > import java.util.concurrent.Semaphore;
61 > import java.util.concurrent.ThreadFactory;
62 > import java.util.concurrent.ThreadPoolExecutor;
63 > import java.util.concurrent.TimeoutException;
64   import java.util.concurrent.atomic.AtomicBoolean;
65   import java.util.concurrent.atomic.AtomicReference;
66 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
67 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
68 < import java.security.CodeSource;
69 < import java.security.Permission;
70 < import java.security.PermissionCollection;
71 < import java.security.Permissions;
72 < import java.security.Policy;
73 < import java.security.ProtectionDomain;
35 < import java.security.SecurityPermission;
66 > import java.util.regex.Matcher;
67 > import java.util.regex.Pattern;
68 >
69 > import junit.framework.AssertionFailedError;
70 > import junit.framework.Test;
71 > import junit.framework.TestCase;
72 > import junit.framework.TestResult;
73 > import junit.framework.TestSuite;
74  
75   /**
76   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 44 | Line 82 | import java.security.SecurityPermission;
82   *
83   * <ol>
84   *
85 < * <li> All assertions in code running in generated threads must use
85 > * <li>All assertions in code running in generated threads must use
86   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
87   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
88   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
89   * particularly recommended) for other code to use these forms too.
90   * Only the most typically used JUnit assertion methods are defined
91 < * this way, but enough to live with.</li>
91 > * this way, but enough to live with.
92   *
93 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
93 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
94   * to invoke {@code super.setUp} and {@code super.tearDown} within
95   * them. These methods are used to clear and check for thread
96 < * assertion failures.</li>
96 > * assertion failures.
97   *
98   * <li>All delays and timeouts must use one of the constants {@code
99   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 66 | Line 104 | import java.security.SecurityPermission;
104   * is always discriminable as larger than SHORT and smaller than
105   * MEDIUM.  And so on. These constants are set to conservative values,
106   * but even so, if there is ever any doubt, they can all be increased
107 < * in one spot to rerun tests on slower platforms.</li>
107 > * in one spot to rerun tests on slower platforms.
108   *
109 < * <li> All threads generated must be joined inside each test case
109 > * <li>All threads generated must be joined inside each test case
110   * method (or {@code fail} to do so) before returning from the
111   * method. The {@code joinPool} method can be used to do this when
112 < * using Executors.</li>
112 > * using Executors.
113   *
114   * </ol>
115   *
116   * <p><b>Other notes</b>
117   * <ul>
118   *
119 < * <li> Usually, there is one testcase method per JSR166 method
119 > * <li>Usually, there is one testcase method per JSR166 method
120   * covering "normal" operation, and then as many exception-testing
121   * methods as there are exceptions the method can throw. Sometimes
122   * there are multiple tests per JSR166 method when the different
123   * "normal" behaviors differ significantly. And sometimes testcases
124 < * cover multiple methods when they cannot be tested in
87 < * isolation.</li>
124 > * cover multiple methods when they cannot be tested in isolation.
125   *
126 < * <li> The documentation style for testcases is to provide as javadoc
126 > * <li>The documentation style for testcases is to provide as javadoc
127   * a simple sentence or two describing the property that the testcase
128   * method purports to test. The javadocs do not say anything about how
129 < * the property is tested. To find out, read the code.</li>
129 > * the property is tested. To find out, read the code.
130   *
131 < * <li> These tests are "conformance tests", and do not attempt to
131 > * <li>These tests are "conformance tests", and do not attempt to
132   * test throughput, latency, scalability or other performance factors
133   * (see the separate "jtreg" tests for a set intended to check these
134   * for the most central aspects of functionality.) So, most tests use
135   * the smallest sensible numbers of threads, collection sizes, etc
136 < * needed to check basic conformance.</li>
136 > * needed to check basic conformance.
137   *
138   * <li>The test classes currently do not declare inclusion in
139   * any particular package to simplify things for people integrating
140 < * them in TCK test suites.</li>
140 > * them in TCK test suites.
141   *
142 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
143 < * runs all JSR166 unit tests.</li>
142 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
143 > * runs all JSR166 unit tests.
144   *
145   * </ul>
146   */
# Line 115 | Line 152 | public class JSR166TestCase extends Test
152          Boolean.getBoolean("jsr166.expensiveTests");
153  
154      /**
155 +     * If true, also run tests that are not part of the official tck
156 +     * because they test unspecified implementation details.
157 +     */
158 +    protected static final boolean testImplementationDetails =
159 +        Boolean.getBoolean("jsr166.testImplementationDetails");
160 +
161 +    /**
162       * If true, report on stdout all "slow" tests, that is, ones that
163       * take more than profileThreshold milliseconds to execute.
164       */
# Line 128 | Line 172 | public class JSR166TestCase extends Test
172      private static final long profileThreshold =
173          Long.getLong("jsr166.profileThreshold", 100);
174  
175 +    /**
176 +     * The number of repetitions per test (for tickling rare bugs).
177 +     */
178 +    private static final int runsPerTest =
179 +        Integer.getInteger("jsr166.runsPerTest", 1);
180 +
181 +    /**
182 +     * The number of repetitions of the test suite (for finding leaks?).
183 +     */
184 +    private static final int suiteRuns =
185 +        Integer.getInteger("jsr166.suiteRuns", 1);
186 +
187 +    private static float systemPropertyValue(String name, float defaultValue) {
188 +        String floatString = System.getProperty(name);
189 +        if (floatString == null)
190 +            return defaultValue;
191 +        try {
192 +            return Float.parseFloat(floatString);
193 +        } catch (NumberFormatException ex) {
194 +            throw new IllegalArgumentException(
195 +                String.format("Bad float value in system property %s=%s",
196 +                              name, floatString));
197 +        }
198 +    }
199 +
200 +    /**
201 +     * The scaling factor to apply to standard delays used in tests.
202 +     */
203 +    private static final float delayFactor =
204 +        systemPropertyValue("jsr166.delay.factor", 1.0f);
205 +    
206 +    /**
207 +     * The timeout factor as used in the jtreg test harness.
208 +     * See: http://openjdk.java.net/jtreg/tag-spec.html
209 +     */
210 +    private static final float jtregTestTimeoutFactor
211 +        = systemPropertyValue("test.timeout.factor", 1.0f);
212 +
213 +    public JSR166TestCase() { super(); }
214 +    public JSR166TestCase(String name) { super(name); }
215 +
216 +    /**
217 +     * A filter for tests to run, matching strings of the form
218 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
219 +     * Usefully combined with jsr166.runsPerTest.
220 +     */
221 +    private static final Pattern methodFilter = methodFilter();
222 +
223 +    private static Pattern methodFilter() {
224 +        String regex = System.getProperty("jsr166.methodFilter");
225 +        return (regex == null) ? null : Pattern.compile(regex);
226 +    }
227 +
228 +    // Instrumentation to debug very rare, but very annoying hung test runs.
229 +    static volatile TestCase currentTestCase;
230 +    // static volatile int currentRun = 0;
231 +    static {
232 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
233 +            // Avoid spurious reports with enormous runsPerTest.
234 +            // A single test case run should never take more than 1 second.
235 +            // But let's cap it at the high end too ...
236 +            final int timeoutMinutes =
237 +                Math.min(15, Math.max(runsPerTest / 60, 1));
238 +            for (TestCase lastTestCase = currentTestCase;;) {
239 +                try { MINUTES.sleep(timeoutMinutes); }
240 +                catch (InterruptedException unexpected) { break; }
241 +                if (lastTestCase == currentTestCase) {
242 +                    System.err.printf(
243 +                        "Looks like we're stuck running test: %s%n",
244 +                        lastTestCase);
245 + //                     System.err.printf(
246 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
247 + //                         lastTestCase, currentRun, runsPerTest);
248 + //                     System.err.println("availableProcessors=" +
249 + //                         Runtime.getRuntime().availableProcessors());
250 + //                     System.err.printf("cpu model = %s%n", cpuModel());
251 +                    dumpTestThreads();
252 +                    // one stack dump is probably enough; more would be spam
253 +                    break;
254 +                }
255 +                lastTestCase = currentTestCase;
256 +            }}};
257 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
258 +        thread.setDaemon(true);
259 +        thread.start();
260 +    }
261 +
262 + //     public static String cpuModel() {
263 + //         try {
264 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
265 + //                 .matcher(new String(
266 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
267 + //             matcher.find();
268 + //             return matcher.group(1);
269 + //         } catch (Exception ex) { return null; }
270 + //     }
271 +
272 +    public void runBare() throws Throwable {
273 +        currentTestCase = this;
274 +        if (methodFilter == null
275 +            || methodFilter.matcher(toString()).find())
276 +            super.runBare();
277 +    }
278 +
279      protected void runTest() throws Throwable {
280 <        if (profileTests)
281 <            runTestProfiled();
282 <        else
283 <            super.runTest();
280 >        for (int i = 0; i < runsPerTest; i++) {
281 >            // currentRun = i;
282 >            if (profileTests)
283 >                runTestProfiled();
284 >            else
285 >                super.runTest();
286 >        }
287      }
288  
289      protected void runTestProfiled() throws Throwable {
290 <        long t0 = System.nanoTime();
291 <        try {
290 >        for (int i = 0; i < 2; i++) {
291 >            long startTime = System.nanoTime();
292              super.runTest();
293 <        } finally {
294 <            long elapsedMillis =
295 <                (System.nanoTime() - t0) / (1000L * 1000L);
296 <            if (elapsedMillis >= profileThreshold)
293 >            long elapsedMillis = millisElapsedSince(startTime);
294 >            if (elapsedMillis < profileThreshold)
295 >                break;
296 >            // Never report first run of any test; treat it as a
297 >            // warmup run, notably to trigger all needed classloading,
298 >            if (i > 0)
299                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
300          }
301      }
302  
303      /**
304       * Runs all JSR166 unit tests using junit.textui.TestRunner.
152     * Optional command line arg provides the number of iterations to
153     * repeat running the tests.
305       */
306      public static void main(String[] args) {
307 +        main(suite(), args);
308 +    }
309 +
310 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
311 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
312 +        long runTime;
313 +        public void startTest(Test test) {}
314 +        protected void printHeader(long runTime) {
315 +            this.runTime = runTime; // defer printing for later
316 +        }
317 +        protected void printFooter(TestResult result) {
318 +            if (result.wasSuccessful()) {
319 +                getWriter().println("OK (" + result.runCount() + " tests)"
320 +                    + "  Time: " + elapsedTimeAsString(runTime));
321 +            } else {
322 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
323 +                super.printFooter(result);
324 +            }
325 +        }
326 +    }
327 +
328 +    /**
329 +     * Returns a TestRunner that doesn't bother with unnecessary
330 +     * fluff, like printing a "." for each test case.
331 +     */
332 +    static junit.textui.TestRunner newPithyTestRunner() {
333 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
334 +        runner.setPrinter(new PithyResultPrinter(System.out));
335 +        return runner;
336 +    }
337 +
338 +    /**
339 +     * Runs all unit tests in the given test suite.
340 +     * Actual behavior influenced by jsr166.* system properties.
341 +     */
342 +    static void main(Test suite, String[] args) {
343          if (useSecurityManager) {
344              System.err.println("Setting a permissive security manager");
345              Policy.setPolicy(permissivePolicy());
346              System.setSecurityManager(new SecurityManager());
347          }
348 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
349 <
350 <        Test s = suite();
351 <        for (int i = 0; i < iters; ++i) {
165 <            junit.textui.TestRunner.run(s);
348 >        for (int i = 0; i < suiteRuns; i++) {
349 >            TestResult result = newPithyTestRunner().doRun(suite);
350 >            if (!result.wasSuccessful())
351 >                System.exit(1);
352              System.gc();
353              System.runFinalization();
354          }
169        System.exit(0);
355      }
356  
357      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 197 | Line 382 | public class JSR166TestCase extends Test
382      }
383  
384      public static final double JAVA_CLASS_VERSION;
385 +    public static final String JAVA_SPECIFICATION_VERSION;
386      static {
387          try {
388              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
389                  new java.security.PrivilegedAction<Double>() {
390                  public Double run() {
391                      return Double.valueOf(System.getProperty("java.class.version"));}});
392 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
393 +                new java.security.PrivilegedAction<String>() {
394 +                public String run() {
395 +                    return System.getProperty("java.specification.version");}});
396          } catch (Throwable t) {
397              throw new Error(t);
398          }
# Line 211 | Line 401 | public class JSR166TestCase extends Test
401      public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
402      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
403      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
404 +    public static boolean atLeastJava9() {
405 +        return JAVA_CLASS_VERSION >= 53.0
406 +            // As of 2015-09, java9 still uses 52.0 class file version
407 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
408 +    }
409 +    public static boolean atLeastJava10() {
410 +        return JAVA_CLASS_VERSION >= 54.0
411 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
412 +    }
413  
414      /**
415       * Collects all JSR166 unit tests as one suite.
# Line 286 | Line 485 | public class JSR166TestCase extends Test
485          // Java8+ test classes
486          if (atLeastJava8()) {
487              String[] java8TestClassNames = {
488 <                "StampedLockTest",
488 >                "Atomic8Test",
489 >                "CompletableFutureTest",
490 >                "ConcurrentHashMap8Test",
491 >                "CountedCompleterTest",
492 >                "DoubleAccumulatorTest",
493 >                "DoubleAdderTest",
494                  "ForkJoinPool8Test",
495 +                "ForkJoinTask8Test",
496 +                "LongAccumulatorTest",
497 +                "LongAdderTest",
498 +                "SplittableRandomTest",
499 +                "StampedLockTest",
500 +                "SubmissionPublisherTest",
501 +                "ThreadLocalRandom8Test",
502              };
503              addNamedTestClasses(suite, java8TestClassNames);
504          }
505  
506 +        // Java9+ test classes
507 +        if (atLeastJava9()) {
508 +            String[] java9TestClassNames = {
509 +                // Currently empty, but expecting varhandle tests
510 +            };
511 +            addNamedTestClasses(suite, java9TestClassNames);
512 +        }
513 +
514          return suite;
515      }
516  
517 +    /** Returns list of junit-style test method names in given class. */
518 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
519 +        Method[] methods = testClass.getDeclaredMethods();
520 +        ArrayList<String> names = new ArrayList<String>(methods.length);
521 +        for (Method method : methods) {
522 +            if (method.getName().startsWith("test")
523 +                && Modifier.isPublic(method.getModifiers())
524 +                // method.getParameterCount() requires jdk8+
525 +                && method.getParameterTypes().length == 0) {
526 +                names.add(method.getName());
527 +            }
528 +        }
529 +        return names;
530 +    }
531 +
532 +    /**
533 +     * Returns junit-style testSuite for the given test class, but
534 +     * parameterized by passing extra data to each test.
535 +     */
536 +    public static <ExtraData> Test parameterizedTestSuite
537 +        (Class<? extends JSR166TestCase> testClass,
538 +         Class<ExtraData> dataClass,
539 +         ExtraData data) {
540 +        try {
541 +            TestSuite suite = new TestSuite();
542 +            Constructor c =
543 +                testClass.getDeclaredConstructor(dataClass, String.class);
544 +            for (String methodName : testMethodNames(testClass))
545 +                suite.addTest((Test) c.newInstance(data, methodName));
546 +            return suite;
547 +        } catch (Exception e) {
548 +            throw new Error(e);
549 +        }
550 +    }
551 +
552 +    /**
553 +     * Returns junit-style testSuite for the jdk8 extension of the
554 +     * given test class, but parameterized by passing extra data to
555 +     * each test.  Uses reflection to allow compilation in jdk7.
556 +     */
557 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
558 +        (Class<? extends JSR166TestCase> testClass,
559 +         Class<ExtraData> dataClass,
560 +         ExtraData data) {
561 +        if (atLeastJava8()) {
562 +            String name = testClass.getName();
563 +            String name8 = name.replaceAll("Test$", "8Test");
564 +            if (name.equals(name8)) throw new Error(name);
565 +            try {
566 +                return (Test)
567 +                    Class.forName(name8)
568 +                    .getMethod("testSuite", new Class[] { dataClass })
569 +                    .invoke(null, data);
570 +            } catch (Exception e) {
571 +                throw new Error(e);
572 +            }
573 +        } else {
574 +            return new TestSuite();
575 +        }
576 +    }
577 +
578 +    // Delays for timing-dependent tests, in milliseconds.
579  
580      public static long SHORT_DELAY_MS;
581      public static long SMALL_DELAY_MS;
582      public static long MEDIUM_DELAY_MS;
583      public static long LONG_DELAY_MS;
584  
304
585      /**
586 <     * Returns the shortest timed delay. This could
587 <     * be reimplemented to use for example a Property.
586 >     * Returns the shortest timed delay. This can be scaled up for
587 >     * slow machines using the jsr166.delay.factor system property,
588 >     * or via jtreg's -timeoutFactor:<val> flag.
589 >     * http://openjdk.java.net/jtreg/command-help.html
590       */
591      protected long getShortDelay() {
592 <        return 50;
592 >        return (long) (50 * delayFactor * jtregTestTimeoutFactor);
593      }
594  
595      /**
# Line 329 | Line 611 | public class JSR166TestCase extends Test
611      }
612  
613      /**
614 <     * Returns a new Date instance representing a time delayMillis
615 <     * milliseconds in the future.
614 >     * Returns a new Date instance representing a time at least
615 >     * delayMillis milliseconds in the future.
616       */
617      Date delayedDate(long delayMillis) {
618 <        return new Date(System.currentTimeMillis() + delayMillis);
618 >        // Add 1 because currentTimeMillis is known to round into the past.
619 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
620      }
621  
622      /**
# Line 349 | Line 632 | public class JSR166TestCase extends Test
632       * the same test have no effect.
633       */
634      public void threadRecordFailure(Throwable t) {
635 +        System.err.println(t);
636 +        dumpTestThreads();
637          threadFailure.compareAndSet(null, t);
638      }
639  
# Line 356 | Line 641 | public class JSR166TestCase extends Test
641          setDelays();
642      }
643  
644 +    void tearDownFail(String format, Object... args) {
645 +        String msg = toString() + ": " + String.format(format, args);
646 +        System.err.println(msg);
647 +        dumpTestThreads();
648 +        throw new AssertionFailedError(msg);
649 +    }
650 +
651      /**
652       * Extra checks that get done for all test cases.
653       *
# Line 383 | Line 675 | public class JSR166TestCase extends Test
675          }
676  
677          if (Thread.interrupted())
678 <            throw new AssertionFailedError("interrupt status set in main thread");
678 >            tearDownFail("interrupt status set in main thread");
679  
680          checkForkJoinPoolThreadLeaks();
681      }
682  
683      /**
684 <     * Find missing try { ... } finally { joinPool(e); }
684 >     * Finds missing PoolCleaners
685       */
686      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
687 <        Thread[] survivors = new Thread[5];
687 >        Thread[] survivors = new Thread[7];
688          int count = Thread.enumerate(survivors);
689          for (int i = 0; i < count; i++) {
690              Thread thread = survivors[i];
# Line 400 | Line 692 | public class JSR166TestCase extends Test
692              if (name.startsWith("ForkJoinPool-")) {
693                  // give thread some time to terminate
694                  thread.join(LONG_DELAY_MS);
695 <                if (!thread.isAlive()) continue;
696 <                thread.stop();
697 <                throw new AssertionFailedError
406 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
407 <                                   toString(), name));
695 >                if (thread.isAlive())
696 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
697 >                                 thread);
698              }
699          }
700 +
701 +        if (!ForkJoinPool.commonPool()
702 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
703 +            tearDownFail("ForkJoin common pool thread stuck");
704      }
705 <        
705 >
706      /**
707       * Just like fail(reason), but additionally recording (using
708       * threadRecordFailure) any AssertionFailedError thrown, so that
# Line 419 | Line 713 | public class JSR166TestCase extends Test
713              fail(reason);
714          } catch (AssertionFailedError t) {
715              threadRecordFailure(t);
716 <            fail(reason);
716 >            throw t;
717          }
718      }
719  
# Line 487 | Line 781 | public class JSR166TestCase extends Test
781      public void threadAssertEquals(Object x, Object y) {
782          try {
783              assertEquals(x, y);
784 <        } catch (AssertionFailedError t) {
785 <            threadRecordFailure(t);
786 <            throw t;
787 <        } catch (Throwable t) {
788 <            threadUnexpectedException(t);
784 >        } catch (AssertionFailedError fail) {
785 >            threadRecordFailure(fail);
786 >            throw fail;
787 >        } catch (Throwable fail) {
788 >            threadUnexpectedException(fail);
789          }
790      }
791  
# Line 503 | Line 797 | public class JSR166TestCase extends Test
797      public void threadAssertSame(Object x, Object y) {
798          try {
799              assertSame(x, y);
800 <        } catch (AssertionFailedError t) {
801 <            threadRecordFailure(t);
802 <            throw t;
800 >        } catch (AssertionFailedError fail) {
801 >            threadRecordFailure(fail);
802 >            throw fail;
803          }
804      }
805  
# Line 546 | Line 840 | public class JSR166TestCase extends Test
840      /**
841       * Delays, via Thread.sleep, for the given millisecond delay, but
842       * if the sleep is shorter than specified, may re-sleep or yield
843 <     * until time elapses.
843 >     * until time elapses.  Ensures that the given time, as measured
844 >     * by System.nanoTime(), has elapsed.
845       */
846      static void delay(long millis) throws InterruptedException {
847 <        long startTime = System.nanoTime();
848 <        long ns = millis * 1000 * 1000;
849 <        for (;;) {
847 >        long nanos = millis * (1000 * 1000);
848 >        final long wakeupTime = System.nanoTime() + nanos;
849 >        do {
850              if (millis > 0L)
851                  Thread.sleep(millis);
852              else // too short to sleep
853                  Thread.yield();
854 <            long d = ns - (System.nanoTime() - startTime);
855 <            if (d > 0L)
856 <                millis = d / (1000 * 1000);
857 <            else
858 <                break;
854 >            nanos = wakeupTime - System.nanoTime();
855 >            millis = nanos / (1000 * 1000);
856 >        } while (nanos >= 0L);
857 >    }
858 >
859 >    /**
860 >     * Allows use of try-with-resources with per-test thread pools.
861 >     */
862 >    class PoolCleaner implements AutoCloseable {
863 >        private final ExecutorService pool;
864 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
865 >        public void close() { joinPool(pool); }
866 >    }
867 >
868 >    /**
869 >     * An extension of PoolCleaner that has an action to release the pool.
870 >     */
871 >    class PoolCleanerWithReleaser extends PoolCleaner {
872 >        private final Runnable releaser;
873 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
874 >            super(pool);
875 >            this.releaser = releaser;
876 >        }
877 >        public void close() {
878 >            try {
879 >                releaser.run();
880 >            } finally {
881 >                super.close();
882 >            }
883          }
884      }
885  
886 +    PoolCleaner cleaner(ExecutorService pool) {
887 +        return new PoolCleaner(pool);
888 +    }
889 +
890 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
891 +        return new PoolCleanerWithReleaser(pool, releaser);
892 +    }
893 +
894 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
895 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
896 +    }
897 +
898 +    Runnable releaser(final CountDownLatch latch) {
899 +        return new Runnable() { public void run() {
900 +            do { latch.countDown(); }
901 +            while (latch.getCount() > 0);
902 +        }};
903 +    }
904 +
905 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
906 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
907 +    }
908 +
909 +    Runnable releaser(final AtomicBoolean flag) {
910 +        return new Runnable() { public void run() { flag.set(true); }};
911 +    }
912 +
913      /**
914       * Waits out termination of a thread pool or fails doing so.
915       */
916 <    void joinPool(ExecutorService exec) {
916 >    void joinPool(ExecutorService pool) {
917          try {
918 <            exec.shutdown();
919 <            assertTrue("ExecutorService did not terminate in a timely manner",
920 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
918 >            pool.shutdown();
919 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
920 >                try {
921 >                    threadFail("ExecutorService " + pool +
922 >                               " did not terminate in a timely manner");
923 >                } finally {
924 >                    // last resort, for the benefit of subsequent tests
925 >                    pool.shutdownNow();
926 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
927 >                }
928 >            }
929          } catch (SecurityException ok) {
930              // Allowed in case test doesn't have privs
931 <        } catch (InterruptedException ie) {
932 <            fail("Unexpected InterruptedException");
931 >        } catch (InterruptedException fail) {
932 >            threadFail("Unexpected InterruptedException");
933          }
934      }
935  
936 +    /** Like Runnable, but with the freedom to throw anything */
937 +    interface Action { public void run() throws Throwable; }
938 +
939      /**
940 <     * A debugging tool to print all stack traces, as jstack does.
940 >     * Runs all the given actions in parallel, failing if any fail.
941 >     * Useful for running multiple variants of tests that are
942 >     * necessarily individually slow because they must block.
943       */
944 <    static void printAllStackTraces() {
945 <        for (ThreadInfo info :
946 <                 ManagementFactory.getThreadMXBean()
947 <                 .dumpAllThreads(true, true))
944 >    void testInParallel(Action ... actions) {
945 >        ExecutorService pool = Executors.newCachedThreadPool();
946 >        try (PoolCleaner cleaner = cleaner(pool)) {
947 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
948 >            for (final Action action : actions)
949 >                futures.add(pool.submit(new CheckedRunnable() {
950 >                    public void realRun() throws Throwable { action.run();}}));
951 >            for (Future<?> future : futures)
952 >                try {
953 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
954 >                } catch (ExecutionException ex) {
955 >                    threadUnexpectedException(ex.getCause());
956 >                } catch (Exception ex) {
957 >                    threadUnexpectedException(ex);
958 >                }
959 >        }
960 >    }
961 >
962 >    /**
963 >     * A debugging tool to print stack traces of most threads, as jstack does.
964 >     * Uninteresting threads are filtered out.
965 >     */
966 >    static void dumpTestThreads() {
967 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
968 >        System.err.println("------ stacktrace dump start ------");
969 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
970 >            String name = info.getThreadName();
971 >            if ("Signal Dispatcher".equals(name))
972 >                continue;
973 >            if ("Reference Handler".equals(name)
974 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
975 >                continue;
976 >            if ("Finalizer".equals(name)
977 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
978 >                continue;
979 >            if ("checkForWedgedTest".equals(name))
980 >                continue;
981              System.err.print(info);
982 +        }
983 +        System.err.println("------ stacktrace dump end ------");
984      }
985  
986      /**
# Line 605 | Line 999 | public class JSR166TestCase extends Test
999              // No need to optimize the failing case via Thread.join.
1000              delay(millis);
1001              assertTrue(thread.isAlive());
1002 <        } catch (InterruptedException ie) {
1003 <            fail("Unexpected InterruptedException");
1002 >        } catch (InterruptedException fail) {
1003 >            threadFail("Unexpected InterruptedException");
1004          }
1005      }
1006  
# Line 627 | Line 1021 | public class JSR166TestCase extends Test
1021              delay(millis);
1022              for (Thread thread : threads)
1023                  assertTrue(thread.isAlive());
1024 <        } catch (InterruptedException ie) {
1025 <            fail("Unexpected InterruptedException");
1024 >        } catch (InterruptedException fail) {
1025 >            threadFail("Unexpected InterruptedException");
1026          }
1027      }
1028  
# Line 649 | Line 1043 | public class JSR166TestCase extends Test
1043              future.get(timeoutMillis, MILLISECONDS);
1044              shouldThrow();
1045          } catch (TimeoutException success) {
1046 <        } catch (Exception e) {
1047 <            threadUnexpectedException(e);
1046 >        } catch (Exception fail) {
1047 >            threadUnexpectedException(fail);
1048          } finally { future.cancel(true); }
1049          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1050      }
# Line 694 | Line 1088 | public class JSR166TestCase extends Test
1088      public static final Integer m6  = new Integer(-6);
1089      public static final Integer m10 = new Integer(-10);
1090  
697
1091      /**
1092       * Runs Runnable r with a security policy that permits precisely
1093       * the specified permissions.  If there is no current security
# Line 807 | Line 1200 | public class JSR166TestCase extends Test
1200      void sleep(long millis) {
1201          try {
1202              delay(millis);
1203 <        } catch (InterruptedException ie) {
1203 >        } catch (InterruptedException fail) {
1204              AssertionFailedError afe =
1205                  new AssertionFailedError("Unexpected InterruptedException");
1206 <            afe.initCause(ie);
1206 >            afe.initCause(fail);
1207              throw afe;
1208          }
1209      }
# Line 848 | Line 1241 | public class JSR166TestCase extends Test
1241      /**
1242       * Returns the number of milliseconds since time given by
1243       * startNanoTime, which must have been previously returned from a
1244 <     * call to {@link System.nanoTime()}.
1244 >     * call to {@link System#nanoTime()}.
1245       */
1246 <    long millisElapsedSince(long startNanoTime) {
1246 >    static long millisElapsedSince(long startNanoTime) {
1247          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1248      }
1249  
1250 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1251 + //         long startTime = System.nanoTime();
1252 + //         try {
1253 + //             r.run();
1254 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1255 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1256 + //             throw new AssertionFailedError("did not return promptly");
1257 + //     }
1258 +
1259 + //     void assertTerminatesPromptly(Runnable r) {
1260 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1261 + //     }
1262 +
1263 +    /**
1264 +     * Checks that timed f.get() returns the expected value, and does not
1265 +     * wait for the timeout to elapse before returning.
1266 +     */
1267 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1268 +        long startTime = System.nanoTime();
1269 +        try {
1270 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1271 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1272 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1273 +            throw new AssertionFailedError("timed get did not return promptly");
1274 +    }
1275 +
1276 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1277 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1278 +    }
1279 +
1280      /**
1281       * Returns a new started daemon Thread running the given runnable.
1282       */
# Line 872 | Line 1295 | public class JSR166TestCase extends Test
1295      void awaitTermination(Thread t, long timeoutMillis) {
1296          try {
1297              t.join(timeoutMillis);
1298 <        } catch (InterruptedException ie) {
1299 <            threadUnexpectedException(ie);
1298 >        } catch (InterruptedException fail) {
1299 >            threadUnexpectedException(fail);
1300          } finally {
1301              if (t.getState() != Thread.State.TERMINATED) {
1302                  t.interrupt();
1303 <                fail("Test timed out");
1303 >                threadFail("timed out waiting for thread to terminate");
1304              }
1305          }
1306      }
# Line 899 | Line 1322 | public class JSR166TestCase extends Test
1322          public final void run() {
1323              try {
1324                  realRun();
1325 <            } catch (Throwable t) {
1326 <                threadUnexpectedException(t);
1325 >            } catch (Throwable fail) {
1326 >                threadUnexpectedException(fail);
1327              }
1328          }
1329      }
# Line 954 | Line 1377 | public class JSR166TestCase extends Test
1377                  threadShouldThrow("InterruptedException");
1378              } catch (InterruptedException success) {
1379                  threadAssertFalse(Thread.interrupted());
1380 <            } catch (Throwable t) {
1381 <                threadUnexpectedException(t);
1380 >            } catch (Throwable fail) {
1381 >                threadUnexpectedException(fail);
1382              }
1383          }
1384      }
# Line 966 | Line 1389 | public class JSR166TestCase extends Test
1389          public final T call() {
1390              try {
1391                  return realCall();
1392 <            } catch (Throwable t) {
1393 <                threadUnexpectedException(t);
1392 >            } catch (Throwable fail) {
1393 >                threadUnexpectedException(fail);
1394                  return null;
1395              }
1396          }
# Line 984 | Line 1407 | public class JSR166TestCase extends Test
1407                  return result;
1408              } catch (InterruptedException success) {
1409                  threadAssertFalse(Thread.interrupted());
1410 <            } catch (Throwable t) {
1411 <                threadUnexpectedException(t);
1410 >            } catch (Throwable fail) {
1411 >                threadUnexpectedException(fail);
1412              }
1413              return null;
1414          }
# Line 1002 | Line 1425 | public class JSR166TestCase extends Test
1425      public static final String TEST_STRING = "a test string";
1426  
1427      public static class StringTask implements Callable<String> {
1428 <        public String call() { return TEST_STRING; }
1428 >        final String value;
1429 >        public StringTask() { this(TEST_STRING); }
1430 >        public StringTask(String value) { this.value = value; }
1431 >        public String call() { return value; }
1432      }
1433  
1434      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1015 | Line 1441 | public class JSR166TestCase extends Test
1441              }};
1442      }
1443  
1444 <    public Runnable awaiter(final CountDownLatch latch) {
1444 >    public Runnable countDowner(final CountDownLatch latch) {
1445          return new CheckedRunnable() {
1446              public void realRun() throws InterruptedException {
1447 <                await(latch);
1447 >                latch.countDown();
1448              }};
1449      }
1450  
1451 +    class LatchAwaiter extends CheckedRunnable {
1452 +        static final int NEW = 0;
1453 +        static final int RUNNING = 1;
1454 +        static final int DONE = 2;
1455 +        final CountDownLatch latch;
1456 +        int state = NEW;
1457 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1458 +        public void realRun() throws InterruptedException {
1459 +            state = 1;
1460 +            await(latch);
1461 +            state = 2;
1462 +        }
1463 +    }
1464 +
1465 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1466 +        return new LatchAwaiter(latch);
1467 +    }
1468 +
1469      public void await(CountDownLatch latch) {
1470          try {
1471 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1472 <        } catch (Throwable t) {
1473 <            threadUnexpectedException(t);
1471 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1472 >                fail("timed out waiting for CountDownLatch for "
1473 >                     + (LONG_DELAY_MS/1000) + " sec");
1474 >        } catch (Throwable fail) {
1475 >            threadUnexpectedException(fail);
1476          }
1477      }
1478  
1479      public void await(Semaphore semaphore) {
1480          try {
1481 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1482 <        } catch (Throwable t) {
1483 <            threadUnexpectedException(t);
1481 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1482 >                fail("timed out waiting for Semaphore for "
1483 >                     + (LONG_DELAY_MS/1000) + " sec");
1484 >        } catch (Throwable fail) {
1485 >            threadUnexpectedException(fail);
1486          }
1487      }
1488  
# Line 1225 | Line 1673 | public class JSR166TestCase extends Test
1673      public abstract class CheckedRecursiveAction extends RecursiveAction {
1674          protected abstract void realCompute() throws Throwable;
1675  
1676 <        public final void compute() {
1676 >        @Override protected final void compute() {
1677              try {
1678                  realCompute();
1679 <            } catch (Throwable t) {
1680 <                threadUnexpectedException(t);
1679 >            } catch (Throwable fail) {
1680 >                threadUnexpectedException(fail);
1681              }
1682          }
1683      }
# Line 1240 | Line 1688 | public class JSR166TestCase extends Test
1688      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1689          protected abstract T realCompute() throws Throwable;
1690  
1691 <        public final T compute() {
1691 >        @Override protected final T compute() {
1692              try {
1693                  return realCompute();
1694 <            } catch (Throwable t) {
1695 <                threadUnexpectedException(t);
1694 >            } catch (Throwable fail) {
1695 >                threadUnexpectedException(fail);
1696                  return null;
1697              }
1698          }
# Line 1268 | Line 1716 | public class JSR166TestCase extends Test
1716          public int await() {
1717              try {
1718                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1719 <            } catch (TimeoutException e) {
1719 >            } catch (TimeoutException timedOut) {
1720                  throw new AssertionFailedError("timed out");
1721 <            } catch (Exception e) {
1721 >            } catch (Exception fail) {
1722                  AssertionFailedError afe =
1723 <                    new AssertionFailedError("Unexpected exception: " + e);
1724 <                afe.initCause(e);
1723 >                    new AssertionFailedError("Unexpected exception: " + fail);
1724 >                afe.initCause(fail);
1725                  throw afe;
1726              }
1727          }
# Line 1301 | Line 1749 | public class JSR166TestCase extends Test
1749                  q.remove();
1750                  shouldThrow();
1751              } catch (NoSuchElementException success) {}
1752 <        } catch (InterruptedException ie) {
1305 <            threadUnexpectedException(ie);
1306 <        }
1752 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1753      }
1754  
1755      void assertSerialEquals(Object x, Object y) {
# Line 1322 | Line 1768 | public class JSR166TestCase extends Test
1768              oos.flush();
1769              oos.close();
1770              return bos.toByteArray();
1771 <        } catch (Throwable t) {
1772 <            threadUnexpectedException(t);
1771 >        } catch (Throwable fail) {
1772 >            threadUnexpectedException(fail);
1773              return new byte[0];
1774          }
1775      }
# Line 1336 | Line 1782 | public class JSR166TestCase extends Test
1782              T clone = (T) ois.readObject();
1783              assertSame(o.getClass(), clone.getClass());
1784              return clone;
1785 <        } catch (Throwable t) {
1786 <            threadUnexpectedException(t);
1785 >        } catch (Throwable fail) {
1786 >            threadUnexpectedException(fail);
1787              return null;
1788          }
1789      }
1790 +
1791 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1792 +                             Runnable... throwingActions) {
1793 +        for (Runnable throwingAction : throwingActions) {
1794 +            boolean threw = false;
1795 +            try { throwingAction.run(); }
1796 +            catch (Throwable t) {
1797 +                threw = true;
1798 +                if (!expectedExceptionClass.isInstance(t)) {
1799 +                    AssertionFailedError afe =
1800 +                        new AssertionFailedError
1801 +                        ("Expected " + expectedExceptionClass.getName() +
1802 +                         ", got " + t.getClass().getName());
1803 +                    afe.initCause(t);
1804 +                    threadUnexpectedException(afe);
1805 +                }
1806 +            }
1807 +            if (!threw)
1808 +                shouldThrow(expectedExceptionClass.getName());
1809 +        }
1810 +    }
1811 +
1812 +    public void assertIteratorExhausted(Iterator<?> it) {
1813 +        try {
1814 +            it.next();
1815 +            shouldThrow();
1816 +        } catch (NoSuchElementException success) {}
1817 +        assertFalse(it.hasNext());
1818 +    }
1819   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines