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.6 by dl, Sun Oct 5 23:00:40 2003 UTC vs.
Revision 1.234 by jsr166, Mon Jul 17 22:27:31 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, 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.*;
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
120 < * threadAssertEquals}, or {@link threadAssertNull}, (not
121 < * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
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 > * {@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 < *
66 < * <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 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
196 <     */
197 <    public static void main (String[] args) {
198 <        junit.textui.TestRunner.run (suite());
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 <     * Collects all JSR166 unit tests as one suite
238 <     */
239 <    public static Test suite ( ) {
240 <        TestSuite suite = new TestSuite("JSR166 Unit Tests");
241 <        
242 <        suite.addTest(new TestSuite(ArrayBlockingQueueTest.class));
243 <        suite.addTest(new TestSuite(AtomicBooleanTest.class));
244 <        suite.addTest(new TestSuite(AtomicIntegerArrayTest.class));
245 <        suite.addTest(new TestSuite(AtomicIntegerFieldUpdaterTest.class));
246 <        suite.addTest(new TestSuite(AtomicIntegerTest.class));
247 <        suite.addTest(new TestSuite(AtomicLongArrayTest.class));
248 <        suite.addTest(new TestSuite(AtomicLongFieldUpdaterTest.class));
249 <        suite.addTest(new TestSuite(AtomicLongTest.class));
250 <        suite.addTest(new TestSuite(AtomicMarkableReferenceTest.class));
251 <        suite.addTest(new TestSuite(AtomicReferenceArrayTest.class));
252 <        suite.addTest(new TestSuite(AtomicReferenceFieldUpdaterTest.class));
253 <        suite.addTest(new TestSuite(AtomicReferenceTest.class));
254 <        suite.addTest(new TestSuite(AtomicStampedReferenceTest.class));
255 <        suite.addTest(new TestSuite(CancellableTaskTest.class));
256 <        suite.addTest(new TestSuite(ConcurrentHashMapTest.class));
257 <        suite.addTest(new TestSuite(ConcurrentLinkedQueueTest.class));
258 <        suite.addTest(new TestSuite(CopyOnWriteArrayListTest.class));
259 <        suite.addTest(new TestSuite(CopyOnWriteArraySetTest.class));
260 <        suite.addTest(new TestSuite(CountDownLatchTest.class));
261 <        suite.addTest(new TestSuite(CyclicBarrierTest.class));
262 <        suite.addTest(new TestSuite(DelayQueueTest.class));
263 <        suite.addTest(new TestSuite(ExchangerTest.class));
264 <        suite.addTest(new TestSuite(ExecutorsTest.class));
265 <        suite.addTest(new TestSuite(FairSemaphoreTest.class));
266 <        suite.addTest(new TestSuite(FutureTaskTest.class));
267 <        suite.addTest(new TestSuite(LinkedBlockingQueueTest.class));
268 <        suite.addTest(new TestSuite(LinkedListTest.class));
269 <        suite.addTest(new TestSuite(LockSupportTest.class));
270 <        suite.addTest(new TestSuite(PriorityBlockingQueueTest.class));
271 <        suite.addTest(new TestSuite(PriorityQueueTest.class));
272 <        suite.addTest(new TestSuite(ReentrantLockTest.class));
273 <        suite.addTest(new TestSuite(ReentrantReadWriteLockTest.class));
274 <        suite.addTest(new TestSuite(ScheduledExecutorTest.class));
275 <        suite.addTest(new TestSuite(SemaphoreTest.class));
276 <        suite.addTest(new TestSuite(SynchronousQueueTest.class));
277 <        suite.addTest(new TestSuite(SystemTest.class));
278 <        suite.addTest(new TestSuite(ThreadLocalTest.class));
279 <        suite.addTest(new TestSuite(ThreadPoolExecutorTest.class));
280 <        suite.addTest(new TestSuite(ThreadTest.class));
281 <        suite.addTest(new TestSuite(TimeUnitTest.class));
282 <                
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 >    }
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 +        // 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 +                "LinkedBlockingDeque8Test",
548 +                "LinkedBlockingQueue8Test",
549 +                "LongAccumulatorTest",
550 +                "LongAdderTest",
551 +                "SplittableRandomTest",
552 +                "StampedLockTest",
553 +                "SubmissionPublisherTest",
554 +                "ThreadLocalRandom8Test",
555 +                "TimeUnit8Test",
556 +            };
557 +            addNamedTestClasses(suite, java8TestClassNames);
558 +        }
559 +
560 +        // Java9+ test classes
561 +        if (atLeastJava9()) {
562 +            String[] java9TestClassNames = {
563 +                "AtomicBoolean9Test",
564 +                "AtomicInteger9Test",
565 +                "AtomicIntegerArray9Test",
566 +                "AtomicLong9Test",
567 +                "AtomicLongArray9Test",
568 +                "AtomicReference9Test",
569 +                "AtomicReferenceArray9Test",
570 +                "ExecutorCompletionService9Test",
571 +                "ForkJoinPool9Test",
572 +            };
573 +            addNamedTestClasses(suite, java9TestClassNames);
574 +        }
575 +
576 +        return suite;
577 +    }
578 +
579 +    /** Returns list of junit-style test method names in given class. */
580 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
581 +        Method[] methods = testClass.getDeclaredMethods();
582 +        ArrayList<String> names = new ArrayList<>(methods.length);
583 +        for (Method method : methods) {
584 +            if (method.getName().startsWith("test")
585 +                && Modifier.isPublic(method.getModifiers())
586 +                // method.getParameterCount() requires jdk8+
587 +                && method.getParameterTypes().length == 0) {
588 +                names.add(method.getName());
589 +            }
590 +        }
591 +        return names;
592 +    }
593 +
594 +    /**
595 +     * Returns junit-style testSuite for the given test class, but
596 +     * parameterized by passing extra data to each test.
597 +     */
598 +    public static <ExtraData> Test parameterizedTestSuite
599 +        (Class<? extends JSR166TestCase> testClass,
600 +         Class<ExtraData> dataClass,
601 +         ExtraData data) {
602 +        try {
603 +            TestSuite suite = new TestSuite();
604 +            Constructor c =
605 +                testClass.getDeclaredConstructor(dataClass, String.class);
606 +            for (String methodName : testMethodNames(testClass))
607 +                suite.addTest((Test) c.newInstance(data, methodName));
608 +            return suite;
609 +        } catch (Exception e) {
610 +            throw new Error(e);
611 +        }
612 +    }
613 +
614 +    /**
615 +     * Returns junit-style testSuite for the jdk8 extension of the
616 +     * given test class, but parameterized by passing extra data to
617 +     * each test.  Uses reflection to allow compilation in jdk7.
618 +     */
619 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
620 +        (Class<? extends JSR166TestCase> testClass,
621 +         Class<ExtraData> dataClass,
622 +         ExtraData data) {
623 +        if (atLeastJava8()) {
624 +            String name = testClass.getName();
625 +            String name8 = name.replaceAll("Test$", "8Test");
626 +            if (name.equals(name8)) throw new Error(name);
627 +            try {
628 +                return (Test)
629 +                    Class.forName(name8)
630 +                    .getMethod("testSuite", new Class[] { dataClass })
631 +                    .invoke(null, data);
632 +            } catch (Exception e) {
633 +                throw new Error(e);
634 +            }
635 +        } else {
636 +            return new TestSuite();
637 +        }
638 +    }
639 +
640 +    // Delays for timing-dependent tests, in milliseconds.
641  
642      public static long SHORT_DELAY_MS;
643      public static long SMALL_DELAY_MS;
644      public static long MEDIUM_DELAY_MS;
645      public static long LONG_DELAY_MS;
646  
647 +    private static final long RANDOM_TIMEOUT;
648 +    private static final long RANDOM_EXPIRED_TIMEOUT;
649 +    private static final TimeUnit RANDOM_TIMEUNIT;
650 +    static {
651 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
652 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
653 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
654 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
655 +        TimeUnit[] timeUnits = TimeUnit.values();
656 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
657 +    }
658 +
659 +    /**
660 +     * Returns a timeout for use when any value at all will do.
661 +     */
662 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
663 +
664 +    /**
665 +     * Returns a timeout that means "no waiting", i.e. not positive.
666 +     */
667 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
668 +
669 +    /**
670 +     * Returns a random non-null TimeUnit.
671 +     */
672 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
673  
674      /**
675 <     * Return the shortest timed delay. This could
676 <     * be reimplmented to use for example a Property.
677 <     */
675 >     * Returns the shortest timed delay. This can be scaled up for
676 >     * slow machines using the jsr166.delay.factor system property,
677 >     * or via jtreg's -timeoutFactor: flag.
678 >     * http://openjdk.java.net/jtreg/command-help.html
679 >     */
680      protected long getShortDelay() {
681 <        return 100;
681 >        return (long) (50 * delayFactor);
682      }
683  
160
684      /**
685 <     * Set delays as multiples of SHORT_DELAY.
685 >     * Sets delays as multiples of SHORT_DELAY.
686       */
687 <    protected  void setDelays() {
687 >    protected void setDelays() {
688          SHORT_DELAY_MS = getShortDelay();
689 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
689 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
690          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
691 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
691 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
692 >    }
693 >
694 >    private static final long TIMEOUT_DELAY_MS
695 >        = (long) (12.0 * Math.cbrt(delayFactor));
696 >
697 >    /**
698 >     * Returns a timeout in milliseconds to be used in tests that verify
699 >     * that operations block or time out.  We want this to be longer
700 >     * than the OS scheduling quantum, but not too long, so don't scale
701 >     * linearly with delayFactor; we use "crazy" cube root instead.
702 >     */
703 >    static long timeoutMillis() {
704 >        return TIMEOUT_DELAY_MS;
705      }
706  
707      /**
708 <     * Flag set true if any threadAssert methods fail
708 >     * Returns a new Date instance representing a time at least
709 >     * delayMillis milliseconds in the future.
710       */
711 <    volatile boolean threadFailed;
711 >    Date delayedDate(long delayMillis) {
712 >        // Add 1 because currentTimeMillis is known to round into the past.
713 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
714 >    }
715  
716      /**
717 <     * Initialize test to indicate that no thread assertions have failed
717 >     * The first exception encountered if any threadAssertXXX method fails.
718       */
719 <    public void setUp() {
719 >    private final AtomicReference<Throwable> threadFailure
720 >        = new AtomicReference<>(null);
721 >
722 >    /**
723 >     * Records an exception so that it can be rethrown later in the test
724 >     * harness thread, triggering a test case failure.  Only the first
725 >     * failure is recorded; subsequent calls to this method from within
726 >     * the same test have no effect.
727 >     */
728 >    public void threadRecordFailure(Throwable t) {
729 >        System.err.println(t);
730 >        dumpTestThreads();
731 >        threadFailure.compareAndSet(null, t);
732 >    }
733 >
734 >    public void setUp() {
735          setDelays();
736 <        threadFailed = false;  
736 >    }
737 >
738 >    void tearDownFail(String format, Object... args) {
739 >        String msg = toString() + ": " + String.format(format, args);
740 >        System.err.println(msg);
741 >        dumpTestThreads();
742 >        throw new AssertionFailedError(msg);
743 >    }
744 >
745 >    /**
746 >     * Extra checks that get done for all test cases.
747 >     *
748 >     * Triggers test case failure if any thread assertions have failed,
749 >     * by rethrowing, in the test harness thread, any exception recorded
750 >     * earlier by threadRecordFailure.
751 >     *
752 >     * Triggers test case failure if interrupt status is set in the main thread.
753 >     */
754 >    public void tearDown() throws Exception {
755 >        Throwable t = threadFailure.getAndSet(null);
756 >        if (t != null) {
757 >            if (t instanceof Error)
758 >                throw (Error) t;
759 >            else if (t instanceof RuntimeException)
760 >                throw (RuntimeException) t;
761 >            else if (t instanceof Exception)
762 >                throw (Exception) t;
763 >            else {
764 >                AssertionFailedError afe =
765 >                    new AssertionFailedError(t.toString());
766 >                afe.initCause(t);
767 >                throw afe;
768 >            }
769 >        }
770 >
771 >        if (Thread.interrupted())
772 >            tearDownFail("interrupt status set in main thread");
773 >
774 >        checkForkJoinPoolThreadLeaks();
775      }
776  
777      /**
778 <     * Trigger test case failure if any thread assertions have failed
778 >     * Finds missing PoolCleaners
779       */
780 <    public void tearDown() {
781 <        assertFalse(threadFailed);  
780 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
781 >        Thread[] survivors = new Thread[7];
782 >        int count = Thread.enumerate(survivors);
783 >        for (int i = 0; i < count; i++) {
784 >            Thread thread = survivors[i];
785 >            String name = thread.getName();
786 >            if (name.startsWith("ForkJoinPool-")) {
787 >                // give thread some time to terminate
788 >                thread.join(LONG_DELAY_MS);
789 >                if (thread.isAlive())
790 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
791 >                                 thread);
792 >            }
793 >        }
794 >
795 >        if (!ForkJoinPool.commonPool()
796 >            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
797 >            tearDownFail("ForkJoin common pool thread stuck");
798      }
799  
800      /**
801 <     * Fail, also setting status to indicate current testcase should fail
802 <     */
801 >     * Just like fail(reason), but additionally recording (using
802 >     * threadRecordFailure) any AssertionFailedError thrown, so that
803 >     * the current testcase will fail.
804 >     */
805      public void threadFail(String reason) {
806 <        threadFailed = true;
807 <        fail(reason);
806 >        try {
807 >            fail(reason);
808 >        } catch (AssertionFailedError t) {
809 >            threadRecordFailure(t);
810 >            throw t;
811 >        }
812      }
813  
814      /**
815 <     * If expression not true, set status to indicate current testcase
816 <     * should fail
817 <     */
815 >     * Just like assertTrue(b), but additionally recording (using
816 >     * threadRecordFailure) any AssertionFailedError thrown, so that
817 >     * the current testcase will fail.
818 >     */
819      public void threadAssertTrue(boolean b) {
820 <        if (!b) {
205 <            threadFailed = true;
820 >        try {
821              assertTrue(b);
822 +        } catch (AssertionFailedError t) {
823 +            threadRecordFailure(t);
824 +            throw t;
825          }
826      }
827  
828      /**
829 <     * If expression not false, set status to indicate current testcase
830 <     * should fail
831 <     */
829 >     * Just like assertFalse(b), but additionally recording (using
830 >     * threadRecordFailure) any AssertionFailedError thrown, so that
831 >     * the current testcase will fail.
832 >     */
833      public void threadAssertFalse(boolean b) {
834 <        if (b) {
216 <            threadFailed = true;
834 >        try {
835              assertFalse(b);
836 +        } catch (AssertionFailedError t) {
837 +            threadRecordFailure(t);
838 +            throw t;
839          }
840      }
841  
842      /**
843 <     * If argument not null, set status to indicate current testcase
844 <     * should fail
845 <     */
843 >     * Just like assertNull(x), but additionally recording (using
844 >     * threadRecordFailure) any AssertionFailedError thrown, so that
845 >     * the current testcase will fail.
846 >     */
847      public void threadAssertNull(Object x) {
848 <        if (x != null) {
227 <            threadFailed = true;
848 >        try {
849              assertNull(x);
850 +        } catch (AssertionFailedError t) {
851 +            threadRecordFailure(t);
852 +            throw t;
853          }
854      }
855  
856      /**
857 <     * If arguments not equal, set status to indicate current testcase
858 <     * should fail
859 <     */
857 >     * Just like assertEquals(x, y), but additionally recording (using
858 >     * threadRecordFailure) any AssertionFailedError thrown, so that
859 >     * the current testcase will fail.
860 >     */
861      public void threadAssertEquals(long x, long y) {
862 <        if (x != y) {
238 <            threadFailed = true;
862 >        try {
863              assertEquals(x, y);
864 +        } catch (AssertionFailedError t) {
865 +            threadRecordFailure(t);
866 +            throw t;
867          }
868      }
869  
870      /**
871 <     * If arguments not equal, set status to indicate current testcase
872 <     * should fail
873 <     */
871 >     * Just like assertEquals(x, y), but additionally recording (using
872 >     * threadRecordFailure) any AssertionFailedError thrown, so that
873 >     * the current testcase will fail.
874 >     */
875      public void threadAssertEquals(Object x, Object y) {
876 <        if (x != y && (x == null || !x.equals(y))) {
249 <            threadFailed = true;
876 >        try {
877              assertEquals(x, y);
878 +        } catch (AssertionFailedError fail) {
879 +            threadRecordFailure(fail);
880 +            throw fail;
881 +        } catch (Throwable fail) {
882 +            threadUnexpectedException(fail);
883 +        }
884 +    }
885 +
886 +    /**
887 +     * Just like assertSame(x, y), but additionally recording (using
888 +     * threadRecordFailure) any AssertionFailedError thrown, so that
889 +     * the current testcase will fail.
890 +     */
891 +    public void threadAssertSame(Object x, Object y) {
892 +        try {
893 +            assertSame(x, y);
894 +        } catch (AssertionFailedError fail) {
895 +            threadRecordFailure(fail);
896 +            throw fail;
897          }
898      }
899  
900      /**
901 <     * threadFail with message "should throw exception"
902 <     */
901 >     * Calls threadFail with message "should throw exception".
902 >     */
903      public void threadShouldThrow() {
904 <        threadFailed = true;
905 <        fail("should throw exception");
904 >        threadFail("should throw exception");
905 >    }
906 >
907 >    /**
908 >     * Calls threadFail with message "should throw" + exceptionName.
909 >     */
910 >    public void threadShouldThrow(String exceptionName) {
911 >        threadFail("should throw " + exceptionName);
912 >    }
913 >
914 >    /**
915 >     * Records the given exception using {@link #threadRecordFailure},
916 >     * then rethrows the exception, wrapping it in an
917 >     * AssertionFailedError if necessary.
918 >     */
919 >    public void threadUnexpectedException(Throwable t) {
920 >        threadRecordFailure(t);
921 >        t.printStackTrace();
922 >        if (t instanceof RuntimeException)
923 >            throw (RuntimeException) t;
924 >        else if (t instanceof Error)
925 >            throw (Error) t;
926 >        else {
927 >            AssertionFailedError afe =
928 >                new AssertionFailedError("unexpected exception: " + t);
929 >            afe.initCause(t);
930 >            throw afe;
931 >        }
932 >    }
933 >
934 >    /**
935 >     * Delays, via Thread.sleep, for the given millisecond delay, but
936 >     * if the sleep is shorter than specified, may re-sleep or yield
937 >     * until time elapses.  Ensures that the given time, as measured
938 >     * by System.nanoTime(), has elapsed.
939 >     */
940 >    static void delay(long millis) throws InterruptedException {
941 >        long nanos = millis * (1000 * 1000);
942 >        final long wakeupTime = System.nanoTime() + nanos;
943 >        do {
944 >            if (millis > 0L)
945 >                Thread.sleep(millis);
946 >            else // too short to sleep
947 >                Thread.yield();
948 >            nanos = wakeupTime - System.nanoTime();
949 >            millis = nanos / (1000 * 1000);
950 >        } while (nanos >= 0L);
951 >    }
952 >
953 >    /**
954 >     * Allows use of try-with-resources with per-test thread pools.
955 >     */
956 >    class PoolCleaner implements AutoCloseable {
957 >        private final ExecutorService pool;
958 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
959 >        public void close() { joinPool(pool); }
960 >    }
961 >
962 >    /**
963 >     * An extension of PoolCleaner that has an action to release the pool.
964 >     */
965 >    class PoolCleanerWithReleaser extends PoolCleaner {
966 >        private final Runnable releaser;
967 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
968 >            super(pool);
969 >            this.releaser = releaser;
970 >        }
971 >        public void close() {
972 >            try {
973 >                releaser.run();
974 >            } finally {
975 >                super.close();
976 >            }
977 >        }
978 >    }
979 >
980 >    PoolCleaner cleaner(ExecutorService pool) {
981 >        return new PoolCleaner(pool);
982 >    }
983 >
984 >    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
985 >        return new PoolCleanerWithReleaser(pool, releaser);
986 >    }
987 >
988 >    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
989 >        return new PoolCleanerWithReleaser(pool, releaser(latch));
990 >    }
991 >
992 >    Runnable releaser(final CountDownLatch latch) {
993 >        return new Runnable() { public void run() {
994 >            do { latch.countDown(); }
995 >            while (latch.getCount() > 0);
996 >        }};
997 >    }
998 >
999 >    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
1000 >        return new PoolCleanerWithReleaser(pool, releaser(flag));
1001 >    }
1002 >
1003 >    Runnable releaser(final AtomicBoolean flag) {
1004 >        return new Runnable() { public void run() { flag.set(true); }};
1005 >    }
1006 >
1007 >    /**
1008 >     * Waits out termination of a thread pool or fails doing so.
1009 >     */
1010 >    void joinPool(ExecutorService pool) {
1011 >        try {
1012 >            pool.shutdown();
1013 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
1014 >                try {
1015 >                    threadFail("ExecutorService " + pool +
1016 >                               " did not terminate in a timely manner");
1017 >                } finally {
1018 >                    // last resort, for the benefit of subsequent tests
1019 >                    pool.shutdownNow();
1020 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
1021 >                }
1022 >            }
1023 >        } catch (SecurityException ok) {
1024 >            // Allowed in case test doesn't have privs
1025 >        } catch (InterruptedException fail) {
1026 >            threadFail("Unexpected InterruptedException");
1027 >        }
1028 >    }
1029 >
1030 >    /**
1031 >     * Like Runnable, but with the freedom to throw anything.
1032 >     * junit folks had the same idea:
1033 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
1034 >     */
1035 >    interface Action { public void run() throws Throwable; }
1036 >
1037 >    /**
1038 >     * Runs all the given actions in parallel, failing if any fail.
1039 >     * Useful for running multiple variants of tests that are
1040 >     * necessarily individually slow because they must block.
1041 >     */
1042 >    void testInParallel(Action ... actions) {
1043 >        ExecutorService pool = Executors.newCachedThreadPool();
1044 >        try (PoolCleaner cleaner = cleaner(pool)) {
1045 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1046 >            for (final Action action : actions)
1047 >                futures.add(pool.submit(new CheckedRunnable() {
1048 >                    public void realRun() throws Throwable { action.run();}}));
1049 >            for (Future<?> future : futures)
1050 >                try {
1051 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1052 >                } catch (ExecutionException ex) {
1053 >                    threadUnexpectedException(ex.getCause());
1054 >                } catch (Exception ex) {
1055 >                    threadUnexpectedException(ex);
1056 >                }
1057 >        }
1058 >    }
1059 >
1060 >    /**
1061 >     * A debugging tool to print stack traces of most threads, as jstack does.
1062 >     * Uninteresting threads are filtered out.
1063 >     */
1064 >    static void dumpTestThreads() {
1065 >        SecurityManager sm = System.getSecurityManager();
1066 >        if (sm != null) {
1067 >            try {
1068 >                System.setSecurityManager(null);
1069 >            } catch (SecurityException giveUp) {
1070 >                return;
1071 >            }
1072 >        }
1073 >
1074 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1075 >        System.err.println("------ stacktrace dump start ------");
1076 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1077 >            final String name = info.getThreadName();
1078 >            String lockName;
1079 >            if ("Signal Dispatcher".equals(name))
1080 >                continue;
1081 >            if ("Reference Handler".equals(name)
1082 >                && (lockName = info.getLockName()) != null
1083 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1084 >                continue;
1085 >            if ("Finalizer".equals(name)
1086 >                && (lockName = info.getLockName()) != null
1087 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1088 >                continue;
1089 >            if ("checkForWedgedTest".equals(name))
1090 >                continue;
1091 >            System.err.print(info);
1092 >        }
1093 >        System.err.println("------ stacktrace dump end ------");
1094 >
1095 >        if (sm != null) System.setSecurityManager(sm);
1096 >    }
1097 >
1098 >    /**
1099 >     * Checks that thread eventually enters the expected blocked thread state.
1100 >     */
1101 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1102 >        // always sleep at least 1 ms, with high probability avoiding
1103 >        // transitory states
1104 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1105 >            try { delay(1); }
1106 >            catch (InterruptedException fail) {
1107 >                fail("Unexpected InterruptedException");
1108 >            }
1109 >            Thread.State s = thread.getState();
1110 >            if (s == expected)
1111 >                return;
1112 >            else if (s == Thread.State.TERMINATED)
1113 >                fail("Unexpected thread termination");
1114 >        }
1115 >        fail("timed out waiting for thread to enter thread state " + expected);
1116      }
1117  
1118      /**
1119 <     * threadFail with message "Unexpected exception"
1119 >     * Checks that thread does not terminate within the default
1120 >     * millisecond delay of {@code timeoutMillis()}.
1121 >     * TODO: REMOVEME
1122       */
1123 <    public void threadUnexpectedException() {
1124 <        threadFailed = true;
1125 <        fail("Unexpected exception");
1123 >    void assertThreadStaysAlive(Thread thread) {
1124 >        assertThreadStaysAlive(thread, timeoutMillis());
1125 >    }
1126 >
1127 >    /**
1128 >     * Checks that thread does not terminate within the given millisecond delay.
1129 >     * TODO: REMOVEME
1130 >     */
1131 >    void assertThreadStaysAlive(Thread thread, long millis) {
1132 >        try {
1133 >            // No need to optimize the failing case via Thread.join.
1134 >            delay(millis);
1135 >            assertTrue(thread.isAlive());
1136 >        } catch (InterruptedException fail) {
1137 >            threadFail("Unexpected InterruptedException");
1138 >        }
1139      }
1140  
1141 +    /**
1142 +     * Checks that the threads do not terminate within the default
1143 +     * millisecond delay of {@code timeoutMillis()}.
1144 +     * TODO: REMOVEME
1145 +     */
1146 +    void assertThreadsStayAlive(Thread... threads) {
1147 +        assertThreadsStayAlive(timeoutMillis(), threads);
1148 +    }
1149  
1150      /**
1151 <     * Wait out termination of a thread pool or fail doing so
1151 >     * Checks that the threads do not terminate within the given millisecond delay.
1152 >     * TODO: REMOVEME
1153       */
1154 <    public void joinPool(ExecutorService exec) {
1154 >    void assertThreadsStayAlive(long millis, Thread... threads) {
1155          try {
1156 <            exec.shutdown();
1157 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
1158 <        } catch(InterruptedException ie) {
1159 <            fail("Unexpected exception");
1156 >            // No need to optimize the failing case via Thread.join.
1157 >            delay(millis);
1158 >            for (Thread thread : threads)
1159 >                assertTrue(thread.isAlive());
1160 >        } catch (InterruptedException fail) {
1161 >            threadFail("Unexpected InterruptedException");
1162          }
1163      }
1164  
1165 +    /**
1166 +     * Checks that future.get times out, with the default timeout of
1167 +     * {@code timeoutMillis()}.
1168 +     */
1169 +    void assertFutureTimesOut(Future future) {
1170 +        assertFutureTimesOut(future, timeoutMillis());
1171 +    }
1172  
1173      /**
1174 <     * fail with message "should throw exception"
1175 <     */
1174 >     * Checks that future.get times out, with the given millisecond timeout.
1175 >     */
1176 >    void assertFutureTimesOut(Future future, long timeoutMillis) {
1177 >        long startTime = System.nanoTime();
1178 >        try {
1179 >            future.get(timeoutMillis, MILLISECONDS);
1180 >            shouldThrow();
1181 >        } catch (TimeoutException success) {
1182 >        } catch (Exception fail) {
1183 >            threadUnexpectedException(fail);
1184 >        } finally { future.cancel(true); }
1185 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1186 >    }
1187 >
1188 >    /**
1189 >     * Fails with message "should throw exception".
1190 >     */
1191      public void shouldThrow() {
1192          fail("Should throw exception");
1193      }
1194  
1195      /**
1196 <     * fail with message "Unexpected exception"
1196 >     * Fails with message "should throw " + exceptionName.
1197       */
1198 <    public void unexpectedException() {
1199 <        fail("Unexpected exception");
1198 >    public void shouldThrow(String exceptionName) {
1199 >        fail("Should throw " + exceptionName);
1200      }
1201  
1202 +    /**
1203 +     * The maximum number of consecutive spurious wakeups we should
1204 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1205 +     */
1206 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1207  
1208      /**
1209       * The number of elements to place in collections, arrays, etc.
1210       */
1211 <    static final int SIZE = 20;
1211 >    public static final int SIZE = 20;
1212  
1213      // Some convenient Integer constants
1214  
1215 <    static final Integer zero = new Integer(0);
1216 <    static final Integer one = new Integer(1);
1217 <    static final Integer two = new Integer(2);
1218 <    static final Integer three  = new Integer(3);
1219 <    static final Integer four  = new Integer(4);
1220 <    static final Integer five  = new Integer(5);
1221 <    static final Integer six = new Integer(6);
1222 <    static final Integer seven = new Integer(7);
1223 <    static final Integer eight = new Integer(8);
1224 <    static final Integer nine = new Integer(9);
1225 <    static final Integer m1  = new Integer(-1);
1226 <    static final Integer m2  = new Integer(-2);
1227 <    static final Integer m3  = new Integer(-3);
1228 <    static final Integer m4 = new Integer(-4);
1229 <    static final Integer m5 = new Integer(-5);
1230 <    static final Integer m10 = new Integer(-10);
1215 >    public static final Integer zero  = new Integer(0);
1216 >    public static final Integer one   = new Integer(1);
1217 >    public static final Integer two   = new Integer(2);
1218 >    public static final Integer three = new Integer(3);
1219 >    public static final Integer four  = new Integer(4);
1220 >    public static final Integer five  = new Integer(5);
1221 >    public static final Integer six   = new Integer(6);
1222 >    public static final Integer seven = new Integer(7);
1223 >    public static final Integer eight = new Integer(8);
1224 >    public static final Integer nine  = new Integer(9);
1225 >    public static final Integer m1  = new Integer(-1);
1226 >    public static final Integer m2  = new Integer(-2);
1227 >    public static final Integer m3  = new Integer(-3);
1228 >    public static final Integer m4  = new Integer(-4);
1229 >    public static final Integer m5  = new Integer(-5);
1230 >    public static final Integer m6  = new Integer(-6);
1231 >    public static final Integer m10 = new Integer(-10);
1232 >
1233 >    /**
1234 >     * Runs Runnable r with a security policy that permits precisely
1235 >     * the specified permissions.  If there is no current security
1236 >     * manager, the runnable is run twice, both with and without a
1237 >     * security manager.  We require that any security manager permit
1238 >     * getPolicy/setPolicy.
1239 >     */
1240 >    public void runWithPermissions(Runnable r, Permission... permissions) {
1241 >        SecurityManager sm = System.getSecurityManager();
1242 >        if (sm == null) {
1243 >            r.run();
1244 >        }
1245 >        runWithSecurityManagerWithPermissions(r, permissions);
1246 >    }
1247  
1248 +    /**
1249 +     * Runs Runnable r with a security policy that permits precisely
1250 +     * the specified permissions.  If there is no current security
1251 +     * manager, a temporary one is set for the duration of the
1252 +     * Runnable.  We require that any security manager permit
1253 +     * getPolicy/setPolicy.
1254 +     */
1255 +    public void runWithSecurityManagerWithPermissions(Runnable r,
1256 +                                                      Permission... permissions) {
1257 +        SecurityManager sm = System.getSecurityManager();
1258 +        if (sm == null) {
1259 +            Policy savedPolicy = Policy.getPolicy();
1260 +            try {
1261 +                Policy.setPolicy(permissivePolicy());
1262 +                System.setSecurityManager(new SecurityManager());
1263 +                runWithSecurityManagerWithPermissions(r, permissions);
1264 +            } finally {
1265 +                System.setSecurityManager(null);
1266 +                Policy.setPolicy(savedPolicy);
1267 +            }
1268 +        } else {
1269 +            Policy savedPolicy = Policy.getPolicy();
1270 +            AdjustablePolicy policy = new AdjustablePolicy(permissions);
1271 +            Policy.setPolicy(policy);
1272  
1273 <    // Some convenient Runnable classes
1273 >            try {
1274 >                r.run();
1275 >            } finally {
1276 >                policy.addPermission(new SecurityPermission("setPolicy"));
1277 >                Policy.setPolicy(savedPolicy);
1278 >            }
1279 >        }
1280 >    }
1281  
1282 <    static class NoOpRunnable implements Runnable {
1283 <        public void run() {}
1282 >    /**
1283 >     * Runs a runnable without any permissions.
1284 >     */
1285 >    public void runWithoutPermissions(Runnable r) {
1286 >        runWithPermissions(r);
1287      }
1288  
1289 <    static class NoOpCallable implements Callable {
1290 <        public Object call() { return Boolean.TRUE; }
1289 >    /**
1290 >     * A security policy where new permissions can be dynamically added
1291 >     * or all cleared.
1292 >     */
1293 >    public static class AdjustablePolicy extends java.security.Policy {
1294 >        Permissions perms = new Permissions();
1295 >        AdjustablePolicy(Permission... permissions) {
1296 >            for (Permission permission : permissions)
1297 >                perms.add(permission);
1298 >        }
1299 >        void addPermission(Permission perm) { perms.add(perm); }
1300 >        void clearPermissions() { perms = new Permissions(); }
1301 >        public PermissionCollection getPermissions(CodeSource cs) {
1302 >            return perms;
1303 >        }
1304 >        public PermissionCollection getPermissions(ProtectionDomain pd) {
1305 >            return perms;
1306 >        }
1307 >        public boolean implies(ProtectionDomain pd, Permission p) {
1308 >            return perms.implies(p);
1309 >        }
1310 >        public void refresh() {}
1311 >        public String toString() {
1312 >            List<Permission> ps = new ArrayList<>();
1313 >            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1314 >                ps.add(e.nextElement());
1315 >            return "AdjustablePolicy with permissions " + ps;
1316 >        }
1317      }
1318  
1319 <    class ShortRunnable implements Runnable {
1320 <        public void run() {
1321 <            try {
1322 <                Thread.sleep(SHORT_DELAY_MS);
1323 <            }
1324 <            catch(Exception e) {
1325 <                threadUnexpectedException();
1319 >    /**
1320 >     * Returns a policy containing all the permissions we ever need.
1321 >     */
1322 >    public static Policy permissivePolicy() {
1323 >        return new AdjustablePolicy
1324 >            // Permissions j.u.c. needs directly
1325 >            (new RuntimePermission("modifyThread"),
1326 >             new RuntimePermission("getClassLoader"),
1327 >             new RuntimePermission("setContextClassLoader"),
1328 >             // Permissions needed to change permissions!
1329 >             new SecurityPermission("getPolicy"),
1330 >             new SecurityPermission("setPolicy"),
1331 >             new RuntimePermission("setSecurityManager"),
1332 >             // Permissions needed by the junit test harness
1333 >             new RuntimePermission("accessDeclaredMembers"),
1334 >             new PropertyPermission("*", "read"),
1335 >             new java.io.FilePermission("<<ALL FILES>>", "read"));
1336 >    }
1337 >
1338 >    /**
1339 >     * Sleeps until the given time has elapsed.
1340 >     * Throws AssertionFailedError if interrupted.
1341 >     */
1342 >    static void sleep(long millis) {
1343 >        try {
1344 >            delay(millis);
1345 >        } catch (InterruptedException fail) {
1346 >            AssertionFailedError afe =
1347 >                new AssertionFailedError("Unexpected InterruptedException");
1348 >            afe.initCause(fail);
1349 >            throw afe;
1350 >        }
1351 >    }
1352 >
1353 >    /**
1354 >     * Spin-waits up to the specified number of milliseconds for the given
1355 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1356 >     */
1357 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1358 >        long startTime = 0L;
1359 >        for (;;) {
1360 >            Thread.State s = thread.getState();
1361 >            if (s == Thread.State.BLOCKED ||
1362 >                s == Thread.State.WAITING ||
1363 >                s == Thread.State.TIMED_WAITING)
1364 >                return;
1365 >            else if (s == Thread.State.TERMINATED)
1366 >                fail("Unexpected thread termination");
1367 >            else if (startTime == 0L)
1368 >                startTime = System.nanoTime();
1369 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1370 >                threadAssertTrue(thread.isAlive());
1371 >                fail("timed out waiting for thread to enter wait state");
1372              }
1373 +            Thread.yield();
1374          }
1375      }
1376  
1377 <    class ShortInterruptedRunnable implements Runnable {
1378 <        public void run() {
1379 <            try {
1380 <                Thread.sleep(SHORT_DELAY_MS);
1381 <                threadShouldThrow();
1377 >    /**
1378 >     * Spin-waits up to the specified number of milliseconds for the given
1379 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1380 >     * and additionally satisfy the given condition.
1381 >     */
1382 >    void waitForThreadToEnterWaitState(
1383 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1384 >        long startTime = 0L;
1385 >        for (;;) {
1386 >            Thread.State s = thread.getState();
1387 >            if (s == Thread.State.BLOCKED ||
1388 >                s == Thread.State.WAITING ||
1389 >                s == Thread.State.TIMED_WAITING) {
1390 >                try {
1391 >                    if (waitingForGodot.call())
1392 >                        return;
1393 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1394 >            }
1395 >            else if (s == Thread.State.TERMINATED)
1396 >                fail("Unexpected thread termination");
1397 >            else if (startTime == 0L)
1398 >                startTime = System.nanoTime();
1399 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1400 >                threadAssertTrue(thread.isAlive());
1401 >                fail("timed out waiting for thread to enter wait state");
1402              }
1403 <            catch(InterruptedException success) {
1403 >            Thread.yield();
1404 >        }
1405 >    }
1406 >
1407 >    /**
1408 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1409 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1410 >     */
1411 >    void waitForThreadToEnterWaitState(Thread thread) {
1412 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1413 >    }
1414 >
1415 >    /**
1416 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1417 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1418 >     * and additionally satisfy the given condition.
1419 >     */
1420 >    void waitForThreadToEnterWaitState(
1421 >        Thread thread, Callable<Boolean> waitingForGodot) {
1422 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1423 >    }
1424 >
1425 >    /**
1426 >     * Returns the number of milliseconds since time given by
1427 >     * startNanoTime, which must have been previously returned from a
1428 >     * call to {@link System#nanoTime()}.
1429 >     */
1430 >    static long millisElapsedSince(long startNanoTime) {
1431 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1432 >    }
1433 >
1434 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1435 > //         long startTime = System.nanoTime();
1436 > //         try {
1437 > //             r.run();
1438 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1439 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1440 > //             throw new AssertionFailedError("did not return promptly");
1441 > //     }
1442 >
1443 > //     void assertTerminatesPromptly(Runnable r) {
1444 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1445 > //     }
1446 >
1447 >    /**
1448 >     * Checks that timed f.get() returns the expected value, and does not
1449 >     * wait for the timeout to elapse before returning.
1450 >     */
1451 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1452 >        long startTime = System.nanoTime();
1453 >        try {
1454 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1455 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1456 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1457 >            throw new AssertionFailedError("timed get did not return promptly");
1458 >    }
1459 >
1460 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1461 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1462 >    }
1463 >
1464 >    /**
1465 >     * Returns a new started daemon Thread running the given runnable.
1466 >     */
1467 >    Thread newStartedThread(Runnable runnable) {
1468 >        Thread t = new Thread(runnable);
1469 >        t.setDaemon(true);
1470 >        t.start();
1471 >        return t;
1472 >    }
1473 >
1474 >    /**
1475 >     * Waits for the specified time (in milliseconds) for the thread
1476 >     * to terminate (using {@link Thread#join(long)}), else interrupts
1477 >     * the thread (in the hope that it may terminate later) and fails.
1478 >     */
1479 >    void awaitTermination(Thread t, long timeoutMillis) {
1480 >        try {
1481 >            t.join(timeoutMillis);
1482 >        } catch (InterruptedException fail) {
1483 >            threadUnexpectedException(fail);
1484 >        } finally {
1485 >            if (t.getState() != Thread.State.TERMINATED) {
1486 >                t.interrupt();
1487 >                threadFail("timed out waiting for thread to terminate");
1488              }
1489          }
1490      }
1491  
1492 <    class SmallRunnable implements Runnable {
1493 <        public void run() {
1492 >    /**
1493 >     * Waits for LONG_DELAY_MS milliseconds for the thread to
1494 >     * terminate (using {@link Thread#join(long)}), else interrupts
1495 >     * the thread (in the hope that it may terminate later) and fails.
1496 >     */
1497 >    void awaitTermination(Thread t) {
1498 >        awaitTermination(t, LONG_DELAY_MS);
1499 >    }
1500 >
1501 >    // Some convenient Runnable classes
1502 >
1503 >    public abstract class CheckedRunnable implements Runnable {
1504 >        protected abstract void realRun() throws Throwable;
1505 >
1506 >        public final void run() {
1507              try {
1508 <                Thread.sleep(SMALL_DELAY_MS);
1509 <            }
1510 <            catch(Exception e) {
362 <                threadUnexpectedException();
1508 >                realRun();
1509 >            } catch (Throwable fail) {
1510 >                threadUnexpectedException(fail);
1511              }
1512          }
1513      }
1514  
1515 <    class SmallPossiblyInterruptedRunnable implements Runnable {
1516 <        public void run() {
1515 >    public abstract class RunnableShouldThrow implements Runnable {
1516 >        protected abstract void realRun() throws Throwable;
1517 >
1518 >        final Class<?> exceptionClass;
1519 >
1520 >        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1521 >            this.exceptionClass = exceptionClass;
1522 >        }
1523 >
1524 >        public final void run() {
1525              try {
1526 <                Thread.sleep(SMALL_DELAY_MS);
1527 <            }
1528 <            catch(Exception e) {
1526 >                realRun();
1527 >                threadShouldThrow(exceptionClass.getSimpleName());
1528 >            } catch (Throwable t) {
1529 >                if (! exceptionClass.isInstance(t))
1530 >                    threadUnexpectedException(t);
1531              }
1532          }
1533      }
1534  
1535 <    class SmallCallable implements Callable {
1536 <        public Object call() {
1535 >    public abstract class ThreadShouldThrow extends Thread {
1536 >        protected abstract void realRun() throws Throwable;
1537 >
1538 >        final Class<?> exceptionClass;
1539 >
1540 >        <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1541 >            this.exceptionClass = exceptionClass;
1542 >        }
1543 >
1544 >        public final void run() {
1545              try {
1546 <                Thread.sleep(SMALL_DELAY_MS);
1546 >                realRun();
1547 >                threadShouldThrow(exceptionClass.getSimpleName());
1548 >            } catch (Throwable t) {
1549 >                if (! exceptionClass.isInstance(t))
1550 >                    threadUnexpectedException(t);
1551              }
382            catch(Exception e) {
383                threadUnexpectedException();
384            }
385            return Boolean.TRUE;
1552          }
1553      }
1554  
1555 <    class SmallInterruptedRunnable implements Runnable {
1556 <        public void run() {
1555 >    public abstract class CheckedInterruptedRunnable implements Runnable {
1556 >        protected abstract void realRun() throws Throwable;
1557 >
1558 >        public final void run() {
1559              try {
1560 <                Thread.sleep(SMALL_DELAY_MS);
1561 <                threadShouldThrow();
1562 <            }
1563 <            catch(InterruptedException success) {
1560 >                realRun();
1561 >                threadShouldThrow("InterruptedException");
1562 >            } catch (InterruptedException success) {
1563 >                threadAssertFalse(Thread.interrupted());
1564 >            } catch (Throwable fail) {
1565 >                threadUnexpectedException(fail);
1566              }
1567          }
1568      }
1569  
1570 +    public abstract class CheckedCallable<T> implements Callable<T> {
1571 +        protected abstract T realCall() throws Throwable;
1572  
1573 <    class MediumRunnable implements Runnable {
402 <        public void run() {
1573 >        public final T call() {
1574              try {
1575 <                Thread.sleep(MEDIUM_DELAY_MS);
1576 <            }
1577 <            catch(Exception e) {
1578 <                threadUnexpectedException();
1575 >                return realCall();
1576 >            } catch (Throwable fail) {
1577 >                threadUnexpectedException(fail);
1578 >                return null;
1579              }
1580          }
1581      }
1582  
1583 <    class MediumInterruptedRunnable implements Runnable {
1584 <        public void run() {
1583 >    public abstract class CheckedInterruptedCallable<T>
1584 >        implements Callable<T> {
1585 >        protected abstract T realCall() throws Throwable;
1586 >
1587 >        public final T call() {
1588              try {
1589 <                Thread.sleep(MEDIUM_DELAY_MS);
1590 <                threadShouldThrow();
1591 <            }
1592 <            catch(InterruptedException success) {
1589 >                T result = realCall();
1590 >                threadShouldThrow("InterruptedException");
1591 >                return result;
1592 >            } catch (InterruptedException success) {
1593 >                threadAssertFalse(Thread.interrupted());
1594 >            } catch (Throwable fail) {
1595 >                threadUnexpectedException(fail);
1596              }
1597 +            return null;
1598          }
1599      }
1600  
1601 <    class MediumPossiblyInterruptedRunnable implements Runnable {
1602 <        public void run() {
1601 >    public static class NoOpRunnable implements Runnable {
1602 >        public void run() {}
1603 >    }
1604 >
1605 >    public static class NoOpCallable implements Callable {
1606 >        public Object call() { return Boolean.TRUE; }
1607 >    }
1608 >
1609 >    public static final String TEST_STRING = "a test string";
1610 >
1611 >    public static class StringTask implements Callable<String> {
1612 >        final String value;
1613 >        public StringTask() { this(TEST_STRING); }
1614 >        public StringTask(String value) { this.value = value; }
1615 >        public String call() { return value; }
1616 >    }
1617 >
1618 >    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1619 >        return new CheckedCallable<String>() {
1620 >            protected String realCall() {
1621 >                try {
1622 >                    latch.await();
1623 >                } catch (InterruptedException quittingTime) {}
1624 >                return TEST_STRING;
1625 >            }};
1626 >    }
1627 >
1628 >    public Runnable countDowner(final CountDownLatch latch) {
1629 >        return new CheckedRunnable() {
1630 >            public void realRun() throws InterruptedException {
1631 >                latch.countDown();
1632 >            }};
1633 >    }
1634 >
1635 >    class LatchAwaiter extends CheckedRunnable {
1636 >        static final int NEW = 0;
1637 >        static final int RUNNING = 1;
1638 >        static final int DONE = 2;
1639 >        final CountDownLatch latch;
1640 >        int state = NEW;
1641 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1642 >        public void realRun() throws InterruptedException {
1643 >            state = 1;
1644 >            await(latch);
1645 >            state = 2;
1646 >        }
1647 >    }
1648 >
1649 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1650 >        return new LatchAwaiter(latch);
1651 >    }
1652 >
1653 >    public void await(CountDownLatch latch, long timeoutMillis) {
1654 >        try {
1655 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1656 >                fail("timed out waiting for CountDownLatch for "
1657 >                     + (timeoutMillis/1000) + " sec");
1658 >        } catch (Throwable fail) {
1659 >            threadUnexpectedException(fail);
1660 >        }
1661 >    }
1662 >
1663 >    public void await(CountDownLatch latch) {
1664 >        await(latch, LONG_DELAY_MS);
1665 >    }
1666 >
1667 >    public void await(Semaphore semaphore) {
1668 >        try {
1669 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1670 >                fail("timed out waiting for Semaphore for "
1671 >                     + (LONG_DELAY_MS/1000) + " sec");
1672 >        } catch (Throwable fail) {
1673 >            threadUnexpectedException(fail);
1674 >        }
1675 >    }
1676 >
1677 >    public void await(CyclicBarrier barrier) {
1678 >        try {
1679 >            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1680 >        } catch (Throwable fail) {
1681 >            threadUnexpectedException(fail);
1682 >        }
1683 >    }
1684 >
1685 > //     /**
1686 > //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1687 > //      */
1688 > //     public void await(AtomicBoolean flag) {
1689 > //         await(flag, LONG_DELAY_MS);
1690 > //     }
1691 >
1692 > //     /**
1693 > //      * Spin-waits up to the specified timeout until flag becomes true.
1694 > //      */
1695 > //     public void await(AtomicBoolean flag, long timeoutMillis) {
1696 > //         long startTime = System.nanoTime();
1697 > //         while (!flag.get()) {
1698 > //             if (millisElapsedSince(startTime) > timeoutMillis)
1699 > //                 throw new AssertionFailedError("timed out");
1700 > //             Thread.yield();
1701 > //         }
1702 > //     }
1703 >
1704 >    public static class NPETask implements Callable<String> {
1705 >        public String call() { throw new NullPointerException(); }
1706 >    }
1707 >
1708 >    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1709 >        protected void realRun() {
1710              try {
1711 <                Thread.sleep(MEDIUM_DELAY_MS);
1712 <            }
428 <            catch(InterruptedException success) {
429 <            }
1711 >                delay(SMALL_DELAY_MS);
1712 >            } catch (InterruptedException ok) {}
1713          }
1714      }
1715  
1716 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1717 +        return new CheckedRunnable() {
1718 +            protected void realRun() {
1719 +                try {
1720 +                    delay(timeoutMillis);
1721 +                } catch (InterruptedException ok) {}
1722 +            }};
1723 +    }
1724 +
1725      /**
1726       * For use as ThreadFactory in constructors
1727       */
1728 <    static class SimpleThreadFactory implements ThreadFactory{
1729 <        public Thread newThread(Runnable r){
1728 >    public static class SimpleThreadFactory implements ThreadFactory {
1729 >        public Thread newThread(Runnable r) {
1730              return new Thread(r);
1731 <        }  
1731 >        }
1732 >    }
1733 >
1734 >    public interface TrackedRunnable extends Runnable {
1735 >        boolean isDone();
1736      }
1737  
1738 <    static class TrackedShortRunnable implements Runnable {
1739 <        volatile boolean done = false;
1738 >    public static class TrackedNoOpRunnable implements Runnable {
1739 >        public volatile boolean done = false;
1740          public void run() {
1741 +            done = true;
1742 +        }
1743 +    }
1744 +
1745 +    /**
1746 +     * Analog of CheckedRunnable for RecursiveAction
1747 +     */
1748 +    public abstract class CheckedRecursiveAction extends RecursiveAction {
1749 +        protected abstract void realCompute() throws Throwable;
1750 +
1751 +        @Override protected final void compute() {
1752              try {
1753 <                Thread.sleep(SMALL_DELAY_MS);
1754 <                done = true;
1755 <            } catch(Exception e){
1753 >                realCompute();
1754 >            } catch (Throwable fail) {
1755 >                threadUnexpectedException(fail);
1756              }
1757          }
1758      }
1759  
1760 <    static class TrackedMediumRunnable implements Runnable {
1761 <        volatile boolean done = false;
1762 <        public void run() {
1760 >    /**
1761 >     * Analog of CheckedCallable for RecursiveTask
1762 >     */
1763 >    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1764 >        protected abstract T realCompute() throws Throwable;
1765 >
1766 >        @Override protected final T compute() {
1767              try {
1768 <                Thread.sleep(MEDIUM_DELAY_MS);
1769 <                done = true;
1770 <            } catch(Exception e){
1768 >                return realCompute();
1769 >            } catch (Throwable fail) {
1770 >                threadUnexpectedException(fail);
1771 >                return null;
1772              }
1773          }
1774      }
1775  
1776 <    static class TrackedLongRunnable implements Runnable {
1777 <        volatile boolean done = false;
1778 <        public void run() {
1776 >    /**
1777 >     * For use as RejectedExecutionHandler in constructors
1778 >     */
1779 >    public static class NoOpREHandler implements RejectedExecutionHandler {
1780 >        public void rejectedExecution(Runnable r,
1781 >                                      ThreadPoolExecutor executor) {}
1782 >    }
1783 >
1784 >    /**
1785 >     * A CyclicBarrier that uses timed await and fails with
1786 >     * AssertionFailedErrors instead of throwing checked exceptions.
1787 >     */
1788 >    public static class CheckedBarrier extends CyclicBarrier {
1789 >        public CheckedBarrier(int parties) { super(parties); }
1790 >
1791 >        public int await() {
1792              try {
1793 <                Thread.sleep(LONG_DELAY_MS);
1794 <                done = true;
1795 <            } catch(Exception e){
1793 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1794 >            } catch (TimeoutException timedOut) {
1795 >                throw new AssertionFailedError("timed out");
1796 >            } catch (Exception fail) {
1797 >                AssertionFailedError afe =
1798 >                    new AssertionFailedError("Unexpected exception: " + fail);
1799 >                afe.initCause(fail);
1800 >                throw afe;
1801              }
1802          }
1803      }
1804  
1805 <    static class TrackedNoOpRunnable implements Runnable {
1806 <        volatile boolean done = false;
1807 <        public void run() {
1808 <            done = true;
1805 >    void checkEmpty(BlockingQueue q) {
1806 >        try {
1807 >            assertTrue(q.isEmpty());
1808 >            assertEquals(0, q.size());
1809 >            assertNull(q.peek());
1810 >            assertNull(q.poll());
1811 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1812 >            assertEquals(q.toString(), "[]");
1813 >            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1814 >            assertFalse(q.iterator().hasNext());
1815 >            try {
1816 >                q.element();
1817 >                shouldThrow();
1818 >            } catch (NoSuchElementException success) {}
1819 >            try {
1820 >                q.iterator().next();
1821 >                shouldThrow();
1822 >            } catch (NoSuchElementException success) {}
1823 >            try {
1824 >                q.remove();
1825 >                shouldThrow();
1826 >            } catch (NoSuchElementException success) {}
1827 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1828 >    }
1829 >
1830 >    void assertSerialEquals(Object x, Object y) {
1831 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1832 >    }
1833 >
1834 >    void assertNotSerialEquals(Object x, Object y) {
1835 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1836 >    }
1837 >
1838 >    byte[] serialBytes(Object o) {
1839 >        try {
1840 >            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1841 >            ObjectOutputStream oos = new ObjectOutputStream(bos);
1842 >            oos.writeObject(o);
1843 >            oos.flush();
1844 >            oos.close();
1845 >            return bos.toByteArray();
1846 >        } catch (Throwable fail) {
1847 >            threadUnexpectedException(fail);
1848 >            return new byte[0];
1849 >        }
1850 >    }
1851 >
1852 >    void assertImmutable(final Object o) {
1853 >        if (o instanceof Collection) {
1854 >            assertThrows(
1855 >                UnsupportedOperationException.class,
1856 >                new Runnable() { public void run() {
1857 >                        ((Collection) o).add(null);}});
1858 >        }
1859 >    }
1860 >
1861 >    @SuppressWarnings("unchecked")
1862 >    <T> T serialClone(T o) {
1863 >        try {
1864 >            ObjectInputStream ois = new ObjectInputStream
1865 >                (new ByteArrayInputStream(serialBytes(o)));
1866 >            T clone = (T) ois.readObject();
1867 >            if (o == clone) assertImmutable(o);
1868 >            assertSame(o.getClass(), clone.getClass());
1869 >            return clone;
1870 >        } catch (Throwable fail) {
1871 >            threadUnexpectedException(fail);
1872 >            return null;
1873          }
1874      }
1875  
1876 <    static class TrackedCallable implements Callable {
1877 <        volatile boolean done = false;
1878 <        public Object call() {
1879 <            try {
1880 <                Thread.sleep(SMALL_DELAY_MS);
1881 <                done = true;
1882 <            } catch(Exception e){
1876 >    /**
1877 >     * A version of serialClone that leaves error handling (for
1878 >     * e.g. NotSerializableException) up to the caller.
1879 >     */
1880 >    @SuppressWarnings("unchecked")
1881 >    <T> T serialClonePossiblyFailing(T o)
1882 >        throws ReflectiveOperationException, java.io.IOException {
1883 >        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1884 >        ObjectOutputStream oos = new ObjectOutputStream(bos);
1885 >        oos.writeObject(o);
1886 >        oos.flush();
1887 >        oos.close();
1888 >        ObjectInputStream ois = new ObjectInputStream
1889 >            (new ByteArrayInputStream(bos.toByteArray()));
1890 >        T clone = (T) ois.readObject();
1891 >        if (o == clone) assertImmutable(o);
1892 >        assertSame(o.getClass(), clone.getClass());
1893 >        return clone;
1894 >    }
1895 >
1896 >    /**
1897 >     * If o implements Cloneable and has a public clone method,
1898 >     * returns a clone of o, else null.
1899 >     */
1900 >    @SuppressWarnings("unchecked")
1901 >    <T> T cloneableClone(T o) {
1902 >        if (!(o instanceof Cloneable)) return null;
1903 >        final T clone;
1904 >        try {
1905 >            clone = (T) o.getClass().getMethod("clone").invoke(o);
1906 >        } catch (NoSuchMethodException ok) {
1907 >            return null;
1908 >        } catch (ReflectiveOperationException unexpected) {
1909 >            throw new Error(unexpected);
1910 >        }
1911 >        assertNotSame(o, clone); // not 100% guaranteed by spec
1912 >        assertSame(o.getClass(), clone.getClass());
1913 >        return clone;
1914 >    }
1915 >
1916 >    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1917 >                             Runnable... throwingActions) {
1918 >        for (Runnable throwingAction : throwingActions) {
1919 >            boolean threw = false;
1920 >            try { throwingAction.run(); }
1921 >            catch (Throwable t) {
1922 >                threw = true;
1923 >                if (!expectedExceptionClass.isInstance(t)) {
1924 >                    AssertionFailedError afe =
1925 >                        new AssertionFailedError
1926 >                        ("Expected " + expectedExceptionClass.getName() +
1927 >                         ", got " + t.getClass().getName());
1928 >                    afe.initCause(t);
1929 >                    threadUnexpectedException(afe);
1930 >                }
1931              }
1932 <            return Boolean.TRUE;
1932 >            if (!threw)
1933 >                shouldThrow(expectedExceptionClass.getName());
1934          }
1935      }
1936  
1937 +    public void assertIteratorExhausted(Iterator<?> it) {
1938 +        try {
1939 +            it.next();
1940 +            shouldThrow();
1941 +        } catch (NoSuchElementException success) {}
1942 +        assertFalse(it.hasNext());
1943 +    }
1944 +
1945 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1946 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1947 +    }
1948 +
1949 +    public Runnable runnableThrowing(final RuntimeException ex) {
1950 +        return new Runnable() { public void run() { throw ex; }};
1951 +    }
1952 +
1953 +    /** A reusable thread pool to be shared by tests. */
1954 +    static final ExecutorService cachedThreadPool =
1955 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1956 +                               1000L, MILLISECONDS,
1957 +                               new SynchronousQueue<Runnable>());
1958 +
1959 +    static <T> void shuffle(T[] array) {
1960 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1961 +    }
1962 +
1963 +    // --- Shared assertions for Executor tests ---
1964 +
1965      /**
1966 <     * For use as RejectedExecutionHandler in constructors
1966 >     * Returns maximum number of tasks that can be submitted to given
1967 >     * pool (with bounded queue) before saturation (when submission
1968 >     * throws RejectedExecutionException).
1969       */
1970 <    static class NoOpREHandler implements RejectedExecutionHandler{
1971 <        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor){}
1970 >    static final int saturatedSize(ThreadPoolExecutor pool) {
1971 >        BlockingQueue<Runnable> q = pool.getQueue();
1972 >        return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1973 >    }
1974 >
1975 >    @SuppressWarnings("FutureReturnValueIgnored")
1976 >    void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1977 >        try {
1978 >            e.execute((Runnable) null);
1979 >            shouldThrow();
1980 >        } catch (NullPointerException success) {}
1981 >
1982 >        if (! (e instanceof ExecutorService)) return;
1983 >        ExecutorService es = (ExecutorService) e;
1984 >        try {
1985 >            es.submit((Runnable) null);
1986 >            shouldThrow();
1987 >        } catch (NullPointerException success) {}
1988 >        try {
1989 >            es.submit((Runnable) null, Boolean.TRUE);
1990 >            shouldThrow();
1991 >        } catch (NullPointerException success) {}
1992 >        try {
1993 >            es.submit((Callable) null);
1994 >            shouldThrow();
1995 >        } catch (NullPointerException success) {}
1996 >
1997 >        if (! (e instanceof ScheduledExecutorService)) return;
1998 >        ScheduledExecutorService ses = (ScheduledExecutorService) e;
1999 >        try {
2000 >            ses.schedule((Runnable) null,
2001 >                         randomTimeout(), randomTimeUnit());
2002 >            shouldThrow();
2003 >        } catch (NullPointerException success) {}
2004 >        try {
2005 >            ses.schedule((Callable) null,
2006 >                         randomTimeout(), randomTimeUnit());
2007 >            shouldThrow();
2008 >        } catch (NullPointerException success) {}
2009 >        try {
2010 >            ses.scheduleAtFixedRate((Runnable) null,
2011 >                                    randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2012 >            shouldThrow();
2013 >        } catch (NullPointerException success) {}
2014 >        try {
2015 >            ses.scheduleWithFixedDelay((Runnable) null,
2016 >                                       randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2017 >            shouldThrow();
2018 >        } catch (NullPointerException success) {}
2019 >    }
2020 >
2021 >    void setRejectedExecutionHandler(
2022 >        ThreadPoolExecutor p, RejectedExecutionHandler handler) {
2023 >        p.setRejectedExecutionHandler(handler);
2024 >        assertSame(handler, p.getRejectedExecutionHandler());
2025 >    }
2026 >
2027 >    void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
2028 >        final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
2029 >        final long savedTaskCount = p.getTaskCount();
2030 >        final long savedCompletedTaskCount = p.getCompletedTaskCount();
2031 >        final int savedQueueSize = p.getQueue().size();
2032 >        final boolean stock = (p.getClass().getClassLoader() == null);
2033 >
2034 >        Runnable r = () -> {};
2035 >        Callable<Boolean> c = () -> Boolean.TRUE;
2036 >
2037 >        class Recorder implements RejectedExecutionHandler {
2038 >            public volatile Runnable r = null;
2039 >            public volatile ThreadPoolExecutor p = null;
2040 >            public void reset() { r = null; p = null; }
2041 >            public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
2042 >                assertNull(this.r);
2043 >                assertNull(this.p);
2044 >                this.r = r;
2045 >                this.p = p;
2046 >            }
2047 >        }
2048 >
2049 >        // check custom handler is invoked exactly once per task
2050 >        Recorder recorder = new Recorder();
2051 >        setRejectedExecutionHandler(p, recorder);
2052 >        for (int i = 2; i--> 0; ) {
2053 >            recorder.reset();
2054 >            p.execute(r);
2055 >            if (stock && p.getClass() == ThreadPoolExecutor.class)
2056 >                assertSame(r, recorder.r);
2057 >            assertSame(p, recorder.p);
2058 >
2059 >            recorder.reset();
2060 >            assertFalse(p.submit(r).isDone());
2061 >            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2062 >            assertSame(p, recorder.p);
2063 >
2064 >            recorder.reset();
2065 >            assertFalse(p.submit(r, Boolean.TRUE).isDone());
2066 >            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2067 >            assertSame(p, recorder.p);
2068 >
2069 >            recorder.reset();
2070 >            assertFalse(p.submit(c).isDone());
2071 >            if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2072 >            assertSame(p, recorder.p);
2073 >
2074 >            if (p instanceof ScheduledExecutorService) {
2075 >                ScheduledExecutorService s = (ScheduledExecutorService) p;
2076 >                ScheduledFuture<?> future;
2077 >
2078 >                recorder.reset();
2079 >                future = s.schedule(r, randomTimeout(), randomTimeUnit());
2080 >                assertFalse(future.isDone());
2081 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2082 >                assertSame(p, recorder.p);
2083 >
2084 >                recorder.reset();
2085 >                future = s.schedule(c, randomTimeout(), randomTimeUnit());
2086 >                assertFalse(future.isDone());
2087 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2088 >                assertSame(p, recorder.p);
2089 >
2090 >                recorder.reset();
2091 >                future = s.scheduleAtFixedRate(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2092 >                assertFalse(future.isDone());
2093 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2094 >                assertSame(p, recorder.p);
2095 >
2096 >                recorder.reset();
2097 >                future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2098 >                assertFalse(future.isDone());
2099 >                if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2100 >                assertSame(p, recorder.p);
2101 >            }
2102 >        }
2103 >
2104 >        // Checking our custom handler above should be sufficient, but
2105 >        // we add some integration tests of standard handlers.
2106 >        final AtomicReference<Thread> thread = new AtomicReference<>();
2107 >        final Runnable setThread = () -> thread.set(Thread.currentThread());
2108 >
2109 >        setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2110 >        try {
2111 >            p.execute(setThread);
2112 >            shouldThrow();
2113 >        } catch (RejectedExecutionException success) {}
2114 >        assertNull(thread.get());
2115 >
2116 >        setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2117 >        p.execute(setThread);
2118 >        assertNull(thread.get());
2119 >
2120 >        setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2121 >        p.execute(setThread);
2122 >        if (p.isShutdown())
2123 >            assertNull(thread.get());
2124 >        else
2125 >            assertSame(Thread.currentThread(), thread.get());
2126 >
2127 >        setRejectedExecutionHandler(p, savedHandler);
2128 >
2129 >        // check that pool was not perturbed by handlers
2130 >        assertEquals(savedTaskCount, p.getTaskCount());
2131 >        assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2132 >        assertEquals(savedQueueSize, p.getQueue().size());
2133      }
500
501    
2134   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines