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.101 by jsr166, Wed Feb 6 16:57:21 2013 UTC vs.
Revision 1.242 by jsr166, Mon Feb 19 16:12:11 2018 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
8   */
9  
10 < import junit.framework.*;
10 > /*
11 > * @test
12 > * @summary JSR-166 tck tests, in a number of variations.
13 > *          The first is the conformance testing variant,
14 > *          while others also test implementation details.
15 > * @build *
16 > * @modules java.management
17 > * @run junit/othervm/timeout=1000 JSR166TestCase
18 > * @run junit/othervm/timeout=1000
19 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 > *      --add-opens java.base/java.lang=ALL-UNNAMED
21 > *      -Djsr166.testImplementationDetails=true
22 > *      JSR166TestCase
23 > * @run junit/othervm/timeout=1000
24 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 > *      --add-opens java.base/java.lang=ALL-UNNAMED
26 > *      -Djsr166.testImplementationDetails=true
27 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28 > *      JSR166TestCase
29 > * @run junit/othervm/timeout=1000
30 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 > *      --add-opens java.base/java.lang=ALL-UNNAMED
32 > *      -Djsr166.testImplementationDetails=true
33 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
34 > *      -Djava.util.secureRandomSeed=true
35 > *      JSR166TestCase
36 > * @run junit/othervm/timeout=1000/policy=tck.policy
37 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 > *      --add-opens java.base/java.lang=ALL-UNNAMED
39 > *      -Djsr166.testImplementationDetails=true
40 > *      JSR166TestCase
41 > */
42 >
43 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
44 > import static java.util.concurrent.TimeUnit.MINUTES;
45 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
46 >
47   import java.io.ByteArrayInputStream;
48   import java.io.ByteArrayOutputStream;
49   import java.io.ObjectInputStream;
50   import java.io.ObjectOutputStream;
51   import java.lang.management.ManagementFactory;
52   import java.lang.management.ThreadInfo;
53 + import java.lang.management.ThreadMXBean;
54 + import java.lang.reflect.Constructor;
55   import java.lang.reflect.Method;
56 + import java.lang.reflect.Modifier;
57 + import java.security.CodeSource;
58 + import java.security.Permission;
59 + import java.security.PermissionCollection;
60 + import java.security.Permissions;
61 + import java.security.Policy;
62 + import java.security.ProtectionDomain;
63 + import java.security.SecurityPermission;
64   import java.util.ArrayList;
65   import java.util.Arrays;
66 + import java.util.Collection;
67 + import java.util.Collections;
68   import java.util.Date;
69   import java.util.Enumeration;
70 + import java.util.Iterator;
71   import java.util.List;
72   import java.util.NoSuchElementException;
73   import java.util.PropertyPermission;
74 < import java.util.concurrent.*;
74 > import java.util.concurrent.BlockingQueue;
75 > import java.util.concurrent.Callable;
76 > import java.util.concurrent.CountDownLatch;
77 > import java.util.concurrent.CyclicBarrier;
78 > import java.util.concurrent.ExecutionException;
79 > import java.util.concurrent.Executor;
80 > import java.util.concurrent.Executors;
81 > import java.util.concurrent.ExecutorService;
82 > import java.util.concurrent.ForkJoinPool;
83 > import java.util.concurrent.Future;
84 > import java.util.concurrent.FutureTask;
85 > import java.util.concurrent.RecursiveAction;
86 > import java.util.concurrent.RecursiveTask;
87 > import java.util.concurrent.RejectedExecutionException;
88 > import java.util.concurrent.RejectedExecutionHandler;
89 > import java.util.concurrent.Semaphore;
90 > import java.util.concurrent.ScheduledExecutorService;
91 > import java.util.concurrent.ScheduledFuture;
92 > import java.util.concurrent.SynchronousQueue;
93 > import java.util.concurrent.ThreadFactory;
94 > import java.util.concurrent.ThreadLocalRandom;
95 > import java.util.concurrent.ThreadPoolExecutor;
96 > import java.util.concurrent.TimeUnit;
97 > import java.util.concurrent.TimeoutException;
98   import java.util.concurrent.atomic.AtomicBoolean;
99   import java.util.concurrent.atomic.AtomicReference;
100 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
101 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
102 < import java.security.CodeSource;
103 < import java.security.Permission;
104 < import java.security.PermissionCollection;
105 < import java.security.Permissions;
33 < import java.security.Policy;
34 < import java.security.ProtectionDomain;
35 < import java.security.SecurityPermission;
100 > import java.util.regex.Pattern;
101 >
102 > import junit.framework.Test;
103 > import junit.framework.TestCase;
104 > import junit.framework.TestResult;
105 > import junit.framework.TestSuite;
106  
107   /**
108   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 44 | Line 114 | import java.security.SecurityPermission;
114   *
115   * <ol>
116   *
117 < * <li> All assertions in code running in generated threads must use
117 > * <li>All assertions in code running in generated threads must use
118   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
119   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
120   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
121   * particularly recommended) for other code to use these forms too.
122   * Only the most typically used JUnit assertion methods are defined
123 < * this way, but enough to live with.</li>
123 > * this way, but enough to live with.
124   *
125 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
125 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
126   * to invoke {@code super.setUp} and {@code super.tearDown} within
127   * them. These methods are used to clear and check for thread
128 < * assertion failures.</li>
128 > * assertion failures.
129   *
130   * <li>All delays and timeouts must use one of the constants {@code
131   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 66 | Line 136 | import java.security.SecurityPermission;
136   * is always discriminable as larger than SHORT and smaller than
137   * MEDIUM.  And so on. These constants are set to conservative values,
138   * but even so, if there is ever any doubt, they can all be increased
139 < * in one spot to rerun tests on slower platforms.</li>
139 > * in one spot to rerun tests on slower platforms.
140   *
141 < * <li> All threads generated must be joined inside each test case
141 > * <li>All threads generated must be joined inside each test case
142   * method (or {@code fail} to do so) before returning from the
143   * method. The {@code joinPool} method can be used to do this when
144 < * using Executors.</li>
144 > * using Executors.
145   *
146   * </ol>
147   *
148   * <p><b>Other notes</b>
149   * <ul>
150   *
151 < * <li> Usually, there is one testcase method per JSR166 method
151 > * <li>Usually, there is one testcase method per JSR166 method
152   * covering "normal" operation, and then as many exception-testing
153   * methods as there are exceptions the method can throw. Sometimes
154   * there are multiple tests per JSR166 method when the different
155   * "normal" behaviors differ significantly. And sometimes testcases
156 < * cover multiple methods when they cannot be tested in
87 < * isolation.</li>
156 > * cover multiple methods when they cannot be tested in isolation.
157   *
158 < * <li> The documentation style for testcases is to provide as javadoc
158 > * <li>The documentation style for testcases is to provide as javadoc
159   * a simple sentence or two describing the property that the testcase
160   * method purports to test. The javadocs do not say anything about how
161 < * the property is tested. To find out, read the code.</li>
161 > * the property is tested. To find out, read the code.
162   *
163 < * <li> These tests are "conformance tests", and do not attempt to
163 > * <li>These tests are "conformance tests", and do not attempt to
164   * test throughput, latency, scalability or other performance factors
165   * (see the separate "jtreg" tests for a set intended to check these
166   * for the most central aspects of functionality.) So, most tests use
167   * the smallest sensible numbers of threads, collection sizes, etc
168 < * needed to check basic conformance.</li>
168 > * needed to check basic conformance.
169   *
170   * <li>The test classes currently do not declare inclusion in
171   * any particular package to simplify things for people integrating
172 < * them in TCK test suites.</li>
172 > * them in TCK test suites.
173   *
174 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
175 < * runs all JSR166 unit tests.</li>
174 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
175 > * runs all JSR166 unit tests.
176   *
177   * </ul>
178   */
# Line 115 | Line 184 | public class JSR166TestCase extends Test
184          Boolean.getBoolean("jsr166.expensiveTests");
185  
186      /**
187 +     * If true, also run tests that are not part of the official tck
188 +     * because they test unspecified implementation details.
189 +     */
190 +    protected static final boolean testImplementationDetails =
191 +        Boolean.getBoolean("jsr166.testImplementationDetails");
192 +
193 +    /**
194       * If true, report on stdout all "slow" tests, that is, ones that
195       * take more than profileThreshold milliseconds to execute.
196       */
# Line 128 | Line 204 | public class JSR166TestCase extends Test
204      private static final long profileThreshold =
205          Long.getLong("jsr166.profileThreshold", 100);
206  
207 +    /**
208 +     * The number of repetitions per test (for tickling rare bugs).
209 +     */
210 +    private static final int runsPerTest =
211 +        Integer.getInteger("jsr166.runsPerTest", 1);
212 +
213 +    /**
214 +     * The number of repetitions of the test suite (for finding leaks?).
215 +     */
216 +    private static final int suiteRuns =
217 +        Integer.getInteger("jsr166.suiteRuns", 1);
218 +
219 +    /**
220 +     * Returns the value of the system property, or NaN if not defined.
221 +     */
222 +    private static float systemPropertyValue(String name) {
223 +        String floatString = System.getProperty(name);
224 +        if (floatString == null)
225 +            return Float.NaN;
226 +        try {
227 +            return Float.parseFloat(floatString);
228 +        } catch (NumberFormatException ex) {
229 +            throw new IllegalArgumentException(
230 +                String.format("Bad float value in system property %s=%s",
231 +                              name, floatString));
232 +        }
233 +    }
234 +
235 +    /**
236 +     * The scaling factor to apply to standard delays used in tests.
237 +     * May be initialized from any of:
238 +     * - the "jsr166.delay.factor" system property
239 +     * - the "test.timeout.factor" system property (as used by jtreg)
240 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
241 +     * - hard-coded fuzz factor when using a known slowpoke VM
242 +     */
243 +    private static final float delayFactor = delayFactor();
244 +
245 +    private static float delayFactor() {
246 +        float x;
247 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
248 +            return x;
249 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
250 +            return x;
251 +        String prop = System.getProperty("java.vm.version");
252 +        if (prop != null && prop.matches(".*debug.*"))
253 +            return 4.0f; // How much slower is fastdebug than product?!
254 +        return 1.0f;
255 +    }
256 +
257 +    public JSR166TestCase() { super(); }
258 +    public JSR166TestCase(String name) { super(name); }
259 +
260 +    /**
261 +     * A filter for tests to run, matching strings of the form
262 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
263 +     * Usefully combined with jsr166.runsPerTest.
264 +     */
265 +    private static final Pattern methodFilter = methodFilter();
266 +
267 +    private static Pattern methodFilter() {
268 +        String regex = System.getProperty("jsr166.methodFilter");
269 +        return (regex == null) ? null : Pattern.compile(regex);
270 +    }
271 +
272 +    // Instrumentation to debug very rare, but very annoying hung test runs.
273 +    static volatile TestCase currentTestCase;
274 +    // static volatile int currentRun = 0;
275 +    static {
276 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
277 +            // Avoid spurious reports with enormous runsPerTest.
278 +            // A single test case run should never take more than 1 second.
279 +            // But let's cap it at the high end too ...
280 +            final int timeoutMinutes =
281 +                Math.min(15, Math.max(runsPerTest / 60, 1));
282 +            for (TestCase lastTestCase = currentTestCase;;) {
283 +                try { MINUTES.sleep(timeoutMinutes); }
284 +                catch (InterruptedException unexpected) { break; }
285 +                if (lastTestCase == currentTestCase) {
286 +                    System.err.printf(
287 +                        "Looks like we're stuck running test: %s%n",
288 +                        lastTestCase);
289 + //                     System.err.printf(
290 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
291 + //                         lastTestCase, currentRun, runsPerTest);
292 + //                     System.err.println("availableProcessors=" +
293 + //                         Runtime.getRuntime().availableProcessors());
294 + //                     System.err.printf("cpu model = %s%n", cpuModel());
295 +                    dumpTestThreads();
296 +                    // one stack dump is probably enough; more would be spam
297 +                    break;
298 +                }
299 +                lastTestCase = currentTestCase;
300 +            }}};
301 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
302 +        thread.setDaemon(true);
303 +        thread.start();
304 +    }
305 +
306 + //     public static String cpuModel() {
307 + //         try {
308 + //             java.util.regex.Matcher matcher
309 + //               = Pattern.compile("model name\\s*: (.*)")
310 + //                 .matcher(new String(
311 + //                     java.nio.file.Files.readAllBytes(
312 + //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
313 + //             matcher.find();
314 + //             return matcher.group(1);
315 + //         } catch (Exception ex) { return null; }
316 + //     }
317 +
318 +    public void runBare() throws Throwable {
319 +        currentTestCase = this;
320 +        if (methodFilter == null
321 +            || methodFilter.matcher(toString()).find())
322 +            super.runBare();
323 +    }
324 +
325      protected void runTest() throws Throwable {
326 <        if (profileTests)
327 <            runTestProfiled();
328 <        else
329 <            super.runTest();
326 >        for (int i = 0; i < runsPerTest; i++) {
327 >            // currentRun = i;
328 >            if (profileTests)
329 >                runTestProfiled();
330 >            else
331 >                super.runTest();
332 >        }
333      }
334  
335      protected void runTestProfiled() throws Throwable {
336 <        long t0 = System.nanoTime();
337 <        try {
336 >        for (int i = 0; i < 2; i++) {
337 >            long startTime = System.nanoTime();
338              super.runTest();
339 <        } finally {
340 <            long elapsedMillis =
341 <                (System.nanoTime() - t0) / (1000L * 1000L);
342 <            if (elapsedMillis >= profileThreshold)
339 >            long elapsedMillis = millisElapsedSince(startTime);
340 >            if (elapsedMillis < profileThreshold)
341 >                break;
342 >            // Never report first run of any test; treat it as a
343 >            // warmup run, notably to trigger all needed classloading,
344 >            if (i > 0)
345                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
346          }
347      }
348  
349      /**
350       * 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.
351       */
352      public static void main(String[] args) {
353 +        main(suite(), args);
354 +    }
355 +
356 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
357 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
358 +        long runTime;
359 +        public void startTest(Test test) {}
360 +        protected void printHeader(long runTime) {
361 +            this.runTime = runTime; // defer printing for later
362 +        }
363 +        protected void printFooter(TestResult result) {
364 +            if (result.wasSuccessful()) {
365 +                getWriter().println("OK (" + result.runCount() + " tests)"
366 +                    + "  Time: " + elapsedTimeAsString(runTime));
367 +            } else {
368 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
369 +                super.printFooter(result);
370 +            }
371 +        }
372 +    }
373 +
374 +    /**
375 +     * Returns a TestRunner that doesn't bother with unnecessary
376 +     * fluff, like printing a "." for each test case.
377 +     */
378 +    static junit.textui.TestRunner newPithyTestRunner() {
379 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
380 +        runner.setPrinter(new PithyResultPrinter(System.out));
381 +        return runner;
382 +    }
383 +
384 +    /**
385 +     * Runs all unit tests in the given test suite.
386 +     * Actual behavior influenced by jsr166.* system properties.
387 +     */
388 +    static void main(Test suite, String[] args) {
389          if (useSecurityManager) {
390              System.err.println("Setting a permissive security manager");
391              Policy.setPolicy(permissivePolicy());
392              System.setSecurityManager(new SecurityManager());
393          }
394 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
395 <
396 <        Test s = suite();
397 <        for (int i = 0; i < iters; ++i) {
165 <            junit.textui.TestRunner.run(s);
394 >        for (int i = 0; i < suiteRuns; i++) {
395 >            TestResult result = newPithyTestRunner().doRun(suite);
396 >            if (!result.wasSuccessful())
397 >                System.exit(1);
398              System.gc();
399              System.runFinalization();
400          }
169        System.exit(0);
401      }
402  
403      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 187 | Line 418 | public class JSR166TestCase extends Test
418          for (String testClassName : testClassNames) {
419              try {
420                  Class<?> testClass = Class.forName(testClassName);
421 <                Method m = testClass.getDeclaredMethod("suite",
191 <                                                       new Class<?>[0]);
421 >                Method m = testClass.getDeclaredMethod("suite");
422                  suite.addTest(newTestSuite((Test)m.invoke(null)));
423 <            } catch (Exception e) {
424 <                throw new Error("Missing test class", e);
423 >            } catch (ReflectiveOperationException e) {
424 >                throw new AssertionError("Missing test class", e);
425              }
426          }
427      }
428  
429      public static final double JAVA_CLASS_VERSION;
430 +    public static final String JAVA_SPECIFICATION_VERSION;
431      static {
432          try {
433              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
434                  new java.security.PrivilegedAction<Double>() {
435                  public Double run() {
436                      return Double.valueOf(System.getProperty("java.class.version"));}});
437 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
438 +                new java.security.PrivilegedAction<String>() {
439 +                public String run() {
440 +                    return System.getProperty("java.specification.version");}});
441          } catch (Throwable t) {
442              throw new Error(t);
443          }
444      }
445  
446 <    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
447 <    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
448 <    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
446 >    public static boolean atLeastJava6()  { return JAVA_CLASS_VERSION >= 50.0; }
447 >    public static boolean atLeastJava7()  { return JAVA_CLASS_VERSION >= 51.0; }
448 >    public static boolean atLeastJava8()  { return JAVA_CLASS_VERSION >= 52.0; }
449 >    public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
450 >    public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
451  
452      /**
453       * Collects all JSR166 unit tests as one suite.
# Line 231 | Line 468 | public class JSR166TestCase extends Test
468              AbstractQueuedLongSynchronizerTest.suite(),
469              ArrayBlockingQueueTest.suite(),
470              ArrayDequeTest.suite(),
471 +            ArrayListTest.suite(),
472              AtomicBooleanTest.suite(),
473              AtomicIntegerArrayTest.suite(),
474              AtomicIntegerFieldUpdaterTest.suite(),
# Line 253 | Line 491 | public class JSR166TestCase extends Test
491              CopyOnWriteArrayListTest.suite(),
492              CopyOnWriteArraySetTest.suite(),
493              CountDownLatchTest.suite(),
494 +            CountedCompleterTest.suite(),
495              CyclicBarrierTest.suite(),
496              DelayQueueTest.suite(),
497              EntryTest.suite(),
# Line 281 | Line 520 | public class JSR166TestCase extends Test
520              TreeMapTest.suite(),
521              TreeSetTest.suite(),
522              TreeSubMapTest.suite(),
523 <            TreeSubSetTest.suite());
523 >            TreeSubSetTest.suite(),
524 >            VectorTest.suite());
525  
526          // Java8+ test classes
527          if (atLeastJava8()) {
528              String[] java8TestClassNames = {
529 <                "StampedLockTest",
529 >                "ArrayDeque8Test",
530 >                "Atomic8Test",
531 >                "CompletableFutureTest",
532 >                "ConcurrentHashMap8Test",
533 >                "CountedCompleter8Test",
534 >                "DoubleAccumulatorTest",
535 >                "DoubleAdderTest",
536                  "ForkJoinPool8Test",
537 +                "ForkJoinTask8Test",
538 +                "HashMapTest",
539 +                "LinkedBlockingDeque8Test",
540 +                "LinkedBlockingQueue8Test",
541 +                "LongAccumulatorTest",
542 +                "LongAdderTest",
543 +                "SplittableRandomTest",
544 +                "StampedLockTest",
545 +                "SubmissionPublisherTest",
546 +                "ThreadLocalRandom8Test",
547 +                "TimeUnit8Test",
548              };
549              addNamedTestClasses(suite, java8TestClassNames);
550          }
551  
552 +        // Java9+ test classes
553 +        if (atLeastJava9()) {
554 +            String[] java9TestClassNames = {
555 +                "AtomicBoolean9Test",
556 +                "AtomicInteger9Test",
557 +                "AtomicIntegerArray9Test",
558 +                "AtomicLong9Test",
559 +                "AtomicLongArray9Test",
560 +                "AtomicReference9Test",
561 +                "AtomicReferenceArray9Test",
562 +                "ExecutorCompletionService9Test",
563 +                "ForkJoinPool9Test",
564 +            };
565 +            addNamedTestClasses(suite, java9TestClassNames);
566 +        }
567 +
568          return suite;
569      }
570  
571 +    /** Returns list of junit-style test method names in given class. */
572 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
573 +        Method[] methods = testClass.getDeclaredMethods();
574 +        ArrayList<String> names = new ArrayList<>(methods.length);
575 +        for (Method method : methods) {
576 +            if (method.getName().startsWith("test")
577 +                && Modifier.isPublic(method.getModifiers())
578 +                // method.getParameterCount() requires jdk8+
579 +                && method.getParameterTypes().length == 0) {
580 +                names.add(method.getName());
581 +            }
582 +        }
583 +        return names;
584 +    }
585 +
586 +    /**
587 +     * Returns junit-style testSuite for the given test class, but
588 +     * parameterized by passing extra data to each test.
589 +     */
590 +    public static <ExtraData> Test parameterizedTestSuite
591 +        (Class<? extends JSR166TestCase> testClass,
592 +         Class<ExtraData> dataClass,
593 +         ExtraData data) {
594 +        try {
595 +            TestSuite suite = new TestSuite();
596 +            Constructor c =
597 +                testClass.getDeclaredConstructor(dataClass, String.class);
598 +            for (String methodName : testMethodNames(testClass))
599 +                suite.addTest((Test) c.newInstance(data, methodName));
600 +            return suite;
601 +        } catch (ReflectiveOperationException e) {
602 +            throw new AssertionError(e);
603 +        }
604 +    }
605 +
606 +    /**
607 +     * Returns junit-style testSuite for the jdk8 extension of the
608 +     * given test class, but parameterized by passing extra data to
609 +     * each test.  Uses reflection to allow compilation in jdk7.
610 +     */
611 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
612 +        (Class<? extends JSR166TestCase> testClass,
613 +         Class<ExtraData> dataClass,
614 +         ExtraData data) {
615 +        if (atLeastJava8()) {
616 +            String name = testClass.getName();
617 +            String name8 = name.replaceAll("Test$", "8Test");
618 +            if (name.equals(name8)) throw new AssertionError(name);
619 +            try {
620 +                return (Test)
621 +                    Class.forName(name8)
622 +                    .getMethod("testSuite", dataClass)
623 +                    .invoke(null, data);
624 +            } catch (ReflectiveOperationException e) {
625 +                throw new AssertionError(e);
626 +            }
627 +        } else {
628 +            return new TestSuite();
629 +        }
630 +    }
631 +
632 +    // Delays for timing-dependent tests, in milliseconds.
633  
634      public static long SHORT_DELAY_MS;
635      public static long SMALL_DELAY_MS;
636      public static long MEDIUM_DELAY_MS;
637      public static long LONG_DELAY_MS;
638  
639 +    private static final long RANDOM_TIMEOUT;
640 +    private static final long RANDOM_EXPIRED_TIMEOUT;
641 +    private static final TimeUnit RANDOM_TIMEUNIT;
642 +    static {
643 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
644 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
645 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
646 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
647 +        TimeUnit[] timeUnits = TimeUnit.values();
648 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
649 +    }
650  
651      /**
652 <     * Returns the shortest timed delay. This could
653 <     * be reimplemented to use for example a Property.
652 >     * Returns a timeout for use when any value at all will do.
653 >     */
654 >    static long randomTimeout() { return RANDOM_TIMEOUT; }
655 >
656 >    /**
657 >     * Returns a timeout that means "no waiting", i.e. not positive.
658 >     */
659 >    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
660 >
661 >    /**
662 >     * Returns a random non-null TimeUnit.
663 >     */
664 >    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
665 >
666 >    /**
667 >     * Returns the shortest timed delay. This can be scaled up for
668 >     * slow machines using the jsr166.delay.factor system property,
669 >     * or via jtreg's -timeoutFactor: flag.
670 >     * http://openjdk.java.net/jtreg/command-help.html
671       */
672      protected long getShortDelay() {
673 <        return 50;
673 >        return (long) (50 * delayFactor);
674      }
675  
676      /**
# Line 320 | Line 683 | public class JSR166TestCase extends Test
683          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
684      }
685  
686 +    private static final long TIMEOUT_DELAY_MS
687 +        = (long) (12.0 * Math.cbrt(delayFactor));
688 +
689      /**
690 <     * Returns a timeout in milliseconds to be used in tests that
691 <     * verify that operations block or time out.
690 >     * Returns a timeout in milliseconds to be used in tests that verify
691 >     * that operations block or time out.  We want this to be longer
692 >     * than the OS scheduling quantum, but not too long, so don't scale
693 >     * linearly with delayFactor; we use "crazy" cube root instead.
694       */
695 <    long timeoutMillis() {
696 <        return SHORT_DELAY_MS / 4;
695 >    static long timeoutMillis() {
696 >        return TIMEOUT_DELAY_MS;
697      }
698  
699      /**
700 <     * Returns a new Date instance representing a time delayMillis
701 <     * milliseconds in the future.
700 >     * Returns a new Date instance representing a time at least
701 >     * delayMillis milliseconds in the future.
702       */
703      Date delayedDate(long delayMillis) {
704 <        return new Date(System.currentTimeMillis() + delayMillis);
704 >        // Add 1 because currentTimeMillis is known to round into the past.
705 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
706      }
707  
708      /**
709       * The first exception encountered if any threadAssertXXX method fails.
710       */
711      private final AtomicReference<Throwable> threadFailure
712 <        = new AtomicReference<Throwable>(null);
712 >        = new AtomicReference<>(null);
713  
714      /**
715       * Records an exception so that it can be rethrown later in the test
# Line 349 | Line 718 | public class JSR166TestCase extends Test
718       * the same test have no effect.
719       */
720      public void threadRecordFailure(Throwable t) {
721 +        System.err.println(t);
722 +        dumpTestThreads();
723          threadFailure.compareAndSet(null, t);
724      }
725  
# Line 356 | Line 727 | public class JSR166TestCase extends Test
727          setDelays();
728      }
729  
730 +    void tearDownFail(String format, Object... args) {
731 +        String msg = toString() + ": " + String.format(format, args);
732 +        System.err.println(msg);
733 +        dumpTestThreads();
734 +        throw new AssertionError(msg);
735 +    }
736 +
737      /**
738       * Extra checks that get done for all test cases.
739       *
# Line 374 | Line 752 | public class JSR166TestCase extends Test
752                  throw (RuntimeException) t;
753              else if (t instanceof Exception)
754                  throw (Exception) t;
755 <            else {
756 <                AssertionFailedError afe =
379 <                    new AssertionFailedError(t.toString());
380 <                afe.initCause(t);
381 <                throw afe;
382 <            }
755 >            else
756 >                throw new AssertionError(t.toString(), t);
757          }
758  
759          if (Thread.interrupted())
760 <            throw new AssertionFailedError("interrupt status set in main thread");
760 >            tearDownFail("interrupt status set in main thread");
761  
762          checkForkJoinPoolThreadLeaks();
763      }
764  
765      /**
766 <     * Find missing try { ... } finally { joinPool(e); }
766 >     * Finds missing PoolCleaners
767       */
768      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
769 <        Thread[] survivors = new Thread[5];
769 >        Thread[] survivors = new Thread[7];
770          int count = Thread.enumerate(survivors);
771          for (int i = 0; i < count; i++) {
772              Thread thread = survivors[i];
# Line 400 | Line 774 | public class JSR166TestCase extends Test
774              if (name.startsWith("ForkJoinPool-")) {
775                  // give thread some time to terminate
776                  thread.join(LONG_DELAY_MS);
777 <                if (!thread.isAlive()) continue;
778 <                thread.stop();
779 <                throw new AssertionFailedError
406 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
407 <                                   toString(), name));
777 >                if (thread.isAlive())
778 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
779 >                                 thread);
780              }
781          }
782 +
783 +        if (!ForkJoinPool.commonPool()
784 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
785 +            tearDownFail("ForkJoin common pool thread stuck");
786      }
787  
788      /**
789       * Just like fail(reason), but additionally recording (using
790 <     * threadRecordFailure) any AssertionFailedError thrown, so that
791 <     * the current testcase will fail.
790 >     * threadRecordFailure) any AssertionError thrown, so that the
791 >     * current testcase will fail.
792       */
793      public void threadFail(String reason) {
794          try {
795              fail(reason);
796 <        } catch (AssertionFailedError t) {
797 <            threadRecordFailure(t);
798 <            fail(reason);
796 >        } catch (AssertionError fail) {
797 >            threadRecordFailure(fail);
798 >            throw fail;
799          }
800      }
801  
802      /**
803       * Just like assertTrue(b), but additionally recording (using
804 <     * threadRecordFailure) any AssertionFailedError thrown, so that
805 <     * the current testcase will fail.
804 >     * threadRecordFailure) any AssertionError thrown, so that the
805 >     * current testcase will fail.
806       */
807      public void threadAssertTrue(boolean b) {
808          try {
809              assertTrue(b);
810 <        } catch (AssertionFailedError t) {
811 <            threadRecordFailure(t);
812 <            throw t;
810 >        } catch (AssertionError fail) {
811 >            threadRecordFailure(fail);
812 >            throw fail;
813          }
814      }
815  
816      /**
817       * Just like assertFalse(b), but additionally recording (using
818 <     * threadRecordFailure) any AssertionFailedError thrown, so that
819 <     * the current testcase will fail.
818 >     * threadRecordFailure) any AssertionError thrown, so that the
819 >     * current testcase will fail.
820       */
821      public void threadAssertFalse(boolean b) {
822          try {
823              assertFalse(b);
824 <        } catch (AssertionFailedError t) {
825 <            threadRecordFailure(t);
826 <            throw t;
824 >        } catch (AssertionError fail) {
825 >            threadRecordFailure(fail);
826 >            throw fail;
827          }
828      }
829  
830      /**
831       * Just like assertNull(x), but additionally recording (using
832 <     * threadRecordFailure) any AssertionFailedError thrown, so that
833 <     * the current testcase will fail.
832 >     * threadRecordFailure) any AssertionError thrown, so that the
833 >     * current testcase will fail.
834       */
835      public void threadAssertNull(Object x) {
836          try {
837              assertNull(x);
838 <        } catch (AssertionFailedError t) {
839 <            threadRecordFailure(t);
840 <            throw t;
838 >        } catch (AssertionError fail) {
839 >            threadRecordFailure(fail);
840 >            throw fail;
841          }
842      }
843  
844      /**
845       * Just like assertEquals(x, y), but additionally recording (using
846 <     * threadRecordFailure) any AssertionFailedError thrown, so that
847 <     * the current testcase will fail.
846 >     * threadRecordFailure) any AssertionError thrown, so that the
847 >     * current testcase will fail.
848       */
849      public void threadAssertEquals(long x, long y) {
850          try {
851              assertEquals(x, y);
852 <        } catch (AssertionFailedError t) {
853 <            threadRecordFailure(t);
854 <            throw t;
852 >        } catch (AssertionError fail) {
853 >            threadRecordFailure(fail);
854 >            throw fail;
855          }
856      }
857  
858      /**
859       * Just like assertEquals(x, y), but additionally recording (using
860 <     * threadRecordFailure) any AssertionFailedError thrown, so that
861 <     * the current testcase will fail.
860 >     * threadRecordFailure) any AssertionError thrown, so that the
861 >     * current testcase will fail.
862       */
863      public void threadAssertEquals(Object x, Object y) {
864          try {
865              assertEquals(x, y);
866 <        } catch (AssertionFailedError t) {
867 <            threadRecordFailure(t);
868 <            throw t;
869 <        } catch (Throwable t) {
870 <            threadUnexpectedException(t);
866 >        } catch (AssertionError fail) {
867 >            threadRecordFailure(fail);
868 >            throw fail;
869 >        } catch (Throwable fail) {
870 >            threadUnexpectedException(fail);
871          }
872      }
873  
874      /**
875       * Just like assertSame(x, y), but additionally recording (using
876 <     * threadRecordFailure) any AssertionFailedError thrown, so that
877 <     * the current testcase will fail.
876 >     * threadRecordFailure) any AssertionError thrown, so that the
877 >     * current testcase will fail.
878       */
879      public void threadAssertSame(Object x, Object y) {
880          try {
881              assertSame(x, y);
882 <        } catch (AssertionFailedError t) {
883 <            threadRecordFailure(t);
884 <            throw t;
882 >        } catch (AssertionError fail) {
883 >            threadRecordFailure(fail);
884 >            throw fail;
885          }
886      }
887  
# Line 525 | Line 901 | public class JSR166TestCase extends Test
901  
902      /**
903       * Records the given exception using {@link #threadRecordFailure},
904 <     * then rethrows the exception, wrapping it in an
905 <     * AssertionFailedError if necessary.
904 >     * then rethrows the exception, wrapping it in an AssertionError
905 >     * if necessary.
906       */
907      public void threadUnexpectedException(Throwable t) {
908          threadRecordFailure(t);
# Line 535 | Line 911 | public class JSR166TestCase extends Test
911              throw (RuntimeException) t;
912          else if (t instanceof Error)
913              throw (Error) t;
914 <        else {
915 <            AssertionFailedError afe =
540 <                new AssertionFailedError("unexpected exception: " + t);
541 <            afe.initCause(t);
542 <            throw afe;
543 <        }
914 >        else
915 >            throw new AssertionError("unexpected exception: " + t, t);
916      }
917  
918      /**
919       * Delays, via Thread.sleep, for the given millisecond delay, but
920       * if the sleep is shorter than specified, may re-sleep or yield
921 <     * until time elapses.
921 >     * until time elapses.  Ensures that the given time, as measured
922 >     * by System.nanoTime(), has elapsed.
923       */
924      static void delay(long millis) throws InterruptedException {
925 <        long startTime = System.nanoTime();
926 <        long ns = millis * 1000 * 1000;
927 <        for (;;) {
925 >        long nanos = millis * (1000 * 1000);
926 >        final long wakeupTime = System.nanoTime() + nanos;
927 >        do {
928              if (millis > 0L)
929                  Thread.sleep(millis);
930              else // too short to sleep
931                  Thread.yield();
932 <            long d = ns - (System.nanoTime() - startTime);
933 <            if (d > 0L)
934 <                millis = d / (1000 * 1000);
935 <            else
936 <                break;
932 >            nanos = wakeupTime - System.nanoTime();
933 >            millis = nanos / (1000 * 1000);
934 >        } while (nanos >= 0L);
935 >    }
936 >
937 >    /**
938 >     * Allows use of try-with-resources with per-test thread pools.
939 >     */
940 >    class PoolCleaner implements AutoCloseable {
941 >        private final ExecutorService pool;
942 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
943 >        public void close() { joinPool(pool); }
944 >    }
945 >
946 >    /**
947 >     * An extension of PoolCleaner that has an action to release the pool.
948 >     */
949 >    class PoolCleanerWithReleaser extends PoolCleaner {
950 >        private final Runnable releaser;
951 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
952 >            super(pool);
953 >            this.releaser = releaser;
954          }
955 +        public void close() {
956 +            try {
957 +                releaser.run();
958 +            } finally {
959 +                super.close();
960 +            }
961 +        }
962 +    }
963 +
964 +    PoolCleaner cleaner(ExecutorService pool) {
965 +        return new PoolCleaner(pool);
966 +    }
967 +
968 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
969 +        return new PoolCleanerWithReleaser(pool, releaser);
970 +    }
971 +
972 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
973 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
974 +    }
975 +
976 +    Runnable releaser(final CountDownLatch latch) {
977 +        return new Runnable() { public void run() {
978 +            do { latch.countDown(); }
979 +            while (latch.getCount() > 0);
980 +        }};
981 +    }
982 +
983 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
984 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
985 +    }
986 +
987 +    Runnable releaser(final AtomicBoolean flag) {
988 +        return new Runnable() { public void run() { flag.set(true); }};
989      }
990  
991      /**
992       * Waits out termination of a thread pool or fails doing so.
993       */
994 <    void joinPool(ExecutorService exec) {
994 >    void joinPool(ExecutorService pool) {
995          try {
996 <            exec.shutdown();
997 <            assertTrue("ExecutorService did not terminate in a timely manner",
998 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
996 >            pool.shutdown();
997 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
998 >                try {
999 >                    threadFail("ExecutorService " + pool +
1000 >                               " did not terminate in a timely manner");
1001 >                } finally {
1002 >                    // last resort, for the benefit of subsequent tests
1003 >                    pool.shutdownNow();
1004 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1005 >                }
1006 >            }
1007          } catch (SecurityException ok) {
1008              // Allowed in case test doesn't have privs
1009 <        } catch (InterruptedException ie) {
1010 <            fail("Unexpected InterruptedException");
1009 >        } catch (InterruptedException fail) {
1010 >            threadFail("Unexpected InterruptedException");
1011          }
1012      }
1013  
1014      /**
1015 <     * A debugging tool to print all stack traces, as jstack does.
1015 >     * Like Runnable, but with the freedom to throw anything.
1016 >     * junit folks had the same idea:
1017 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1018       */
1019 <    static void printAllStackTraces() {
586 <        for (ThreadInfo info :
587 <                 ManagementFactory.getThreadMXBean()
588 <                 .dumpAllThreads(true, true))
589 <            System.err.print(info);
590 <    }
1019 >    interface Action { public void run() throws Throwable; }
1020  
1021      /**
1022 <     * Checks that thread does not terminate within the default
1023 <     * millisecond delay of {@code timeoutMillis()}.
1022 >     * Runs all the given actions in parallel, failing if any fail.
1023 >     * Useful for running multiple variants of tests that are
1024 >     * necessarily individually slow because they must block.
1025       */
1026 <    void assertThreadStaysAlive(Thread thread) {
1027 <        assertThreadStaysAlive(thread, timeoutMillis());
1026 >    void testInParallel(Action ... actions) {
1027 >        ExecutorService pool = Executors.newCachedThreadPool();
1028 >        try (PoolCleaner cleaner = cleaner(pool)) {
1029 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1030 >            for (final Action action : actions)
1031 >                futures.add(pool.submit(new CheckedRunnable() {
1032 >                    public void realRun() throws Throwable { action.run();}}));
1033 >            for (Future<?> future : futures)
1034 >                try {
1035 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1036 >                } catch (ExecutionException ex) {
1037 >                    threadUnexpectedException(ex.getCause());
1038 >                } catch (Exception ex) {
1039 >                    threadUnexpectedException(ex);
1040 >                }
1041 >        }
1042      }
1043  
1044      /**
1045 <     * Checks that thread does not terminate within the given millisecond delay.
1045 >     * A debugging tool to print stack traces of most threads, as jstack does.
1046 >     * Uninteresting threads are filtered out.
1047       */
1048 <    void assertThreadStaysAlive(Thread thread, long millis) {
1049 <        try {
1050 <            // No need to optimize the failing case via Thread.join.
1051 <            delay(millis);
1052 <            assertTrue(thread.isAlive());
1053 <        } catch (InterruptedException ie) {
1054 <            fail("Unexpected InterruptedException");
1048 >    static void dumpTestThreads() {
1049 >        SecurityManager sm = System.getSecurityManager();
1050 >        if (sm != null) {
1051 >            try {
1052 >                System.setSecurityManager(null);
1053 >            } catch (SecurityException giveUp) {
1054 >                return;
1055 >            }
1056          }
611    }
1057  
1058 <    /**
1059 <     * Checks that the threads do not terminate within the default
1060 <     * millisecond delay of {@code timeoutMillis()}.
1061 <     */
1062 <    void assertThreadsStayAlive(Thread... threads) {
1063 <        assertThreadsStayAlive(timeoutMillis(), threads);
1058 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1059 >        System.err.println("------ stacktrace dump start ------");
1060 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1061 >            final String name = info.getThreadName();
1062 >            String lockName;
1063 >            if ("Signal Dispatcher".equals(name))
1064 >                continue;
1065 >            if ("Reference Handler".equals(name)
1066 >                && (lockName = info.getLockName()) != null
1067 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1068 >                continue;
1069 >            if ("Finalizer".equals(name)
1070 >                && (lockName = info.getLockName()) != null
1071 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1072 >                continue;
1073 >            if ("checkForWedgedTest".equals(name))
1074 >                continue;
1075 >            System.err.print(info);
1076 >        }
1077 >        System.err.println("------ stacktrace dump end ------");
1078 >
1079 >        if (sm != null) System.setSecurityManager(sm);
1080      }
1081  
1082      /**
1083 <     * Checks that the threads do not terminate within the given millisecond delay.
1083 >     * Checks that thread eventually enters the expected blocked thread state.
1084       */
1085 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1086 <        try {
1087 <            // No need to optimize the failing case via Thread.join.
1088 <            delay(millis);
1089 <            for (Thread thread : threads)
1090 <                assertTrue(thread.isAlive());
1091 <        } catch (InterruptedException ie) {
1092 <            fail("Unexpected InterruptedException");
1085 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1086 >        // always sleep at least 1 ms, with high probability avoiding
1087 >        // transitory states
1088 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1089 >            try { delay(1); }
1090 >            catch (InterruptedException fail) {
1091 >                throw new AssertionError("Unexpected InterruptedException", fail);
1092 >            }
1093 >            Thread.State s = thread.getState();
1094 >            if (s == expected)
1095 >                return;
1096 >            else if (s == Thread.State.TERMINATED)
1097 >                fail("Unexpected thread termination");
1098          }
1099 +        fail("timed out waiting for thread to enter thread state " + expected);
1100      }
1101  
1102      /**
# Line 649 | Line 1116 | public class JSR166TestCase extends Test
1116              future.get(timeoutMillis, MILLISECONDS);
1117              shouldThrow();
1118          } catch (TimeoutException success) {
1119 <        } catch (Exception e) {
1120 <            threadUnexpectedException(e);
1119 >        } catch (Exception fail) {
1120 >            threadUnexpectedException(fail);
1121          } finally { future.cancel(true); }
1122          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1123      }
# Line 670 | Line 1137 | public class JSR166TestCase extends Test
1137      }
1138  
1139      /**
1140 +     * The maximum number of consecutive spurious wakeups we should
1141 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1142 +     */
1143 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1144 +
1145 +    /**
1146       * The number of elements to place in collections, arrays, etc.
1147       */
1148      public static final int SIZE = 20;
# Line 694 | Line 1167 | public class JSR166TestCase extends Test
1167      public static final Integer m6  = new Integer(-6);
1168      public static final Integer m10 = new Integer(-10);
1169  
697
1170      /**
1171       * Runs Runnable r with a security policy that permits precisely
1172       * the specified permissions.  If there is no current security
# Line 774 | Line 1246 | public class JSR166TestCase extends Test
1246          }
1247          public void refresh() {}
1248          public String toString() {
1249 <            List<Permission> ps = new ArrayList<Permission>();
1249 >            List<Permission> ps = new ArrayList<>();
1250              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1251                  ps.add(e.nextElement());
1252              return "AdjustablePolicy with permissions " + ps;
# Line 802 | Line 1274 | public class JSR166TestCase extends Test
1274  
1275      /**
1276       * Sleeps until the given time has elapsed.
1277 <     * Throws AssertionFailedError if interrupted.
1277 >     * Throws AssertionError if interrupted.
1278       */
1279 <    void sleep(long millis) {
1279 >    static void sleep(long millis) {
1280          try {
1281              delay(millis);
1282 <        } catch (InterruptedException ie) {
1283 <            AssertionFailedError afe =
812 <                new AssertionFailedError("Unexpected InterruptedException");
813 <            afe.initCause(ie);
814 <            throw afe;
1282 >        } catch (InterruptedException fail) {
1283 >            throw new AssertionError("Unexpected InterruptedException", fail);
1284          }
1285      }
1286  
# Line 820 | Line 1289 | public class JSR166TestCase extends Test
1289       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1290       */
1291      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1292 <        long startTime = System.nanoTime();
1292 >        long startTime = 0L;
1293          for (;;) {
1294              Thread.State s = thread.getState();
1295              if (s == Thread.State.BLOCKED ||
# Line 829 | Line 1298 | public class JSR166TestCase extends Test
1298                  return;
1299              else if (s == Thread.State.TERMINATED)
1300                  fail("Unexpected thread termination");
1301 +            else if (startTime == 0L)
1302 +                startTime = System.nanoTime();
1303              else if (millisElapsedSince(startTime) > timeoutMillis) {
1304                  threadAssertTrue(thread.isAlive());
1305 <                return;
1305 >                fail("timed out waiting for thread to enter wait state");
1306              }
1307              Thread.yield();
1308          }
1309      }
1310  
1311      /**
1312 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1313 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1312 >     * Spin-waits up to the specified number of milliseconds for the given
1313 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1314 >     * and additionally satisfy the given condition.
1315 >     */
1316 >    void waitForThreadToEnterWaitState(
1317 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1318 >        long startTime = 0L;
1319 >        for (;;) {
1320 >            Thread.State s = thread.getState();
1321 >            if (s == Thread.State.BLOCKED ||
1322 >                s == Thread.State.WAITING ||
1323 >                s == Thread.State.TIMED_WAITING) {
1324 >                try {
1325 >                    if (waitingForGodot.call())
1326 >                        return;
1327 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1328 >            }
1329 >            else if (s == Thread.State.TERMINATED)
1330 >                fail("Unexpected thread termination");
1331 >            else if (startTime == 0L)
1332 >                startTime = System.nanoTime();
1333 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1334 >                threadAssertTrue(thread.isAlive());
1335 >                fail("timed out waiting for thread to enter wait state");
1336 >            }
1337 >            Thread.yield();
1338 >        }
1339 >    }
1340 >
1341 >    /**
1342 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1343 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1344       */
1345      void waitForThreadToEnterWaitState(Thread thread) {
1346          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1347      }
1348  
1349      /**
1350 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1351 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1352 +     * and additionally satisfy the given condition.
1353 +     */
1354 +    void waitForThreadToEnterWaitState(
1355 +        Thread thread, Callable<Boolean> waitingForGodot) {
1356 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1357 +    }
1358 +
1359 +    /**
1360       * Returns the number of milliseconds since time given by
1361       * startNanoTime, which must have been previously returned from a
1362 <     * call to {@link System.nanoTime()}.
1362 >     * call to {@link System#nanoTime()}.
1363       */
1364 <    long millisElapsedSince(long startNanoTime) {
1364 >    static long millisElapsedSince(long startNanoTime) {
1365          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1366      }
1367  
1368 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1369 + //         long startTime = System.nanoTime();
1370 + //         try {
1371 + //             r.run();
1372 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1373 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1374 + //             throw new AssertionError("did not return promptly");
1375 + //     }
1376 +
1377 + //     void assertTerminatesPromptly(Runnable r) {
1378 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1379 + //     }
1380 +
1381 +    /**
1382 +     * Checks that timed f.get() returns the expected value, and does not
1383 +     * wait for the timeout to elapse before returning.
1384 +     */
1385 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1386 +        long startTime = System.nanoTime();
1387 +        try {
1388 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1389 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1390 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1391 +            throw new AssertionError("timed get did not return promptly");
1392 +    }
1393 +
1394 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1395 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1396 +    }
1397 +
1398      /**
1399       * Returns a new started daemon Thread running the given runnable.
1400       */
# Line 872 | Line 1413 | public class JSR166TestCase extends Test
1413      void awaitTermination(Thread t, long timeoutMillis) {
1414          try {
1415              t.join(timeoutMillis);
1416 <        } catch (InterruptedException ie) {
1417 <            threadUnexpectedException(ie);
1416 >        } catch (InterruptedException fail) {
1417 >            threadUnexpectedException(fail);
1418          } finally {
1419              if (t.getState() != Thread.State.TERMINATED) {
1420                  t.interrupt();
1421 <                fail("Test timed out");
1421 >                threadFail("timed out waiting for thread to terminate");
1422              }
1423          }
1424      }
# Line 899 | Line 1440 | public class JSR166TestCase extends Test
1440          public final void run() {
1441              try {
1442                  realRun();
1443 <            } catch (Throwable t) {
1444 <                threadUnexpectedException(t);
904 <            }
905 <        }
906 <    }
907 <
908 <    public abstract class RunnableShouldThrow implements Runnable {
909 <        protected abstract void realRun() throws Throwable;
910 <
911 <        final Class<?> exceptionClass;
912 <
913 <        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
914 <            this.exceptionClass = exceptionClass;
915 <        }
916 <
917 <        public final void run() {
918 <            try {
919 <                realRun();
920 <                threadShouldThrow(exceptionClass.getSimpleName());
921 <            } catch (Throwable t) {
922 <                if (! exceptionClass.isInstance(t))
923 <                    threadUnexpectedException(t);
1443 >            } catch (Throwable fail) {
1444 >                threadUnexpectedException(fail);
1445              }
1446          }
1447      }
# Line 954 | Line 1475 | public class JSR166TestCase extends Test
1475                  threadShouldThrow("InterruptedException");
1476              } catch (InterruptedException success) {
1477                  threadAssertFalse(Thread.interrupted());
1478 <            } catch (Throwable t) {
1479 <                threadUnexpectedException(t);
1478 >            } catch (Throwable fail) {
1479 >                threadUnexpectedException(fail);
1480              }
1481          }
1482      }
# Line 966 | Line 1487 | public class JSR166TestCase extends Test
1487          public final T call() {
1488              try {
1489                  return realCall();
1490 <            } catch (Throwable t) {
1491 <                threadUnexpectedException(t);
1490 >            } catch (Throwable fail) {
1491 >                threadUnexpectedException(fail);
1492                  return null;
1493              }
1494          }
# Line 984 | Line 1505 | public class JSR166TestCase extends Test
1505                  return result;
1506              } catch (InterruptedException success) {
1507                  threadAssertFalse(Thread.interrupted());
1508 <            } catch (Throwable t) {
1509 <                threadUnexpectedException(t);
1508 >            } catch (Throwable fail) {
1509 >                threadUnexpectedException(fail);
1510              }
1511              return null;
1512          }
# Line 1002 | Line 1523 | public class JSR166TestCase extends Test
1523      public static final String TEST_STRING = "a test string";
1524  
1525      public static class StringTask implements Callable<String> {
1526 <        public String call() { return TEST_STRING; }
1526 >        final String value;
1527 >        public StringTask() { this(TEST_STRING); }
1528 >        public StringTask(String value) { this.value = value; }
1529 >        public String call() { return value; }
1530      }
1531  
1532      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1015 | Line 1539 | public class JSR166TestCase extends Test
1539              }};
1540      }
1541  
1542 <    public Runnable awaiter(final CountDownLatch latch) {
1542 >    public Runnable countDowner(final CountDownLatch latch) {
1543          return new CheckedRunnable() {
1544              public void realRun() throws InterruptedException {
1545 <                await(latch);
1545 >                latch.countDown();
1546              }};
1547      }
1548  
1549 <    public void await(CountDownLatch latch) {
1549 >    class LatchAwaiter extends CheckedRunnable {
1550 >        static final int NEW = 0;
1551 >        static final int RUNNING = 1;
1552 >        static final int DONE = 2;
1553 >        final CountDownLatch latch;
1554 >        int state = NEW;
1555 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1556 >        public void realRun() throws InterruptedException {
1557 >            state = 1;
1558 >            await(latch);
1559 >            state = 2;
1560 >        }
1561 >    }
1562 >
1563 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1564 >        return new LatchAwaiter(latch);
1565 >    }
1566 >
1567 >    public void await(CountDownLatch latch, long timeoutMillis) {
1568          try {
1569 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1570 <        } catch (Throwable t) {
1571 <            threadUnexpectedException(t);
1569 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1570 >                fail("timed out waiting for CountDownLatch for "
1571 >                     + (timeoutMillis/1000) + " sec");
1572 >        } catch (Throwable fail) {
1573 >            threadUnexpectedException(fail);
1574          }
1575      }
1576  
1577 +    public void await(CountDownLatch latch) {
1578 +        await(latch, LONG_DELAY_MS);
1579 +    }
1580 +
1581      public void await(Semaphore semaphore) {
1582          try {
1583 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1584 <        } catch (Throwable t) {
1585 <            threadUnexpectedException(t);
1583 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1584 >                fail("timed out waiting for Semaphore for "
1585 >                     + (LONG_DELAY_MS/1000) + " sec");
1586 >        } catch (Throwable fail) {
1587 >            threadUnexpectedException(fail);
1588 >        }
1589 >    }
1590 >
1591 >    public void await(CyclicBarrier barrier) {
1592 >        try {
1593 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1594 >        } catch (Throwable fail) {
1595 >            threadUnexpectedException(fail);
1596          }
1597      }
1598  
# Line 1052 | Line 1610 | public class JSR166TestCase extends Test
1610   //         long startTime = System.nanoTime();
1611   //         while (!flag.get()) {
1612   //             if (millisElapsedSince(startTime) > timeoutMillis)
1613 < //                 throw new AssertionFailedError("timed out");
1613 > //                 throw new AssertionError("timed out");
1614   //             Thread.yield();
1615   //         }
1616   //     }
# Line 1061 | Line 1619 | public class JSR166TestCase extends Test
1619          public String call() { throw new NullPointerException(); }
1620      }
1621  
1064    public static class CallableOne implements Callable<Integer> {
1065        public Integer call() { return one; }
1066    }
1067
1068    public class ShortRunnable extends CheckedRunnable {
1069        protected void realRun() throws Throwable {
1070            delay(SHORT_DELAY_MS);
1071        }
1072    }
1073
1074    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1075        protected void realRun() throws InterruptedException {
1076            delay(SHORT_DELAY_MS);
1077        }
1078    }
1079
1080    public class SmallRunnable extends CheckedRunnable {
1081        protected void realRun() throws Throwable {
1082            delay(SMALL_DELAY_MS);
1083        }
1084    }
1085
1622      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1623          protected void realRun() {
1624              try {
# Line 1091 | Line 1627 | public class JSR166TestCase extends Test
1627          }
1628      }
1629  
1094    public class SmallCallable extends CheckedCallable {
1095        protected Object realCall() throws InterruptedException {
1096            delay(SMALL_DELAY_MS);
1097            return Boolean.TRUE;
1098        }
1099    }
1100
1101    public class MediumRunnable extends CheckedRunnable {
1102        protected void realRun() throws Throwable {
1103            delay(MEDIUM_DELAY_MS);
1104        }
1105    }
1106
1107    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1108        protected void realRun() throws InterruptedException {
1109            delay(MEDIUM_DELAY_MS);
1110        }
1111    }
1112
1630      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1631          return new CheckedRunnable() {
1632              protected void realRun() {
# Line 1119 | Line 1636 | public class JSR166TestCase extends Test
1636              }};
1637      }
1638  
1122    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1123        protected void realRun() {
1124            try {
1125                delay(MEDIUM_DELAY_MS);
1126            } catch (InterruptedException ok) {}
1127        }
1128    }
1129
1130    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1131        protected void realRun() {
1132            try {
1133                delay(LONG_DELAY_MS);
1134            } catch (InterruptedException ok) {}
1135        }
1136    }
1137
1639      /**
1640       * For use as ThreadFactory in constructors
1641       */
# Line 1148 | Line 1649 | public class JSR166TestCase extends Test
1649          boolean isDone();
1650      }
1651  
1151    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1152        return new TrackedRunnable() {
1153                private volatile boolean done = false;
1154                public boolean isDone() { return done; }
1155                public void run() {
1156                    try {
1157                        delay(timeoutMillis);
1158                        done = true;
1159                    } catch (InterruptedException ok) {}
1160                }
1161            };
1162    }
1163
1164    public static class TrackedShortRunnable implements Runnable {
1165        public volatile boolean done = false;
1166        public void run() {
1167            try {
1168                delay(SHORT_DELAY_MS);
1169                done = true;
1170            } catch (InterruptedException ok) {}
1171        }
1172    }
1173
1174    public static class TrackedSmallRunnable implements Runnable {
1175        public volatile boolean done = false;
1176        public void run() {
1177            try {
1178                delay(SMALL_DELAY_MS);
1179                done = true;
1180            } catch (InterruptedException ok) {}
1181        }
1182    }
1183
1184    public static class TrackedMediumRunnable implements Runnable {
1185        public volatile boolean done = false;
1186        public void run() {
1187            try {
1188                delay(MEDIUM_DELAY_MS);
1189                done = true;
1190            } catch (InterruptedException ok) {}
1191        }
1192    }
1193
1194    public static class TrackedLongRunnable implements Runnable {
1195        public volatile boolean done = false;
1196        public void run() {
1197            try {
1198                delay(LONG_DELAY_MS);
1199                done = true;
1200            } catch (InterruptedException ok) {}
1201        }
1202    }
1203
1652      public static class TrackedNoOpRunnable implements Runnable {
1653          public volatile boolean done = false;
1654          public void run() {
# Line 1208 | Line 1656 | public class JSR166TestCase extends Test
1656          }
1657      }
1658  
1211    public static class TrackedCallable implements Callable {
1212        public volatile boolean done = false;
1213        public Object call() {
1214            try {
1215                delay(SMALL_DELAY_MS);
1216                done = true;
1217            } catch (InterruptedException ok) {}
1218            return Boolean.TRUE;
1219        }
1220    }
1221
1659      /**
1660       * Analog of CheckedRunnable for RecursiveAction
1661       */
1662      public abstract class CheckedRecursiveAction extends RecursiveAction {
1663          protected abstract void realCompute() throws Throwable;
1664  
1665 <        public final void compute() {
1665 >        @Override protected final void compute() {
1666              try {
1667                  realCompute();
1668 <            } catch (Throwable t) {
1669 <                threadUnexpectedException(t);
1668 >            } catch (Throwable fail) {
1669 >                threadUnexpectedException(fail);
1670              }
1671          }
1672      }
# Line 1240 | Line 1677 | public class JSR166TestCase extends Test
1677      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1678          protected abstract T realCompute() throws Throwable;
1679  
1680 <        public final T compute() {
1680 >        @Override protected final T compute() {
1681              try {
1682                  return realCompute();
1683 <            } catch (Throwable t) {
1684 <                threadUnexpectedException(t);
1683 >            } catch (Throwable fail) {
1684 >                threadUnexpectedException(fail);
1685                  return null;
1686              }
1687          }
# Line 1260 | Line 1697 | public class JSR166TestCase extends Test
1697  
1698      /**
1699       * A CyclicBarrier that uses timed await and fails with
1700 <     * AssertionFailedErrors instead of throwing checked exceptions.
1700 >     * AssertionErrors instead of throwing checked exceptions.
1701       */
1702 <    public class CheckedBarrier extends CyclicBarrier {
1702 >    public static class CheckedBarrier extends CyclicBarrier {
1703          public CheckedBarrier(int parties) { super(parties); }
1704  
1705          public int await() {
1706              try {
1707                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1708 <            } catch (TimeoutException e) {
1709 <                throw new AssertionFailedError("timed out");
1710 <            } catch (Exception e) {
1711 <                AssertionFailedError afe =
1275 <                    new AssertionFailedError("Unexpected exception: " + e);
1276 <                afe.initCause(e);
1277 <                throw afe;
1708 >            } catch (TimeoutException timedOut) {
1709 >                throw new AssertionError("timed out");
1710 >            } catch (Exception fail) {
1711 >                throw new AssertionError("Unexpected exception: " + fail, fail);
1712              }
1713          }
1714      }
# Line 1285 | Line 1719 | public class JSR166TestCase extends Test
1719              assertEquals(0, q.size());
1720              assertNull(q.peek());
1721              assertNull(q.poll());
1722 <            assertNull(q.poll(0, MILLISECONDS));
1722 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1723              assertEquals(q.toString(), "[]");
1724              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1725              assertFalse(q.iterator().hasNext());
# Line 1301 | Line 1735 | public class JSR166TestCase extends Test
1735                  q.remove();
1736                  shouldThrow();
1737              } catch (NoSuchElementException success) {}
1738 <        } catch (InterruptedException ie) {
1305 <            threadUnexpectedException(ie);
1306 <        }
1738 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1739      }
1740  
1741      void assertSerialEquals(Object x, Object y) {
# Line 1322 | Line 1754 | public class JSR166TestCase extends Test
1754              oos.flush();
1755              oos.close();
1756              return bos.toByteArray();
1757 <        } catch (Throwable t) {
1758 <            threadUnexpectedException(t);
1757 >        } catch (Throwable fail) {
1758 >            threadUnexpectedException(fail);
1759              return new byte[0];
1760          }
1761      }
1762  
1763 +    void assertImmutable(final Object o) {
1764 +        if (o instanceof Collection) {
1765 +            assertThrows(
1766 +                UnsupportedOperationException.class,
1767 +                new Runnable() { public void run() {
1768 +                        ((Collection) o).add(null);}});
1769 +        }
1770 +    }
1771 +
1772      @SuppressWarnings("unchecked")
1773      <T> T serialClone(T o) {
1774          try {
1775              ObjectInputStream ois = new ObjectInputStream
1776                  (new ByteArrayInputStream(serialBytes(o)));
1777              T clone = (T) ois.readObject();
1778 +            if (o == clone) assertImmutable(o);
1779              assertSame(o.getClass(), clone.getClass());
1780              return clone;
1781 <        } catch (Throwable t) {
1782 <            threadUnexpectedException(t);
1781 >        } catch (Throwable fail) {
1782 >            threadUnexpectedException(fail);
1783              return null;
1784          }
1785      }
1786 +
1787 +    /**
1788 +     * A version of serialClone that leaves error handling (for
1789 +     * e.g. NotSerializableException) up to the caller.
1790 +     */
1791 +    @SuppressWarnings("unchecked")
1792 +    <T> T serialClonePossiblyFailing(T o)
1793 +        throws ReflectiveOperationException, java.io.IOException {
1794 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1795 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1796 +        oos.writeObject(o);
1797 +        oos.flush();
1798 +        oos.close();
1799 +        ObjectInputStream ois = new ObjectInputStream
1800 +            (new ByteArrayInputStream(bos.toByteArray()));
1801 +        T clone = (T) ois.readObject();
1802 +        if (o == clone) assertImmutable(o);
1803 +        assertSame(o.getClass(), clone.getClass());
1804 +        return clone;
1805 +    }
1806 +
1807 +    /**
1808 +     * If o implements Cloneable and has a public clone method,
1809 +     * returns a clone of o, else null.
1810 +     */
1811 +    @SuppressWarnings("unchecked")
1812 +    <T> T cloneableClone(T o) {
1813 +        if (!(o instanceof Cloneable)) return null;
1814 +        final T clone;
1815 +        try {
1816 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1817 +        } catch (NoSuchMethodException ok) {
1818 +            return null;
1819 +        } catch (ReflectiveOperationException unexpected) {
1820 +            throw new Error(unexpected);
1821 +        }
1822 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1823 +        assertSame(o.getClass(), clone.getClass());
1824 +        return clone;
1825 +    }
1826 +
1827 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1828 +                             Runnable... throwingActions) {
1829 +        for (Runnable throwingAction : throwingActions) {
1830 +            boolean threw = false;
1831 +            try { throwingAction.run(); }
1832 +            catch (Throwable t) {
1833 +                threw = true;
1834 +                if (!expectedExceptionClass.isInstance(t))
1835 +                    throw new AssertionError(
1836 +                            "Expected " + expectedExceptionClass.getName() +
1837 +                            ", got " + t.getClass().getName(),
1838 +                            t);
1839 +            }
1840 +            if (!threw)
1841 +                shouldThrow(expectedExceptionClass.getName());
1842 +        }
1843 +    }
1844 +
1845 +    public void assertIteratorExhausted(Iterator<?> it) {
1846 +        try {
1847 +            it.next();
1848 +            shouldThrow();
1849 +        } catch (NoSuchElementException success) {}
1850 +        assertFalse(it.hasNext());
1851 +    }
1852 +
1853 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1854 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1855 +    }
1856 +
1857 +    public Runnable runnableThrowing(final RuntimeException ex) {
1858 +        return new Runnable() { public void run() { throw ex; }};
1859 +    }
1860 +
1861 +    /** A reusable thread pool to be shared by tests. */
1862 +    static final ExecutorService cachedThreadPool =
1863 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1864 +                               1000L, MILLISECONDS,
1865 +                               new SynchronousQueue<Runnable>());
1866 +
1867 +    static <T> void shuffle(T[] array) {
1868 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1869 +    }
1870 +
1871 +    /**
1872 +     * Returns the same String as would be returned by {@link
1873 +     * Object#toString}, whether or not the given object's class
1874 +     * overrides toString().
1875 +     *
1876 +     * @see System#identityHashCode
1877 +     */
1878 +    static String identityString(Object x) {
1879 +        return x.getClass().getName()
1880 +            + "@" + Integer.toHexString(System.identityHashCode(x));
1881 +    }
1882 +
1883 +    // --- Shared assertions for Executor tests ---
1884 +
1885 +    /**
1886 +     * Returns maximum number of tasks that can be submitted to given
1887 +     * pool (with bounded queue) before saturation (when submission
1888 +     * throws RejectedExecutionException).
1889 +     */
1890 +    static final int saturatedSize(ThreadPoolExecutor pool) {
1891 +        BlockingQueue<Runnable> q = pool.getQueue();
1892 +        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1893 +    }
1894 +
1895 +    @SuppressWarnings("FutureReturnValueIgnored")
1896 +    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1897 +        try {
1898 +            e.execute((Runnable) null);
1899 +            shouldThrow();
1900 +        } catch (NullPointerException success) {}
1901 +
1902 +        if (! (e instanceof ExecutorService)) return;
1903 +        ExecutorService es = (ExecutorService) e;
1904 +        try {
1905 +            es.submit((Runnable) null);
1906 +            shouldThrow();
1907 +        } catch (NullPointerException success) {}
1908 +        try {
1909 +            es.submit((Runnable) null, Boolean.TRUE);
1910 +            shouldThrow();
1911 +        } catch (NullPointerException success) {}
1912 +        try {
1913 +            es.submit((Callable) null);
1914 +            shouldThrow();
1915 +        } catch (NullPointerException success) {}
1916 +
1917 +        if (! (e instanceof ScheduledExecutorService)) return;
1918 +        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1919 +        try {
1920 +            ses.schedule((Runnable) null,
1921 +                         randomTimeout(), randomTimeUnit());
1922 +            shouldThrow();
1923 +        } catch (NullPointerException success) {}
1924 +        try {
1925 +            ses.schedule((Callable) null,
1926 +                         randomTimeout(), randomTimeUnit());
1927 +            shouldThrow();
1928 +        } catch (NullPointerException success) {}
1929 +        try {
1930 +            ses.scheduleAtFixedRate((Runnable) null,
1931 +                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1932 +            shouldThrow();
1933 +        } catch (NullPointerException success) {}
1934 +        try {
1935 +            ses.scheduleWithFixedDelay((Runnable) null,
1936 +                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1937 +            shouldThrow();
1938 +        } catch (NullPointerException success) {}
1939 +    }
1940 +
1941 +    void setRejectedExecutionHandler(
1942 +        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1943 +        p.setRejectedExecutionHandler(handler);
1944 +        assertSame(handler, p.getRejectedExecutionHandler());
1945 +    }
1946 +
1947 +    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1948 +        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1949 +        final long savedTaskCount = p.getTaskCount();
1950 +        final long savedCompletedTaskCount = p.getCompletedTaskCount();
1951 +        final int savedQueueSize = p.getQueue().size();
1952 +        final boolean stock = (p.getClass().getClassLoader() == null);
1953 +
1954 +        Runnable r = () -> {};
1955 +        Callable<Boolean> c = () -> Boolean.TRUE;
1956 +
1957 +        class Recorder implements RejectedExecutionHandler {
1958 +            public volatile Runnable r = null;
1959 +            public volatile ThreadPoolExecutor p = null;
1960 +            public void reset() { r = null; p = null; }
1961 +            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1962 +                assertNull(this.r);
1963 +                assertNull(this.p);
1964 +                this.r = r;
1965 +                this.p = p;
1966 +            }
1967 +        }
1968 +
1969 +        // check custom handler is invoked exactly once per task
1970 +        Recorder recorder = new Recorder();
1971 +        setRejectedExecutionHandler(p, recorder);
1972 +        for (int i = 2; i--> 0; ) {
1973 +            recorder.reset();
1974 +            p.execute(r);
1975 +            if (stock && p.getClass() == ThreadPoolExecutor.class)
1976 +                assertSame(r, recorder.r);
1977 +            assertSame(p, recorder.p);
1978 +
1979 +            recorder.reset();
1980 +            assertFalse(p.submit(r).isDone());
1981 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1982 +            assertSame(p, recorder.p);
1983 +
1984 +            recorder.reset();
1985 +            assertFalse(p.submit(r, Boolean.TRUE).isDone());
1986 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1987 +            assertSame(p, recorder.p);
1988 +
1989 +            recorder.reset();
1990 +            assertFalse(p.submit(c).isDone());
1991 +            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
1992 +            assertSame(p, recorder.p);
1993 +
1994 +            if (p instanceof ScheduledExecutorService) {
1995 +                ScheduledExecutorService s = (ScheduledExecutorService) p;
1996 +                ScheduledFuture<?> future;
1997 +
1998 +                recorder.reset();
1999 +                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2000 +                assertFalse(future.isDone());
2001 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2002 +                assertSame(p, recorder.p);
2003 +
2004 +                recorder.reset();
2005 +                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2006 +                assertFalse(future.isDone());
2007 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2008 +                assertSame(p, recorder.p);
2009 +
2010 +                recorder.reset();
2011 +                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2012 +                assertFalse(future.isDone());
2013 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2014 +                assertSame(p, recorder.p);
2015 +
2016 +                recorder.reset();
2017 +                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2018 +                assertFalse(future.isDone());
2019 +                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2020 +                assertSame(p, recorder.p);
2021 +            }
2022 +        }
2023 +
2024 +        // Checking our custom handler above should be sufficient, but
2025 +        // we add some integration tests of standard handlers.
2026 +        final AtomicReference<Thread> thread = new AtomicReference<>();
2027 +        final Runnable setThread = () -> thread.set(Thread.currentThread());
2028 +
2029 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2030 +        try {
2031 +            p.execute(setThread);
2032 +            shouldThrow();
2033 +        } catch (RejectedExecutionException success) {}
2034 +        assertNull(thread.get());
2035 +
2036 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2037 +        p.execute(setThread);
2038 +        assertNull(thread.get());
2039 +
2040 +        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2041 +        p.execute(setThread);
2042 +        if (p.isShutdown())
2043 +            assertNull(thread.get());
2044 +        else
2045 +            assertSame(Thread.currentThread(), thread.get());
2046 +
2047 +        setRejectedExecutionHandler(p, savedHandler);
2048 +
2049 +        // check that pool was not perturbed by handlers
2050 +        assertEquals(savedTaskCount, p.getTaskCount());
2051 +        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2052 +        assertEquals(savedQueueSize, p.getQueue().size());
2053 +    }
2054   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines