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.39 by jsr166, Tue Nov 17 21:51:45 2009 UTC vs.
Revision 1.271 by jsr166, Sat Feb 1 18:52:17 2020 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines