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