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