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