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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines