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