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