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         T actual = null;
1419         try {
1420             actual = f.get(timeoutMillis, MILLISECONDS);
1421         } catch (Throwable fail) { threadUnexpectedException(fail); }
1422         assertEquals(expectedValue, actual);
1423         if (millisElapsedSince(startTime) > timeoutMillis/2)
1424             throw new AssertionError("timed get did not return promptly");
1425     }
1426 
1427     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1428         checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1429     }
1430 
1431     /**
1432      * Returns a new started daemon Thread running the given runnable.
1433      */
1434     Thread newStartedThread(Runnable runnable) {
1435         Thread t = new Thread(runnable);
1436         t.setDaemon(true);
1437         t.start();
1438         return t;
1439     }
1440 
1441     /**
1442      * Waits for the specified time (in milliseconds) for the thread
1443      * to terminate (using {@link Thread#join(long)}), else interrupts
1444      * the thread (in the hope that it may terminate later) and fails.
1445      */
1446     void awaitTermination(Thread t, long timeoutMillis) {
1447         try {
1448             t.join(timeoutMillis);
1449         } catch (InterruptedException fail) {
1450             threadUnexpectedException(fail);
1451         } finally {
1452             if (t.getState() != Thread.State.TERMINATED) {
1453                 t.interrupt();
1454                 threadFail("timed out waiting for thread to terminate");
1455             }
1456         }
1457     }
1458 
1459     /**
1460      * Waits for LONG_DELAY_MS milliseconds for the thread to
1461      * terminate (using {@link Thread#join(long)}), else interrupts
1462      * the thread (in the hope that it may terminate later) and fails.
1463      */
1464     void awaitTermination(Thread t) {
1465         awaitTermination(t, LONG_DELAY_MS);
1466     }
1467 
1468     // Some convenient Runnable classes
1469 
1470     public abstract class CheckedRunnable implements Runnable {
1471         protected abstract void realRun() throws Throwable;
1472 
1473         public final void run() {
1474             try {
1475                 realRun();
1476             } catch (Throwable fail) {
1477                 threadUnexpectedException(fail);
1478             }
1479         }
1480     }
1481 
1482     public abstract class ThreadShouldThrow extends Thread {
1483         protected abstract void realRun() throws Throwable;
1484 
1485         final Class<?> exceptionClass;
1486 
1487         <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1488             this.exceptionClass = exceptionClass;
1489         }
1490 
1491         public final void run() {
1492             try {
1493                 realRun();
1494                 threadShouldThrow(exceptionClass.getSimpleName());
1495             } catch (Throwable t) {
1496                 if (! exceptionClass.isInstance(t))
1497                     threadUnexpectedException(t);
1498             }
1499         }
1500     }
1501 
1502     public abstract class CheckedInterruptedRunnable implements Runnable {
1503         protected abstract void realRun() throws Throwable;
1504 
1505         public final void run() {
1506             try {
1507                 realRun();
1508                 threadShouldThrow("InterruptedException");
1509             } catch (InterruptedException success) {
1510                 threadAssertFalse(Thread.interrupted());
1511             } catch (Throwable fail) {
1512                 threadUnexpectedException(fail);
1513             }
1514         }
1515     }
1516 
1517     public abstract class CheckedCallable<T> implements Callable<T> {
1518         protected abstract T realCall() throws Throwable;
1519 
1520         public final T call() {
1521             try {
1522                 return realCall();
1523             } catch (Throwable fail) {
1524                 threadUnexpectedException(fail);
1525                 return null;
1526             }
1527         }
1528     }
1529 
1530     public abstract class CheckedInterruptedCallable<T>
1531         implements Callable<T> {
1532         protected abstract T realCall() throws Throwable;
1533 
1534         public final T call() {
1535             try {
1536                 T result = realCall();
1537                 threadShouldThrow("InterruptedException");
1538                 return result;
1539             } catch (InterruptedException success) {
1540                 threadAssertFalse(Thread.interrupted());
1541             } catch (Throwable fail) {
1542                 threadUnexpectedException(fail);
1543             }
1544             return null;
1545         }
1546     }
1547 
1548     public static class NoOpRunnable implements Runnable {
1549         public void run() {}
1550     }
1551 
1552     public static class NoOpCallable implements Callable {
1553         public Object call() { return Boolean.TRUE; }
1554     }
1555 
1556     public static final String TEST_STRING = "a test string";
1557 
1558     public static class StringTask implements Callable<String> {
1559         final String value;
1560         public StringTask() { this(TEST_STRING); }
1561         public StringTask(String value) { this.value = value; }
1562         public String call() { return value; }
1563     }
1564 
1565     public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1566         return new CheckedCallable<String>() {
1567             protected String realCall() {
1568                 try {
1569                     latch.await();
1570                 } catch (InterruptedException quittingTime) {}
1571                 return TEST_STRING;
1572             }};
1573     }
1574 
1575     public Runnable countDowner(final CountDownLatch latch) {
1576         return new CheckedRunnable() {
1577             public void realRun() throws InterruptedException {
1578                 latch.countDown();
1579             }};
1580     }
1581 
1582     class LatchAwaiter extends CheckedRunnable {
1583         static final int NEW = 0;
1584         static final int RUNNING = 1;
1585         static final int DONE = 2;
1586         final CountDownLatch latch;
1587         int state = NEW;
1588         LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1589         public void realRun() throws InterruptedException {
1590             state = 1;
1591             await(latch);
1592             state = 2;
1593         }
1594     }
1595 
1596     public LatchAwaiter awaiter(CountDownLatch latch) {
1597         return new LatchAwaiter(latch);
1598     }
1599 
1600     public void await(CountDownLatch latch, long timeoutMillis) {
1601         boolean timedOut = false;
1602         try {
1603             timedOut = !latch.await(timeoutMillis, MILLISECONDS);
1604         } catch (Throwable fail) {
1605             threadUnexpectedException(fail);
1606         }
1607         if (timedOut)
1608             fail("timed out waiting for CountDownLatch for "
1609                  + (timeoutMillis/1000) + " sec");
1610     }
1611 
1612     public void await(CountDownLatch latch) {
1613         await(latch, LONG_DELAY_MS);
1614     }
1615 
1616     public void await(Semaphore semaphore) {
1617         boolean timedOut = false;
1618         try {
1619             timedOut = !semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS);
1620         } catch (Throwable fail) {
1621             threadUnexpectedException(fail);
1622         }
1623         if (timedOut)
1624             fail("timed out waiting for Semaphore for "
1625                  + (LONG_DELAY_MS/1000) + " sec");
1626     }
1627 
1628     public void await(CyclicBarrier barrier) {
1629         try {
1630             barrier.await(LONG_DELAY_MS, MILLISECONDS);
1631         } catch (Throwable fail) {
1632             threadUnexpectedException(fail);
1633         }
1634     }
1635 
1636 //     /**
1637 //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1638 //      */
1639 //     public void await(AtomicBoolean flag) {
1640 //         await(flag, LONG_DELAY_MS);
1641 //     }
1642 
1643 //     /**
1644 //      * Spin-waits up to the specified timeout until flag becomes true.
1645 //      */
1646 //     public void await(AtomicBoolean flag, long timeoutMillis) {
1647 //         long startTime = System.nanoTime();
1648 //         while (!flag.get()) {
1649 //             if (millisElapsedSince(startTime) > timeoutMillis)
1650 //                 throw new AssertionError("timed out");
1651 //             Thread.yield();
1652 //         }
1653 //     }
1654 
1655     public static class NPETask implements Callable<String> {
1656         public String call() { throw new NullPointerException(); }
1657     }
1658 
1659     public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1660         protected void realRun() {
1661             try {
1662                 delay(SMALL_DELAY_MS);
1663             } catch (InterruptedException ok) {}
1664         }
1665     }
1666 
1667     public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1668         return new CheckedRunnable() {
1669             protected void realRun() {
1670                 try {
1671                     delay(timeoutMillis);
1672                 } catch (InterruptedException ok) {}
1673             }};
1674     }
1675 
1676     /**
1677      * For use as ThreadFactory in constructors
1678      */
1679     public static class SimpleThreadFactory implements ThreadFactory {
1680         public Thread newThread(Runnable r) {
1681             return new Thread(r);
1682         }
1683     }
1684 
1685     public interface TrackedRunnable extends Runnable {
1686         boolean isDone();
1687     }
1688 
1689     public static class TrackedNoOpRunnable implements Runnable {
1690         public volatile boolean done = false;
1691         public void run() {
1692             done = true;
1693         }
1694     }
1695 
1696     /**
1697      * Analog of CheckedRunnable for RecursiveAction
1698      */
1699     public abstract class CheckedRecursiveAction extends RecursiveAction {
1700         protected abstract void realCompute() throws Throwable;
1701 
1702         @Override protected final void compute() {
1703             try {
1704                 realCompute();
1705             } catch (Throwable fail) {
1706                 threadUnexpectedException(fail);
1707             }
1708         }
1709     }
1710 
1711     /**
1712      * Analog of CheckedCallable for RecursiveTask
1713      */
1714     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1715         protected abstract T realCompute() throws Throwable;
1716 
1717         @Override protected final T compute() {
1718             try {
1719                 return realCompute();
1720             } catch (Throwable fail) {
1721                 threadUnexpectedException(fail);
1722                 return null;
1723             }
1724         }
1725     }
1726 
1727     /**
1728      * For use as RejectedExecutionHandler in constructors
1729      */
1730     public static class NoOpREHandler implements RejectedExecutionHandler {
1731         public void rejectedExecution(Runnable r,
1732                                       ThreadPoolExecutor executor) {}
1733     }
1734 
1735     /**
1736      * A CyclicBarrier that uses timed await and fails with
1737      * AssertionErrors instead of throwing checked exceptions.
1738      */
1739     public static class CheckedBarrier extends CyclicBarrier {
1740         public CheckedBarrier(int parties) { super(parties); }
1741 
1742         public int await() {
1743             try {
1744                 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1745             } catch (TimeoutException timedOut) {
1746                 throw new AssertionError("timed out");
1747             } catch (Exception fail) {
1748                 throw new AssertionError("Unexpected exception: " + fail, fail);
1749             }
1750         }
1751     }
1752 
1753     void checkEmpty(BlockingQueue q) {
1754         try {
1755             assertTrue(q.isEmpty());
1756             assertEquals(0, q.size());
1757             assertNull(q.peek());
1758             assertNull(q.poll());
1759             assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1760             assertEquals(q.toString(), "[]");
1761             assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1762             assertFalse(q.iterator().hasNext());
1763             try {
1764                 q.element();
1765                 shouldThrow();
1766             } catch (NoSuchElementException success) {}
1767             try {
1768                 q.iterator().next();
1769                 shouldThrow();
1770             } catch (NoSuchElementException success) {}
1771             try {
1772                 q.remove();
1773                 shouldThrow();
1774             } catch (NoSuchElementException success) {}
1775         } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1776     }
1777 
1778     void assertSerialEquals(Object x, Object y) {
1779         assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1780     }
1781 
1782     void assertNotSerialEquals(Object x, Object y) {
1783         assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1784     }
1785 
1786     byte[] serialBytes(Object o) {
1787         try {
1788             ByteArrayOutputStream bos = new ByteArrayOutputStream();
1789             ObjectOutputStream oos = new ObjectOutputStream(bos);
1790             oos.writeObject(o);
1791             oos.flush();
1792             oos.close();
1793             return bos.toByteArray();
1794         } catch (Throwable fail) {
1795             threadUnexpectedException(fail);
1796             return new byte[0];
1797         }
1798     }
1799 
1800     void assertImmutable(final Object o) {
1801         if (o instanceof Collection) {
1802             assertThrows(
1803                 UnsupportedOperationException.class,
1804                 new Runnable() { public void run() {
1805                         ((Collection) o).add(null);}});
1806         }
1807     }
1808 
1809     @SuppressWarnings("unchecked")
1810     <T> T serialClone(T o) {
1811         T clone = null;
1812         try {
1813             ObjectInputStream ois = new ObjectInputStream
1814                 (new ByteArrayInputStream(serialBytes(o)));
1815             clone = (T) ois.readObject();
1816         } catch (Throwable fail) {
1817             threadUnexpectedException(fail);
1818         }
1819         if (o == clone) assertImmutable(o);
1820         else assertSame(o.getClass(), clone.getClass());
1821         return clone;
1822     }
1823 
1824     /**
1825      * A version of serialClone that leaves error handling (for
1826      * e.g. NotSerializableException) up to the caller.
1827      */
1828     @SuppressWarnings("unchecked")
1829     <T> T serialClonePossiblyFailing(T o)
1830         throws ReflectiveOperationException, java.io.IOException {
1831         ByteArrayOutputStream bos = new ByteArrayOutputStream();
1832         ObjectOutputStream oos = new ObjectOutputStream(bos);
1833         oos.writeObject(o);
1834         oos.flush();
1835         oos.close();
1836         ObjectInputStream ois = new ObjectInputStream
1837             (new ByteArrayInputStream(bos.toByteArray()));
1838         T clone = (T) ois.readObject();
1839         if (o == clone) assertImmutable(o);
1840         else assertSame(o.getClass(), clone.getClass());
1841         return clone;
1842     }
1843 
1844     /**
1845      * If o implements Cloneable and has a public clone method,
1846      * returns a clone of o, else null.
1847      */
1848     @SuppressWarnings("unchecked")
1849     <T> T cloneableClone(T o) {
1850         if (!(o instanceof Cloneable)) return null;
1851         final T clone;
1852         try {
1853             clone = (T) o.getClass().getMethod("clone").invoke(o);
1854         } catch (NoSuchMethodException ok) {
1855             return null;
1856         } catch (ReflectiveOperationException unexpected) {
1857             throw new Error(unexpected);
1858         }
1859         assertNotSame(o, clone); // not 100% guaranteed by spec
1860         assertSame(o.getClass(), clone.getClass());
1861         return clone;
1862     }
1863 
1864     public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1865                              Runnable... throwingActions) {
1866         for (Runnable throwingAction : throwingActions) {
1867             boolean threw = false;
1868             try { throwingAction.run(); }
1869             catch (Throwable t) {
1870                 threw = true;
1871                 if (!expectedExceptionClass.isInstance(t))
1872                     throw new AssertionError(
1873                             "Expected " + expectedExceptionClass.getName() +
1874                             ", got " + t.getClass().getName(),
1875                             t);
1876             }
1877             if (!threw)
1878                 shouldThrow(expectedExceptionClass.getName());
1879         }
1880     }
1881 
1882     public void assertIteratorExhausted(Iterator<?> it) {
1883         try {
1884             it.next();
1885             shouldThrow();
1886         } catch (NoSuchElementException success) {}
1887         assertFalse(it.hasNext());
1888     }
1889 
1890     public <T> Callable<T> callableThrowing(final Exception ex) {
1891         return new Callable<T>() { public T call() throws Exception { throw ex; }};
1892     }
1893 
1894     public Runnable runnableThrowing(final RuntimeException ex) {
1895         return new Runnable() { public void run() { throw ex; }};
1896     }
1897 
1898     /** A reusable thread pool to be shared by tests. */
1899     static final ExecutorService cachedThreadPool =
1900         new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1901                                1000L, MILLISECONDS,
1902                                new SynchronousQueue<Runnable>());
1903 
1904     static <T> void shuffle(T[] array) {
1905         Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1906     }
1907 
1908     /**
1909      * Returns the same String as would be returned by {@link
1910      * Object#toString}, whether or not the given object's class
1911      * overrides toString().
1912      *
1913      * @see System#identityHashCode
1914      */
1915     static String identityString(Object x) {
1916         return x.getClass().getName()
1917             + "@" + Integer.toHexString(System.identityHashCode(x));
1918     }
1919 
1920     // --- Shared assertions for Executor tests ---
1921 
1922     /**
1923      * Returns maximum number of tasks that can be submitted to given
1924      * pool (with bounded queue) before saturation (when submission
1925      * throws RejectedExecutionException).
1926      */
1927     static final int saturatedSize(ThreadPoolExecutor pool) {
1928         BlockingQueue<Runnable> q = pool.getQueue();
1929         return pool.getMaximumPoolSize() + q.size() + q.remainingCapacity();
1930     }
1931 
1932     @SuppressWarnings("FutureReturnValueIgnored")
1933     void assertNullTaskSubmissionThrowsNullPointerException(Executor e) {
1934         try {
1935             e.execute((Runnable) null);
1936             shouldThrow();
1937         } catch (NullPointerException success) {}
1938 
1939         if (! (e instanceof ExecutorService)) return;
1940         ExecutorService es = (ExecutorService) e;
1941         try {
1942             es.submit((Runnable) null);
1943             shouldThrow();
1944         } catch (NullPointerException success) {}
1945         try {
1946             es.submit((Runnable) null, Boolean.TRUE);
1947             shouldThrow();
1948         } catch (NullPointerException success) {}
1949         try {
1950             es.submit((Callable) null);
1951             shouldThrow();
1952         } catch (NullPointerException success) {}
1953 
1954         if (! (e instanceof ScheduledExecutorService)) return;
1955         ScheduledExecutorService ses = (ScheduledExecutorService) e;
1956         try {
1957             ses.schedule((Runnable) null,
1958                          randomTimeout(), randomTimeUnit());
1959             shouldThrow();
1960         } catch (NullPointerException success) {}
1961         try {
1962             ses.schedule((Callable) null,
1963                          randomTimeout(), randomTimeUnit());
1964             shouldThrow();
1965         } catch (NullPointerException success) {}
1966         try {
1967             ses.scheduleAtFixedRate((Runnable) null,
1968                                     randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1969             shouldThrow();
1970         } catch (NullPointerException success) {}
1971         try {
1972             ses.scheduleWithFixedDelay((Runnable) null,
1973                                        randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
1974             shouldThrow();
1975         } catch (NullPointerException success) {}
1976     }
1977 
1978     void setRejectedExecutionHandler(
1979         ThreadPoolExecutor p, RejectedExecutionHandler handler) {
1980         p.setRejectedExecutionHandler(handler);
1981         assertSame(handler, p.getRejectedExecutionHandler());
1982     }
1983 
1984     void assertTaskSubmissionsAreRejected(ThreadPoolExecutor p) {
1985         final RejectedExecutionHandler savedHandler = p.getRejectedExecutionHandler();
1986         final long savedTaskCount = p.getTaskCount();
1987         final long savedCompletedTaskCount = p.getCompletedTaskCount();
1988         final int savedQueueSize = p.getQueue().size();
1989         final boolean stock = (p.getClass().getClassLoader() == null);
1990 
1991         Runnable r = () -> {};
1992         Callable<Boolean> c = () -> Boolean.TRUE;
1993 
1994         class Recorder implements RejectedExecutionHandler {
1995             public volatile Runnable r = null;
1996             public volatile ThreadPoolExecutor p = null;
1997             public void reset() { r = null; p = null; }
1998             public void rejectedExecution(Runnable r, ThreadPoolExecutor p) {
1999                 assertNull(this.r);
2000                 assertNull(this.p);
2001                 this.r = r;
2002                 this.p = p;
2003             }
2004         }
2005 
2006         // check custom handler is invoked exactly once per task
2007         Recorder recorder = new Recorder();
2008         setRejectedExecutionHandler(p, recorder);
2009         for (int i = 2; i--> 0; ) {
2010             recorder.reset();
2011             p.execute(r);
2012             if (stock && p.getClass() == ThreadPoolExecutor.class)
2013                 assertSame(r, recorder.r);
2014             assertSame(p, recorder.p);
2015 
2016             recorder.reset();
2017             assertFalse(p.submit(r).isDone());
2018             if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2019             assertSame(p, recorder.p);
2020 
2021             recorder.reset();
2022             assertFalse(p.submit(r, Boolean.TRUE).isDone());
2023             if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2024             assertSame(p, recorder.p);
2025 
2026             recorder.reset();
2027             assertFalse(p.submit(c).isDone());
2028             if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2029             assertSame(p, recorder.p);
2030 
2031             if (p instanceof ScheduledExecutorService) {
2032                 ScheduledExecutorService s = (ScheduledExecutorService) p;
2033                 ScheduledFuture<?> future;
2034 
2035                 recorder.reset();
2036                 future = s.schedule(r, 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.schedule(c, randomTimeout(), randomTimeUnit());
2043                 assertFalse(future.isDone());
2044                 if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2045                 assertSame(p, recorder.p);
2046 
2047                 recorder.reset();
2048                 future = s.scheduleAtFixedRate(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                 recorder.reset();
2054                 future = s.scheduleWithFixedDelay(r, randomTimeout(), LONG_DELAY_MS, MILLISECONDS);
2055                 assertFalse(future.isDone());
2056                 if (stock) assertTrue(!((FutureTask) recorder.r).isDone());
2057                 assertSame(p, recorder.p);
2058             }
2059         }
2060 
2061         // Checking our custom handler above should be sufficient, but
2062         // we add some integration tests of standard handlers.
2063         final AtomicReference<Thread> thread = new AtomicReference<>();
2064         final Runnable setThread = () -> thread.set(Thread.currentThread());
2065 
2066         setRejectedExecutionHandler(p, new ThreadPoolExecutor.AbortPolicy());
2067         try {
2068             p.execute(setThread);
2069             shouldThrow();
2070         } catch (RejectedExecutionException success) {}
2071         assertNull(thread.get());
2072 
2073         setRejectedExecutionHandler(p, new ThreadPoolExecutor.DiscardPolicy());
2074         p.execute(setThread);
2075         assertNull(thread.get());
2076 
2077         setRejectedExecutionHandler(p, new ThreadPoolExecutor.CallerRunsPolicy());
2078         p.execute(setThread);
2079         if (p.isShutdown())
2080             assertNull(thread.get());
2081         else
2082             assertSame(Thread.currentThread(), thread.get());
2083 
2084         setRejectedExecutionHandler(p, savedHandler);
2085 
2086         // check that pool was not perturbed by handlers
2087         assertEquals(savedTaskCount, p.getTaskCount());
2088         assertEquals(savedCompletedTaskCount, p.getCompletedTaskCount());
2089         assertEquals(savedQueueSize, p.getQueue().size());
2090     }
2091 
2092     void assertCollectionsEquals(Collection<?> x, Collection<?> y) {
2093         assertEquals(x, y);
2094         assertEquals(y, x);
2095         assertEquals(x.isEmpty(), y.isEmpty());
2096         assertEquals(x.size(), y.size());
2097         if (x instanceof List) {
2098             assertEquals(x.toString(), y.toString());
2099         }
2100         if (x instanceof List || x instanceof Set) {
2101             assertEquals(x.hashCode(), y.hashCode());
2102         }
2103         if (x instanceof List || x instanceof Deque) {
2104             assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2105             assertTrue(Arrays.equals(x.toArray(new Object[0]),
2106                                      y.toArray(new Object[0])));
2107         }
2108     }
2109 
2110     /**
2111      * A weaker form of assertCollectionsEquals which does not insist
2112      * that the two collections satisfy Object#equals(Object), since
2113      * they may use identity semantics as Deques do.
2114      */
2115     void assertCollectionsEquivalent(Collection<?> x, Collection<?> y) {
2116         if (x instanceof List || x instanceof Set)
2117             assertCollectionsEquals(x, y);
2118         else {
2119             assertEquals(x.isEmpty(), y.isEmpty());
2120             assertEquals(x.size(), y.size());
2121             assertEquals(new HashSet(x), new HashSet(y));
2122             if (x instanceof Deque) {
2123                 assertTrue(Arrays.equals(x.toArray(), y.toArray()));
2124                 assertTrue(Arrays.equals(x.toArray(new Object[0]),
2125                                          y.toArray(new Object[0])));
2126             }
2127         }
2128     }
2129 }