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.83 by jsr166, Fri May 27 19:29:59 2011 UTC vs.
Revision 1.180 by jsr166, Mon Nov 9 05:43:39 2015 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 > import static java.util.concurrent.TimeUnit.MINUTES;
11 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
12 >
13   import java.io.ByteArrayInputStream;
14   import java.io.ByteArrayOutputStream;
15   import java.io.ObjectInputStream;
16   import java.io.ObjectOutputStream;
17 < import java.util.Arrays;
18 < import java.util.Date;
19 < import java.util.NoSuchElementException;
20 < import java.util.PropertyPermission;
21 < import java.util.concurrent.*;
22 < import java.util.concurrent.atomic.AtomicBoolean;
23 < import java.util.concurrent.atomic.AtomicReference;
24 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
17 > import java.lang.management.ManagementFactory;
18 > import java.lang.management.ThreadInfo;
19 > import java.lang.management.ThreadMXBean;
20 > import java.lang.reflect.Constructor;
21 > import java.lang.reflect.Method;
22 > import java.lang.reflect.Modifier;
23 > import java.nio.file.Files;
24 > import java.nio.file.Paths;
25   import java.security.CodeSource;
26   import java.security.Permission;
27   import java.security.PermissionCollection;
# Line 27 | Line 29 | import java.security.Permissions;
29   import java.security.Policy;
30   import java.security.ProtectionDomain;
31   import java.security.SecurityPermission;
32 + import java.util.ArrayList;
33 + import java.util.Arrays;
34 + import java.util.Date;
35 + import java.util.Enumeration;
36 + import java.util.Iterator;
37 + import java.util.List;
38 + import java.util.NoSuchElementException;
39 + import java.util.PropertyPermission;
40 + import java.util.concurrent.BlockingQueue;
41 + import java.util.concurrent.Callable;
42 + import java.util.concurrent.CountDownLatch;
43 + import java.util.concurrent.CyclicBarrier;
44 + import java.util.concurrent.ExecutionException;
45 + import java.util.concurrent.Executors;
46 + import java.util.concurrent.ExecutorService;
47 + import java.util.concurrent.ForkJoinPool;
48 + import java.util.concurrent.Future;
49 + import java.util.concurrent.RecursiveAction;
50 + import java.util.concurrent.RecursiveTask;
51 + import java.util.concurrent.RejectedExecutionHandler;
52 + import java.util.concurrent.Semaphore;
53 + import java.util.concurrent.ThreadFactory;
54 + import java.util.concurrent.ThreadPoolExecutor;
55 + import java.util.concurrent.TimeoutException;
56 + import java.util.concurrent.atomic.AtomicReference;
57 + import java.util.regex.Matcher;
58 + import java.util.regex.Pattern;
59 +
60 + import junit.framework.AssertionFailedError;
61 + import junit.framework.Test;
62 + import junit.framework.TestCase;
63 + import junit.framework.TestResult;
64 + import junit.framework.TestSuite;
65  
66   /**
67   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 38 | Line 73 | import java.security.SecurityPermission;
73   *
74   * <ol>
75   *
76 < * <li> All assertions in code running in generated threads must use
76 > * <li>All assertions in code running in generated threads must use
77   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
78   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
79   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
80   * particularly recommended) for other code to use these forms too.
81   * Only the most typically used JUnit assertion methods are defined
82 < * this way, but enough to live with.</li>
82 > * this way, but enough to live with.
83   *
84 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
84 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
85   * to invoke {@code super.setUp} and {@code super.tearDown} within
86   * them. These methods are used to clear and check for thread
87 < * assertion failures.</li>
87 > * assertion failures.
88   *
89   * <li>All delays and timeouts must use one of the constants {@code
90   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 60 | Line 95 | import java.security.SecurityPermission;
95   * is always discriminable as larger than SHORT and smaller than
96   * MEDIUM.  And so on. These constants are set to conservative values,
97   * but even so, if there is ever any doubt, they can all be increased
98 < * in one spot to rerun tests on slower platforms.</li>
98 > * in one spot to rerun tests on slower platforms.
99   *
100 < * <li> All threads generated must be joined inside each test case
100 > * <li>All threads generated must be joined inside each test case
101   * method (or {@code fail} to do so) before returning from the
102   * method. The {@code joinPool} method can be used to do this when
103 < * using Executors.</li>
103 > * using Executors.
104   *
105   * </ol>
106   *
107 < * <p> <b>Other notes</b>
107 > * <p><b>Other notes</b>
108   * <ul>
109   *
110 < * <li> Usually, there is one testcase method per JSR166 method
110 > * <li>Usually, there is one testcase method per JSR166 method
111   * covering "normal" operation, and then as many exception-testing
112   * methods as there are exceptions the method can throw. Sometimes
113   * there are multiple tests per JSR166 method when the different
114   * "normal" behaviors differ significantly. And sometimes testcases
115 < * cover multiple methods when they cannot be tested in
81 < * isolation.</li>
115 > * cover multiple methods when they cannot be tested in isolation.
116   *
117 < * <li> The documentation style for testcases is to provide as javadoc
117 > * <li>The documentation style for testcases is to provide as javadoc
118   * a simple sentence or two describing the property that the testcase
119   * method purports to test. The javadocs do not say anything about how
120 < * the property is tested. To find out, read the code.</li>
120 > * the property is tested. To find out, read the code.
121   *
122 < * <li> These tests are "conformance tests", and do not attempt to
122 > * <li>These tests are "conformance tests", and do not attempt to
123   * test throughput, latency, scalability or other performance factors
124   * (see the separate "jtreg" tests for a set intended to check these
125   * for the most central aspects of functionality.) So, most tests use
126   * the smallest sensible numbers of threads, collection sizes, etc
127 < * needed to check basic conformance.</li>
127 > * needed to check basic conformance.
128   *
129   * <li>The test classes currently do not declare inclusion in
130   * any particular package to simplify things for people integrating
131 < * them in TCK test suites.</li>
131 > * them in TCK test suites.
132   *
133 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
134 < * runs all JSR166 unit tests.</li>
133 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
134 > * runs all JSR166 unit tests.
135   *
136   * </ul>
137   */
# Line 109 | Line 143 | public class JSR166TestCase extends Test
143          Boolean.getBoolean("jsr166.expensiveTests");
144  
145      /**
146 +     * If true, also run tests that are not part of the official tck
147 +     * because they test unspecified implementation details.
148 +     */
149 +    protected static final boolean testImplementationDetails =
150 +        Boolean.getBoolean("jsr166.testImplementationDetails");
151 +
152 +    /**
153       * If true, report on stdout all "slow" tests, that is, ones that
154       * take more than profileThreshold milliseconds to execute.
155       */
# Line 122 | Line 163 | public class JSR166TestCase extends Test
163      private static final long profileThreshold =
164          Long.getLong("jsr166.profileThreshold", 100);
165  
166 +    /**
167 +     * The number of repetitions per test (for tickling rare bugs).
168 +     */
169 +    private static final int runsPerTest =
170 +        Integer.getInteger("jsr166.runsPerTest", 1);
171 +
172 +    /**
173 +     * The number of repetitions of the test suite (for finding leaks?).
174 +     */
175 +    private static final int suiteRuns =
176 +        Integer.getInteger("jsr166.suiteRuns", 1);
177 +
178 +    public JSR166TestCase() { super(); }
179 +    public JSR166TestCase(String name) { super(name); }
180 +
181 +    /**
182 +     * A filter for tests to run, matching strings of the form
183 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
184 +     * Usefully combined with jsr166.runsPerTest.
185 +     */
186 +    private static final Pattern methodFilter = methodFilter();
187 +
188 +    private static Pattern methodFilter() {
189 +        String regex = System.getProperty("jsr166.methodFilter");
190 +        return (regex == null) ? null : Pattern.compile(regex);
191 +    }
192 +
193 +    // Instrumentation to debug very rare, but very annoying hung test runs.
194 +    static volatile TestCase currentTestCase;
195 +    // static volatile int currentRun = 0;
196 +    static {
197 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
198 +            // Avoid spurious reports with enormous runsPerTest.
199 +            // A single test case run should never take more than 1 second.
200 +            // But let's cap it at the high end too ...
201 +            final int timeoutMinutes =
202 +                Math.min(15, Math.max(runsPerTest / 60, 1));
203 +            for (TestCase lastTestCase = currentTestCase;;) {
204 +                try { MINUTES.sleep(timeoutMinutes); }
205 +                catch (InterruptedException unexpected) { break; }
206 +                if (lastTestCase == currentTestCase) {
207 +                    System.err.printf(
208 +                        "Looks like we're stuck running test: %s%n",
209 +                        lastTestCase);
210 + //                     System.err.printf(
211 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
212 + //                         lastTestCase, currentRun, runsPerTest);
213 + //                     System.err.println("availableProcessors=" +
214 + //                         Runtime.getRuntime().availableProcessors());
215 + //                     System.err.printf("cpu model = %s%n", cpuModel());
216 +                    dumpTestThreads();
217 +                    // one stack dump is probably enough; more would be spam
218 +                    break;
219 +                }
220 +                lastTestCase = currentTestCase;
221 +            }}};
222 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
223 +        thread.setDaemon(true);
224 +        thread.start();
225 +    }
226 +
227 + //     public static String cpuModel() {
228 + //         try {
229 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
230 + //                 .matcher(new String(
231 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
232 + //             matcher.find();
233 + //             return matcher.group(1);
234 + //         } catch (Exception ex) { return null; }
235 + //     }
236 +
237 +    public void runBare() throws Throwable {
238 +        currentTestCase = this;
239 +        if (methodFilter == null
240 +            || methodFilter.matcher(toString()).find())
241 +            super.runBare();
242 +    }
243 +
244      protected void runTest() throws Throwable {
245 <        if (profileTests)
246 <            runTestProfiled();
247 <        else
248 <            super.runTest();
245 >        for (int i = 0; i < runsPerTest; i++) {
246 >            // currentRun = i;
247 >            if (profileTests)
248 >                runTestProfiled();
249 >            else
250 >                super.runTest();
251 >        }
252      }
253  
254      protected void runTestProfiled() throws Throwable {
255 <        long t0 = System.nanoTime();
256 <        try {
255 >        for (int i = 0; i < 2; i++) {
256 >            long startTime = System.nanoTime();
257              super.runTest();
258 <        } finally {
259 <            long elapsedMillis =
260 <                (System.nanoTime() - t0) / (1000L * 1000L);
261 <            if (elapsedMillis >= profileThreshold)
258 >            long elapsedMillis = millisElapsedSince(startTime);
259 >            if (elapsedMillis < profileThreshold)
260 >                break;
261 >            // Never report first run of any test; treat it as a
262 >            // warmup run, notably to trigger all needed classloading,
263 >            if (i > 0)
264                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
265          }
266      }
267  
268      /**
269 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
269 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
270       */
271      public static void main(String[] args) {
272 +        main(suite(), args);
273 +    }
274 +
275 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
276 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
277 +        long runTime;
278 +        public void startTest(Test test) {}
279 +        protected void printHeader(long runTime) {
280 +            this.runTime = runTime; // defer printing for later
281 +        }
282 +        protected void printFooter(TestResult result) {
283 +            if (result.wasSuccessful()) {
284 +                getWriter().println("OK (" + result.runCount() + " tests)"
285 +                    + "  Time: " + elapsedTimeAsString(runTime));
286 +            } else {
287 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
288 +                super.printFooter(result);
289 +            }
290 +        }
291 +    }
292 +
293 +    /**
294 +     * Returns a TestRunner that doesn't bother with unnecessary
295 +     * fluff, like printing a "." for each test case.
296 +     */
297 +    static junit.textui.TestRunner newPithyTestRunner() {
298 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
299 +        runner.setPrinter(new PithyResultPrinter(System.out));
300 +        return runner;
301 +    }
302 +
303 +    /**
304 +     * Runs all unit tests in the given test suite.
305 +     * Actual behavior influenced by jsr166.* system properties.
306 +     */
307 +    static void main(Test suite, String[] args) {
308          if (useSecurityManager) {
309              System.err.println("Setting a permissive security manager");
310              Policy.setPolicy(permissivePolicy());
311              System.setSecurityManager(new SecurityManager());
312          }
313 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
314 <
315 <        Test s = suite();
316 <        for (int i = 0; i < iters; ++i) {
157 <            junit.textui.TestRunner.run(s);
313 >        for (int i = 0; i < suiteRuns; i++) {
314 >            TestResult result = newPithyTestRunner().doRun(suite);
315 >            if (!result.wasSuccessful())
316 >                System.exit(1);
317              System.gc();
318              System.runFinalization();
319          }
161        System.exit(0);
320      }
321  
322      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 174 | Line 332 | public class JSR166TestCase extends Test
332          return suite;
333      }
334  
335 +    public static void addNamedTestClasses(TestSuite suite,
336 +                                           String... testClassNames) {
337 +        for (String testClassName : testClassNames) {
338 +            try {
339 +                Class<?> testClass = Class.forName(testClassName);
340 +                Method m = testClass.getDeclaredMethod("suite",
341 +                                                       new Class<?>[0]);
342 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
343 +            } catch (Exception e) {
344 +                throw new Error("Missing test class", e);
345 +            }
346 +        }
347 +    }
348 +
349 +    public static final double JAVA_CLASS_VERSION;
350 +    public static final String JAVA_SPECIFICATION_VERSION;
351 +    static {
352 +        try {
353 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
354 +                new java.security.PrivilegedAction<Double>() {
355 +                public Double run() {
356 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
357 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
358 +                new java.security.PrivilegedAction<String>() {
359 +                public String run() {
360 +                    return System.getProperty("java.specification.version");}});
361 +        } catch (Throwable t) {
362 +            throw new Error(t);
363 +        }
364 +    }
365 +
366 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
367 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
368 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
369 +    public static boolean atLeastJava9() {
370 +        return JAVA_CLASS_VERSION >= 53.0
371 +            // As of 2015-09, java9 still uses 52.0 class file version
372 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
373 +    }
374 +    public static boolean atLeastJava10() {
375 +        return JAVA_CLASS_VERSION >= 54.0
376 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
377 +    }
378 +
379      /**
380       * Collects all JSR166 unit tests as one suite.
381       */
382      public static Test suite() {
383 <        return newTestSuite(
383 >        // Java7+ test classes
384 >        TestSuite suite = newTestSuite(
385              ForkJoinPoolTest.suite(),
386              ForkJoinTaskTest.suite(),
387              RecursiveActionTest.suite(),
# Line 243 | Line 446 | public class JSR166TestCase extends Test
446              TreeSetTest.suite(),
447              TreeSubMapTest.suite(),
448              TreeSubSetTest.suite());
449 +
450 +        // Java8+ test classes
451 +        if (atLeastJava8()) {
452 +            String[] java8TestClassNames = {
453 +                "Atomic8Test",
454 +                "CompletableFutureTest",
455 +                "ConcurrentHashMap8Test",
456 +                "CountedCompleterTest",
457 +                "DoubleAccumulatorTest",
458 +                "DoubleAdderTest",
459 +                "ForkJoinPool8Test",
460 +                "ForkJoinTask8Test",
461 +                "LongAccumulatorTest",
462 +                "LongAdderTest",
463 +                "SplittableRandomTest",
464 +                "StampedLockTest",
465 +                "SubmissionPublisherTest",
466 +                "ThreadLocalRandom8Test",
467 +            };
468 +            addNamedTestClasses(suite, java8TestClassNames);
469 +        }
470 +
471 +        // Java9+ test classes
472 +        if (atLeastJava9()) {
473 +            String[] java9TestClassNames = {
474 +                // Currently empty, but expecting varhandle tests
475 +            };
476 +            addNamedTestClasses(suite, java9TestClassNames);
477 +        }
478 +
479 +        return suite;
480 +    }
481 +
482 +    /** Returns list of junit-style test method names in given class. */
483 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
484 +        Method[] methods = testClass.getDeclaredMethods();
485 +        ArrayList<String> names = new ArrayList<String>(methods.length);
486 +        for (Method method : methods) {
487 +            if (method.getName().startsWith("test")
488 +                && Modifier.isPublic(method.getModifiers())
489 +                // method.getParameterCount() requires jdk8+
490 +                && method.getParameterTypes().length == 0) {
491 +                names.add(method.getName());
492 +            }
493 +        }
494 +        return names;
495 +    }
496 +
497 +    /**
498 +     * Returns junit-style testSuite for the given test class, but
499 +     * parameterized by passing extra data to each test.
500 +     */
501 +    public static <ExtraData> Test parameterizedTestSuite
502 +        (Class<? extends JSR166TestCase> testClass,
503 +         Class<ExtraData> dataClass,
504 +         ExtraData data) {
505 +        try {
506 +            TestSuite suite = new TestSuite();
507 +            Constructor c =
508 +                testClass.getDeclaredConstructor(dataClass, String.class);
509 +            for (String methodName : testMethodNames(testClass))
510 +                suite.addTest((Test) c.newInstance(data, methodName));
511 +            return suite;
512 +        } catch (Exception e) {
513 +            throw new Error(e);
514 +        }
515 +    }
516 +
517 +    /**
518 +     * Returns junit-style testSuite for the jdk8 extension of the
519 +     * given test class, but parameterized by passing extra data to
520 +     * each test.  Uses reflection to allow compilation in jdk7.
521 +     */
522 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
523 +        (Class<? extends JSR166TestCase> testClass,
524 +         Class<ExtraData> dataClass,
525 +         ExtraData data) {
526 +        if (atLeastJava8()) {
527 +            String name = testClass.getName();
528 +            String name8 = name.replaceAll("Test$", "8Test");
529 +            if (name.equals(name8)) throw new Error(name);
530 +            try {
531 +                return (Test)
532 +                    Class.forName(name8)
533 +                    .getMethod("testSuite", new Class[] { dataClass })
534 +                    .invoke(null, data);
535 +            } catch (Exception e) {
536 +                throw new Error(e);
537 +            }
538 +        } else {
539 +            return new TestSuite();
540 +        }
541      }
542  
543 +    // Delays for timing-dependent tests, in milliseconds.
544  
545      public static long SHORT_DELAY_MS;
546      public static long SMALL_DELAY_MS;
547      public static long MEDIUM_DELAY_MS;
548      public static long LONG_DELAY_MS;
549  
254
550      /**
551       * Returns the shortest timed delay. This could
552       * be reimplemented to use for example a Property.
# Line 279 | Line 574 | public class JSR166TestCase extends Test
574      }
575  
576      /**
577 <     * Returns a new Date instance representing a time delayMillis
578 <     * milliseconds in the future.
577 >     * Returns a new Date instance representing a time at least
578 >     * delayMillis milliseconds in the future.
579       */
580      Date delayedDate(long delayMillis) {
581 <        return new Date(new Date().getTime() + delayMillis);
581 >        // Add 1 because currentTimeMillis is known to round into the past.
582 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
583      }
584  
585      /**
# Line 299 | Line 595 | public class JSR166TestCase extends Test
595       * the same test have no effect.
596       */
597      public void threadRecordFailure(Throwable t) {
598 +        System.err.println(t);
599 +        dumpTestThreads();
600          threadFailure.compareAndSet(null, t);
601      }
602  
# Line 306 | Line 604 | public class JSR166TestCase extends Test
604          setDelays();
605      }
606  
607 +    void tearDownFail(String format, Object... args) {
608 +        String msg = toString() + ": " + String.format(format, args);
609 +        System.err.println(msg);
610 +        dumpTestThreads();
611 +        throw new AssertionFailedError(msg);
612 +    }
613 +
614      /**
615 +     * Extra checks that get done for all test cases.
616 +     *
617       * Triggers test case failure if any thread assertions have failed,
618       * by rethrowing, in the test harness thread, any exception recorded
619       * earlier by threadRecordFailure.
620 +     *
621 +     * Triggers test case failure if interrupt status is set in the main thread.
622       */
623      public void tearDown() throws Exception {
624          Throwable t = threadFailure.getAndSet(null);
# Line 327 | Line 636 | public class JSR166TestCase extends Test
636                  throw afe;
637              }
638          }
639 +
640 +        if (Thread.interrupted())
641 +            tearDownFail("interrupt status set in main thread");
642 +
643 +        checkForkJoinPoolThreadLeaks();
644 +    }
645 +
646 +    /**
647 +     * Finds missing PoolCleaners
648 +     */
649 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
650 +        Thread[] survivors = new Thread[7];
651 +        int count = Thread.enumerate(survivors);
652 +        for (int i = 0; i < count; i++) {
653 +            Thread thread = survivors[i];
654 +            String name = thread.getName();
655 +            if (name.startsWith("ForkJoinPool-")) {
656 +                // give thread some time to terminate
657 +                thread.join(LONG_DELAY_MS);
658 +                if (thread.isAlive())
659 +                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
660 +                                 thread);
661 +            }
662 +        }
663 +
664 +        if (!ForkJoinPool.commonPool()
665 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
666 +            tearDownFail("ForkJoin common pool thread stuck");
667      }
668  
669      /**
# Line 339 | Line 676 | public class JSR166TestCase extends Test
676              fail(reason);
677          } catch (AssertionFailedError t) {
678              threadRecordFailure(t);
679 <            fail(reason);
679 >            throw t;
680          }
681      }
682  
# Line 407 | Line 744 | public class JSR166TestCase extends Test
744      public void threadAssertEquals(Object x, Object y) {
745          try {
746              assertEquals(x, y);
747 <        } catch (AssertionFailedError t) {
748 <            threadRecordFailure(t);
749 <            throw t;
750 <        } catch (Throwable t) {
751 <            threadUnexpectedException(t);
747 >        } catch (AssertionFailedError fail) {
748 >            threadRecordFailure(fail);
749 >            throw fail;
750 >        } catch (Throwable fail) {
751 >            threadUnexpectedException(fail);
752          }
753      }
754  
# Line 423 | Line 760 | public class JSR166TestCase extends Test
760      public void threadAssertSame(Object x, Object y) {
761          try {
762              assertSame(x, y);
763 <        } catch (AssertionFailedError t) {
764 <            threadRecordFailure(t);
765 <            throw t;
763 >        } catch (AssertionFailedError fail) {
764 >            threadRecordFailure(fail);
765 >            throw fail;
766          }
767      }
768  
# Line 466 | Line 803 | public class JSR166TestCase extends Test
803      /**
804       * Delays, via Thread.sleep, for the given millisecond delay, but
805       * if the sleep is shorter than specified, may re-sleep or yield
806 <     * until time elapses.
806 >     * until time elapses.  Ensures that the given time, as measured
807 >     * by System.nanoTime(), has elapsed.
808       */
809      static void delay(long millis) throws InterruptedException {
810 <        long startTime = System.nanoTime();
811 <        long ns = millis * 1000 * 1000;
812 <        for (;;) {
810 >        long nanos = millis * (1000 * 1000);
811 >        final long wakeupTime = System.nanoTime() + nanos;
812 >        do {
813              if (millis > 0L)
814                  Thread.sleep(millis);
815              else // too short to sleep
816                  Thread.yield();
817 <            long d = ns - (System.nanoTime() - startTime);
818 <            if (d > 0L)
819 <                millis = d / (1000 * 1000);
820 <            else
821 <                break;
817 >            nanos = wakeupTime - System.nanoTime();
818 >            millis = nanos / (1000 * 1000);
819 >        } while (nanos >= 0L);
820 >    }
821 >
822 >    /**
823 >     * Allows use of try-with-resources with per-test thread pools.
824 >     */
825 >    class PoolCleaner implements AutoCloseable {
826 >        private final ExecutorService pool;
827 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
828 >        public void close() { joinPool(pool); }
829 >    }
830 >
831 >    /**
832 >     * An extension of PoolCleaner that has an action to release the pool.
833 >     */
834 >    class PoolCleanerWithReleaser extends PoolCleaner {
835 >        private final Runnable releaser;
836 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
837 >            super(pool);
838 >            this.releaser = releaser;
839 >        }
840 >        public void close() {
841 >            try {
842 >                releaser.run();
843 >            } finally {
844 >                super.close();
845 >            }
846          }
847      }
848  
849 +    PoolCleaner cleaner(ExecutorService pool) {
850 +        return new PoolCleaner(pool);
851 +    }
852 +
853 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
854 +        return new PoolCleanerWithReleaser(pool, releaser);
855 +    }
856 +
857 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
858 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
859 +    }
860 +
861 +    Runnable releaser(final CountDownLatch latch) {
862 +        return new Runnable() { public void run() {
863 +            do { latch.countDown(); }
864 +            while (latch.getCount() > 0);
865 +        }};
866 +    }
867 +
868      /**
869       * Waits out termination of a thread pool or fails doing so.
870       */
871 <    void joinPool(ExecutorService exec) {
871 >    void joinPool(ExecutorService pool) {
872          try {
873 <            exec.shutdown();
874 <            assertTrue("ExecutorService did not terminate in a timely manner",
875 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
873 >            pool.shutdown();
874 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
875 >                try {
876 >                    threadFail("ExecutorService " + pool +
877 >                               " did not terminate in a timely manner");
878 >                } finally {
879 >                    // last resort, for the benefit of subsequent tests
880 >                    pool.shutdownNow();
881 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
882 >                }
883 >            }
884          } catch (SecurityException ok) {
885              // Allowed in case test doesn't have privs
886 <        } catch (InterruptedException ie) {
887 <            fail("Unexpected InterruptedException");
886 >        } catch (InterruptedException fail) {
887 >            threadFail("Unexpected InterruptedException");
888 >        }
889 >    }
890 >
891 >    /** Like Runnable, but with the freedom to throw anything */
892 >    interface Action { public void run() throws Throwable; }
893 >
894 >    /**
895 >     * Runs all the given actions in parallel, failing if any fail.
896 >     * Useful for running multiple variants of tests that are
897 >     * necessarily individually slow because they must block.
898 >     */
899 >    void testInParallel(Action ... actions) {
900 >        ExecutorService pool = Executors.newCachedThreadPool();
901 >        try (PoolCleaner cleaner = cleaner(pool)) {
902 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
903 >            for (final Action action : actions)
904 >                futures.add(pool.submit(new CheckedRunnable() {
905 >                    public void realRun() throws Throwable { action.run();}}));
906 >            for (Future<?> future : futures)
907 >                try {
908 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
909 >                } catch (ExecutionException ex) {
910 >                    threadUnexpectedException(ex.getCause());
911 >                } catch (Exception ex) {
912 >                    threadUnexpectedException(ex);
913 >                }
914 >        }
915 >    }
916 >
917 >    /**
918 >     * A debugging tool to print stack traces of most threads, as jstack does.
919 >     * Uninteresting threads are filtered out.
920 >     */
921 >    static void dumpTestThreads() {
922 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
923 >        System.err.println("------ stacktrace dump start ------");
924 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
925 >            String name = info.getThreadName();
926 >            if ("Signal Dispatcher".equals(name))
927 >                continue;
928 >            if ("Reference Handler".equals(name)
929 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
930 >                continue;
931 >            if ("Finalizer".equals(name)
932 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
933 >                continue;
934 >            if ("checkForWedgedTest".equals(name))
935 >                continue;
936 >            System.err.print(info);
937          }
938 +        System.err.println("------ stacktrace dump end ------");
939      }
940  
941      /**
# Line 515 | Line 954 | public class JSR166TestCase extends Test
954              // No need to optimize the failing case via Thread.join.
955              delay(millis);
956              assertTrue(thread.isAlive());
957 <        } catch (InterruptedException ie) {
958 <            fail("Unexpected InterruptedException");
957 >        } catch (InterruptedException fail) {
958 >            threadFail("Unexpected InterruptedException");
959 >        }
960 >    }
961 >
962 >    /**
963 >     * Checks that the threads do not terminate within the default
964 >     * millisecond delay of {@code timeoutMillis()}.
965 >     */
966 >    void assertThreadsStayAlive(Thread... threads) {
967 >        assertThreadsStayAlive(timeoutMillis(), threads);
968 >    }
969 >
970 >    /**
971 >     * Checks that the threads do not terminate within the given millisecond delay.
972 >     */
973 >    void assertThreadsStayAlive(long millis, Thread... threads) {
974 >        try {
975 >            // No need to optimize the failing case via Thread.join.
976 >            delay(millis);
977 >            for (Thread thread : threads)
978 >                assertTrue(thread.isAlive());
979 >        } catch (InterruptedException fail) {
980 >            threadFail("Unexpected InterruptedException");
981          }
982      }
983  
# Line 537 | Line 998 | public class JSR166TestCase extends Test
998              future.get(timeoutMillis, MILLISECONDS);
999              shouldThrow();
1000          } catch (TimeoutException success) {
1001 <        } catch (Exception e) {
1002 <            threadUnexpectedException(e);
1001 >        } catch (Exception fail) {
1002 >            threadUnexpectedException(fail);
1003          } finally { future.cancel(true); }
1004          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1005      }
# Line 582 | Line 1043 | public class JSR166TestCase extends Test
1043      public static final Integer m6  = new Integer(-6);
1044      public static final Integer m10 = new Integer(-10);
1045  
585
1046      /**
1047       * Runs Runnable r with a security policy that permits precisely
1048       * the specified permissions.  If there is no current security
# Line 594 | Line 1054 | public class JSR166TestCase extends Test
1054          SecurityManager sm = System.getSecurityManager();
1055          if (sm == null) {
1056              r.run();
1057 +        }
1058 +        runWithSecurityManagerWithPermissions(r, permissions);
1059 +    }
1060 +
1061 +    /**
1062 +     * Runs Runnable r with a security policy that permits precisely
1063 +     * the specified permissions.  If there is no current security
1064 +     * manager, a temporary one is set for the duration of the
1065 +     * Runnable.  We require that any security manager permit
1066 +     * getPolicy/setPolicy.
1067 +     */
1068 +    public void runWithSecurityManagerWithPermissions(Runnable r,
1069 +                                                      Permission... permissions) {
1070 +        SecurityManager sm = System.getSecurityManager();
1071 +        if (sm == null) {
1072              Policy savedPolicy = Policy.getPolicy();
1073              try {
1074                  Policy.setPolicy(permissivePolicy());
1075                  System.setSecurityManager(new SecurityManager());
1076 <                runWithPermissions(r, permissions);
1076 >                runWithSecurityManagerWithPermissions(r, permissions);
1077              } finally {
1078                  System.setSecurityManager(null);
1079                  Policy.setPolicy(savedPolicy);
# Line 646 | Line 1121 | public class JSR166TestCase extends Test
1121              return perms.implies(p);
1122          }
1123          public void refresh() {}
1124 +        public String toString() {
1125 +            List<Permission> ps = new ArrayList<Permission>();
1126 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1127 +                ps.add(e.nextElement());
1128 +            return "AdjustablePolicy with permissions " + ps;
1129 +        }
1130      }
1131  
1132      /**
# Line 674 | Line 1155 | public class JSR166TestCase extends Test
1155      void sleep(long millis) {
1156          try {
1157              delay(millis);
1158 <        } catch (InterruptedException ie) {
1158 >        } catch (InterruptedException fail) {
1159              AssertionFailedError afe =
1160                  new AssertionFailedError("Unexpected InterruptedException");
1161 <            afe.initCause(ie);
1161 >            afe.initCause(fail);
1162              throw afe;
1163          }
1164      }
1165  
1166      /**
1167 <     * Waits up to the specified number of milliseconds for the given
1167 >     * Spin-waits up to the specified number of milliseconds for the given
1168       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1169       */
1170      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1171 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
691 <        long t0 = System.nanoTime();
1171 >        long startTime = System.nanoTime();
1172          for (;;) {
1173              Thread.State s = thread.getState();
1174              if (s == Thread.State.BLOCKED ||
# Line 697 | Line 1177 | public class JSR166TestCase extends Test
1177                  return;
1178              else if (s == Thread.State.TERMINATED)
1179                  fail("Unexpected thread termination");
1180 <            else if (System.nanoTime() - t0 > timeoutNanos) {
1180 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1181                  threadAssertTrue(thread.isAlive());
1182                  return;
1183              }
# Line 716 | Line 1196 | public class JSR166TestCase extends Test
1196      /**
1197       * Returns the number of milliseconds since time given by
1198       * startNanoTime, which must have been previously returned from a
1199 <     * call to {@link System.nanoTime()}.
1199 >     * call to {@link System#nanoTime()}.
1200       */
1201 <    long millisElapsedSince(long startNanoTime) {
1201 >    static long millisElapsedSince(long startNanoTime) {
1202          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1203      }
1204  
1205 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1206 + //         long startTime = System.nanoTime();
1207 + //         try {
1208 + //             r.run();
1209 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1210 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1211 + //             throw new AssertionFailedError("did not return promptly");
1212 + //     }
1213 +
1214 + //     void assertTerminatesPromptly(Runnable r) {
1215 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1216 + //     }
1217 +
1218 +    /**
1219 +     * Checks that timed f.get() returns the expected value, and does not
1220 +     * wait for the timeout to elapse before returning.
1221 +     */
1222 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1223 +        long startTime = System.nanoTime();
1224 +        try {
1225 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1226 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1227 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1228 +            throw new AssertionFailedError("timed get did not return promptly");
1229 +    }
1230 +
1231 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1232 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1233 +    }
1234 +
1235      /**
1236       * Returns a new started daemon Thread running the given runnable.
1237       */
# Line 740 | Line 1250 | public class JSR166TestCase extends Test
1250      void awaitTermination(Thread t, long timeoutMillis) {
1251          try {
1252              t.join(timeoutMillis);
1253 <        } catch (InterruptedException ie) {
1254 <            threadUnexpectedException(ie);
1253 >        } catch (InterruptedException fail) {
1254 >            threadUnexpectedException(fail);
1255          } finally {
1256              if (t.getState() != Thread.State.TERMINATED) {
1257                  t.interrupt();
1258 <                fail("Test timed out");
1258 >                threadFail("timed out waiting for thread to terminate");
1259              }
1260          }
1261      }
# Line 767 | Line 1277 | public class JSR166TestCase extends Test
1277          public final void run() {
1278              try {
1279                  realRun();
1280 <            } catch (Throwable t) {
1281 <                threadUnexpectedException(t);
1280 >            } catch (Throwable fail) {
1281 >                threadUnexpectedException(fail);
1282              }
1283          }
1284      }
# Line 822 | Line 1332 | public class JSR166TestCase extends Test
1332                  threadShouldThrow("InterruptedException");
1333              } catch (InterruptedException success) {
1334                  threadAssertFalse(Thread.interrupted());
1335 <            } catch (Throwable t) {
1336 <                threadUnexpectedException(t);
1335 >            } catch (Throwable fail) {
1336 >                threadUnexpectedException(fail);
1337              }
1338          }
1339      }
# Line 834 | Line 1344 | public class JSR166TestCase extends Test
1344          public final T call() {
1345              try {
1346                  return realCall();
1347 <            } catch (Throwable t) {
1348 <                threadUnexpectedException(t);
1347 >            } catch (Throwable fail) {
1348 >                threadUnexpectedException(fail);
1349                  return null;
1350              }
1351          }
# Line 852 | Line 1362 | public class JSR166TestCase extends Test
1362                  return result;
1363              } catch (InterruptedException success) {
1364                  threadAssertFalse(Thread.interrupted());
1365 <            } catch (Throwable t) {
1366 <                threadUnexpectedException(t);
1365 >            } catch (Throwable fail) {
1366 >                threadUnexpectedException(fail);
1367              }
1368              return null;
1369          }
# Line 870 | Line 1380 | public class JSR166TestCase extends Test
1380      public static final String TEST_STRING = "a test string";
1381  
1382      public static class StringTask implements Callable<String> {
1383 <        public String call() { return TEST_STRING; }
1383 >        final String value;
1384 >        public StringTask() { this(TEST_STRING); }
1385 >        public StringTask(String value) { this.value = value; }
1386 >        public String call() { return value; }
1387      }
1388  
1389      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 883 | Line 1396 | public class JSR166TestCase extends Test
1396              }};
1397      }
1398  
1399 <    public Runnable awaiter(final CountDownLatch latch) {
1399 >    public Runnable countDowner(final CountDownLatch latch) {
1400          return new CheckedRunnable() {
1401              public void realRun() throws InterruptedException {
1402 <                await(latch);
1402 >                latch.countDown();
1403              }};
1404      }
1405  
1406 +    class LatchAwaiter extends CheckedRunnable {
1407 +        static final int NEW = 0;
1408 +        static final int RUNNING = 1;
1409 +        static final int DONE = 2;
1410 +        final CountDownLatch latch;
1411 +        int state = NEW;
1412 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1413 +        public void realRun() throws InterruptedException {
1414 +            state = 1;
1415 +            await(latch);
1416 +            state = 2;
1417 +        }
1418 +    }
1419 +
1420 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1421 +        return new LatchAwaiter(latch);
1422 +    }
1423 +
1424      public void await(CountDownLatch latch) {
1425          try {
1426 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1427 <        } catch (Throwable t) {
1428 <            threadUnexpectedException(t);
1426 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1427 >                fail("timed out waiting for CountDownLatch for "
1428 >                     + (LONG_DELAY_MS/1000) + " sec");
1429 >        } catch (Throwable fail) {
1430 >            threadUnexpectedException(fail);
1431 >        }
1432 >    }
1433 >
1434 >    public void await(Semaphore semaphore) {
1435 >        try {
1436 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1437 >                fail("timed out waiting for Semaphore for "
1438 >                     + (LONG_DELAY_MS/1000) + " sec");
1439 >        } catch (Throwable fail) {
1440 >            threadUnexpectedException(fail);
1441          }
1442      }
1443  
# Line 1085 | Line 1628 | public class JSR166TestCase extends Test
1628      public abstract class CheckedRecursiveAction extends RecursiveAction {
1629          protected abstract void realCompute() throws Throwable;
1630  
1631 <        public final void compute() {
1631 >        @Override protected final void compute() {
1632              try {
1633                  realCompute();
1634 <            } catch (Throwable t) {
1635 <                threadUnexpectedException(t);
1634 >            } catch (Throwable fail) {
1635 >                threadUnexpectedException(fail);
1636              }
1637          }
1638      }
# Line 1100 | Line 1643 | public class JSR166TestCase extends Test
1643      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1644          protected abstract T realCompute() throws Throwable;
1645  
1646 <        public final T compute() {
1646 >        @Override protected final T compute() {
1647              try {
1648                  return realCompute();
1649 <            } catch (Throwable t) {
1650 <                threadUnexpectedException(t);
1649 >            } catch (Throwable fail) {
1650 >                threadUnexpectedException(fail);
1651                  return null;
1652              }
1653          }
# Line 1119 | Line 1662 | public class JSR166TestCase extends Test
1662      }
1663  
1664      /**
1665 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1666 <     * of throwing checked exceptions.
1665 >     * A CyclicBarrier that uses timed await and fails with
1666 >     * AssertionFailedErrors instead of throwing checked exceptions.
1667       */
1668      public class CheckedBarrier extends CyclicBarrier {
1669          public CheckedBarrier(int parties) { super(parties); }
1670  
1671          public int await() {
1672              try {
1673 <                return super.await();
1674 <            } catch (Exception e) {
1673 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1674 >            } catch (TimeoutException timedOut) {
1675 >                throw new AssertionFailedError("timed out");
1676 >            } catch (Exception fail) {
1677                  AssertionFailedError afe =
1678 <                    new AssertionFailedError("Unexpected exception: " + e);
1679 <                afe.initCause(e);
1678 >                    new AssertionFailedError("Unexpected exception: " + fail);
1679 >                afe.initCause(fail);
1680                  throw afe;
1681              }
1682          }
# Line 1159 | Line 1704 | public class JSR166TestCase extends Test
1704                  q.remove();
1705                  shouldThrow();
1706              } catch (NoSuchElementException success) {}
1707 <        } catch (InterruptedException ie) {
1163 <            threadUnexpectedException(ie);
1164 <        }
1707 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1708      }
1709  
1710 <    @SuppressWarnings("unchecked")
1711 <    <T> T serialClone(T o) {
1710 >    void assertSerialEquals(Object x, Object y) {
1711 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1712 >    }
1713 >
1714 >    void assertNotSerialEquals(Object x, Object y) {
1715 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1716 >    }
1717 >
1718 >    byte[] serialBytes(Object o) {
1719          try {
1720              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1721              ObjectOutputStream oos = new ObjectOutputStream(bos);
1722              oos.writeObject(o);
1723              oos.flush();
1724              oos.close();
1725 <            ByteArrayInputStream bin =
1726 <                new ByteArrayInputStream(bos.toByteArray());
1727 <            ObjectInputStream ois = new ObjectInputStream(bin);
1728 <            return (T) ois.readObject();
1729 <        } catch (Throwable t) {
1730 <            threadUnexpectedException(t);
1725 >            return bos.toByteArray();
1726 >        } catch (Throwable fail) {
1727 >            threadUnexpectedException(fail);
1728 >            return new byte[0];
1729 >        }
1730 >    }
1731 >
1732 >    @SuppressWarnings("unchecked")
1733 >    <T> T serialClone(T o) {
1734 >        try {
1735 >            ObjectInputStream ois = new ObjectInputStream
1736 >                (new ByteArrayInputStream(serialBytes(o)));
1737 >            T clone = (T) ois.readObject();
1738 >            assertSame(o.getClass(), clone.getClass());
1739 >            return clone;
1740 >        } catch (Throwable fail) {
1741 >            threadUnexpectedException(fail);
1742              return null;
1743          }
1744      }
1745 +
1746 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1747 +                             Runnable... throwingActions) {
1748 +        for (Runnable throwingAction : throwingActions) {
1749 +            boolean threw = false;
1750 +            try { throwingAction.run(); }
1751 +            catch (Throwable t) {
1752 +                threw = true;
1753 +                if (!expectedExceptionClass.isInstance(t)) {
1754 +                    AssertionFailedError afe =
1755 +                        new AssertionFailedError
1756 +                        ("Expected " + expectedExceptionClass.getName() +
1757 +                         ", got " + t.getClass().getName());
1758 +                    afe.initCause(t);
1759 +                    threadUnexpectedException(afe);
1760 +                }
1761 +            }
1762 +            if (!threw)
1763 +                shouldThrow(expectedExceptionClass.getName());
1764 +        }
1765 +    }
1766 +
1767 +    public void assertIteratorExhausted(Iterator<?> it) {
1768 +        try {
1769 +            it.next();
1770 +            shouldThrow();
1771 +        } catch (NoSuchElementException success) {}
1772 +        assertFalse(it.hasNext());
1773 +    }
1774   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines