< prev index next >

test/jdk/java/util/concurrent/tck/JSR166TestCase.java

Print this page
8225490: Miscellaneous changes imported from jsr166 CVS 2019-09
Reviewed-by: martin, alanb


 294 
 295     public JSR166TestCase() { super(); }
 296     public JSR166TestCase(String name) { super(name); }
 297 
 298     /**
 299      * A filter for tests to run, matching strings of the form
 300      * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
 301      * Usefully combined with jsr166.runsPerTest.
 302      */
 303     private static final Pattern methodFilter = methodFilter();
 304 
 305     private static Pattern methodFilter() {
 306         String regex = System.getProperty("jsr166.methodFilter");
 307         return (regex == null) ? null : Pattern.compile(regex);
 308     }
 309 
 310     // Instrumentation to debug very rare, but very annoying hung test runs.
 311     static volatile TestCase currentTestCase;
 312     // static volatile int currentRun = 0;
 313     static {
 314         Runnable checkForWedgedTest = new Runnable() { public void run() {
 315             // Avoid spurious reports with enormous runsPerTest.
 316             // A single test case run should never take more than 1 second.
 317             // But let's cap it at the high end too ...
 318             final int timeoutMinutes =
 319                 Math.min(15, Math.max(runsPerTest / 60, 1));

 320             for (TestCase lastTestCase = currentTestCase;;) {
 321                 try { MINUTES.sleep(timeoutMinutes); }
 322                 catch (InterruptedException unexpected) { break; }
 323                 if (lastTestCase == currentTestCase) {
 324                     System.err.printf(
 325                         "Looks like we're stuck running test: %s%n",
 326                         lastTestCase);
 327 //                     System.err.printf(
 328 //                         "Looks like we're stuck running test: %s (%d/%d)%n",
 329 //                         lastTestCase, currentRun, runsPerTest);
 330 //                     System.err.println("availableProcessors=" +
 331 //                         Runtime.getRuntime().availableProcessors());
 332 //                     System.err.printf("cpu model = %s%n", cpuModel());
 333                     dumpTestThreads();
 334                     // one stack dump is probably enough; more would be spam
 335                     break;
 336                 }
 337                 lastTestCase = currentTestCase;
 338             }}};
 339         Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
 340         thread.setDaemon(true);
 341         thread.start();
 342     }
 343 
 344 //     public static String cpuModel() {
 345 //         try {
 346 //             java.util.regex.Matcher matcher
 347 //               = Pattern.compile("model name\\s*: (.*)")
 348 //                 .matcher(new String(
 349 //                     java.nio.file.Files.readAllBytes(
 350 //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
 351 //             matcher.find();
 352 //             return matcher.group(1);
 353 //         } catch (Exception ex) { return null; }
 354 //     }
 355 
 356     public void runBare() throws Throwable {
 357         currentTestCase = this;
 358         if (methodFilter == null
 359             || methodFilter.matcher(toString()).find())


 363     protected void runTest() throws Throwable {
 364         for (int i = 0; i < runsPerTest; i++) {
 365             // currentRun = i;
 366             if (profileTests)
 367                 runTestProfiled();
 368             else
 369                 super.runTest();
 370         }
 371     }
 372 
 373     protected void runTestProfiled() throws Throwable {
 374         for (int i = 0; i < 2; i++) {
 375             long startTime = System.nanoTime();
 376             super.runTest();
 377             long elapsedMillis = millisElapsedSince(startTime);
 378             if (elapsedMillis < profileThreshold)
 379                 break;
 380             // Never report first run of any test; treat it as a
 381             // warmup run, notably to trigger all needed classloading,
 382             if (i > 0)
 383                 System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
 384         }
 385     }
 386 
 387     /**
 388      * Runs all JSR166 unit tests using junit.textui.TestRunner.
 389      */
 390     public static void main(String[] args) {
 391         main(suite(), args);
 392     }
 393 
 394     static class PithyResultPrinter extends junit.textui.ResultPrinter {
 395         PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
 396         long runTime;
 397         public void startTest(Test test) {}
 398         protected void printHeader(long runTime) {
 399             this.runTime = runTime; // defer printing for later
 400         }
 401         protected void printFooter(TestResult result) {
 402             if (result.wasSuccessful()) {
 403                 getWriter().println("OK (" + result.runCount() + " tests)"


 666             try {
 667                 return (Test)
 668                     Class.forName(name8)
 669                     .getMethod("testSuite", dataClass)
 670                     .invoke(null, data);
 671             } catch (ReflectiveOperationException e) {
 672                 throw new AssertionError(e);
 673             }
 674         } else {
 675             return new TestSuite();
 676         }
 677     }
 678 
 679     // Delays for timing-dependent tests, in milliseconds.
 680 
 681     public static long SHORT_DELAY_MS;
 682     public static long SMALL_DELAY_MS;
 683     public static long MEDIUM_DELAY_MS;
 684     public static long LONG_DELAY_MS;
 685 






 686     private static final long RANDOM_TIMEOUT;
 687     private static final long RANDOM_EXPIRED_TIMEOUT;
 688     private static final TimeUnit RANDOM_TIMEUNIT;
 689     static {
 690         ThreadLocalRandom rnd = ThreadLocalRandom.current();
 691         long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
 692         RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
 693         RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
 694         TimeUnit[] timeUnits = TimeUnit.values();
 695         RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
 696     }
 697 
 698     /**
 699      * Returns a timeout for use when any value at all will do.
 700      */
 701     static long randomTimeout() { return RANDOM_TIMEOUT; }
 702 
 703     /**
 704      * Returns a timeout that means "no waiting", i.e. not positive.
 705      */
 706     static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
 707 
 708     /**
 709      * Returns a random non-null TimeUnit.
 710      */
 711     static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
 712 
 713     /**














 714      * Returns the shortest timed delay. This can be scaled up for
 715      * slow machines using the jsr166.delay.factor system property,
 716      * or via jtreg's -timeoutFactor: flag.
 717      * http://openjdk.java.net/jtreg/command-help.html
 718      */
 719     protected long getShortDelay() {
 720         return (long) (50 * delayFactor);
 721     }
 722 
 723     /**
 724      * Sets delays as multiples of SHORT_DELAY.
 725      */
 726     protected void setDelays() {
 727         SHORT_DELAY_MS = getShortDelay();
 728         SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
 729         MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
 730         LONG_DELAY_MS   = SHORT_DELAY_MS * 200;

 731     }
 732 
 733     private static final long TIMEOUT_DELAY_MS
 734         = (long) (12.0 * Math.cbrt(delayFactor));
 735 
 736     /**
 737      * Returns a timeout in milliseconds to be used in tests that verify
 738      * that operations block or time out.  We want this to be longer
 739      * than the OS scheduling quantum, but not too long, so don't scale
 740      * linearly with delayFactor; we use "crazy" cube root instead.
 741      */
 742     static long timeoutMillis() {
 743         return TIMEOUT_DELAY_MS;
 744     }
 745 
 746     /**
 747      * Returns a new Date instance representing a time at least
 748      * delayMillis milliseconds in the future.
 749      */
 750     Date delayedDate(long delayMillis) {
 751         // Add 1 because currentTimeMillis is known to round into the past.
 752         return new Date(System.currentTimeMillis() + delayMillis + 1);
 753     }
 754 
 755     /**
 756      * The first exception encountered if any threadAssertXXX method fails.
 757      */
 758     private final AtomicReference<Throwable> threadFailure
 759         = new AtomicReference<>(null);
 760 
 761     /**
 762      * Records an exception so that it can be rethrown later in the test
 763      * harness thread, triggering a test case failure.  Only the first
 764      * failure is recorded; subsequent calls to this method from within
 765      * the same test have no effect.
 766      */
 767     public void threadRecordFailure(Throwable t) {
 768         System.err.println(t);

 769         dumpTestThreads();
 770         threadFailure.compareAndSet(null, t);
 771     }
 772 
 773     public void setUp() {
 774         setDelays();
 775     }
 776 
 777     void tearDownFail(String format, Object... args) {
 778         String msg = toString() + ": " + String.format(format, args);
 779         System.err.println(msg);
 780         dumpTestThreads();
 781         throw new AssertionError(msg);
 782     }
 783 
 784     /**
 785      * Extra checks that get done for all test cases.
 786      *
 787      * Triggers test case failure if any thread assertions have failed,
 788      * by rethrowing, in the test harness thread, any exception recorded
 789      * earlier by threadRecordFailure.
 790      *


1071      * necessarily individually slow because they must block.
1072      */
1073     void testInParallel(Action ... actions) {
1074         ExecutorService pool = Executors.newCachedThreadPool();
1075         try (PoolCleaner cleaner = cleaner(pool)) {
1076             ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1077             for (final Action action : actions)
1078                 futures.add(pool.submit(new CheckedRunnable() {
1079                     public void realRun() throws Throwable { action.run();}}));
1080             for (Future<?> future : futures)
1081                 try {
1082                     assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1083                 } catch (ExecutionException ex) {
1084                     threadUnexpectedException(ex.getCause());
1085                 } catch (Exception ex) {
1086                     threadUnexpectedException(ex);
1087                 }
1088         }
1089     }
1090 

































1091     /**
1092      * A debugging tool to print stack traces of most threads, as jstack does.
1093      * Uninteresting threads are filtered out.
1094      */
1095     static void dumpTestThreads() {
1096         SecurityManager sm = System.getSecurityManager();
1097         if (sm != null) {
1098             try {
1099                 System.setSecurityManager(null);
1100             } catch (SecurityException giveUp) {
1101                 return;
1102             }
1103         }
1104 
1105         ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1106         System.err.println("------ stacktrace dump start ------");
1107         for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1108             final String name = info.getThreadName();
1109             String lockName;
1110             if ("Signal Dispatcher".equals(name))
1111                 continue;
1112             if ("Reference Handler".equals(name)
1113                 && (lockName = info.getLockName()) != null
1114                 && lockName.startsWith("java.lang.ref.Reference$Lock"))
1115                 continue;
1116             if ("Finalizer".equals(name)
1117                 && (lockName = info.getLockName()) != null
1118                 && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1119                 continue;
1120             if ("checkForWedgedTest".equals(name))
1121                 continue;
1122             System.err.print(info);
1123         }
1124         System.err.println("------ stacktrace dump end ------");
1125 
1126         if (sm != null) System.setSecurityManager(sm);
1127     }
1128 
1129     /**
1130      * Checks that thread eventually enters the expected blocked thread state.
1131      */
1132     void assertThreadBlocks(Thread thread, Thread.State expected) {
1133         // always sleep at least 1 ms, with high probability avoiding
1134         // transitory states
1135         for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1136             try { delay(1); }
1137             catch (InterruptedException fail) {
1138                 throw new AssertionError("Unexpected InterruptedException", fail);
1139             }
1140             Thread.State s = thread.getState();
1141             if (s == expected)
1142                 return;
1143             else if (s == Thread.State.TERMINATED)


1376 
1377     /**
1378      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1379      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1380      */
1381     void waitForThreadToEnterWaitState(Thread thread) {
1382         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1383     }
1384 
1385     /**
1386      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1387      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1388      * and additionally satisfy the given condition.
1389      */
1390     void waitForThreadToEnterWaitState(Thread thread,
1391                                        Callable<Boolean> waitingForGodot) {
1392         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1393     }
1394 
1395     /**














1396      * Returns the number of milliseconds since time given by
1397      * startNanoTime, which must have been previously returned from a
1398      * call to {@link System#nanoTime()}.
1399      */
1400     static long millisElapsedSince(long startNanoTime) {
1401         return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1402     }
1403 
1404 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1405 //         long startTime = System.nanoTime();
1406 //         try {
1407 //             r.run();
1408 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1409 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1410 //             throw new AssertionError("did not return promptly");
1411 //     }
1412 
1413 //     void assertTerminatesPromptly(Runnable r) {
1414 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1415 //     }
1416 
1417     /**
1418      * Checks that timed f.get() returns the expected value, and does not
1419      * wait for the timeout to elapse before returning.
1420      */
1421     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1422         long startTime = System.nanoTime();
1423         T actual = null;
1424         try {
1425             actual = f.get(timeoutMillis, MILLISECONDS);
1426         } catch (Throwable fail) { threadUnexpectedException(fail); }
1427         assertEquals(expectedValue, actual);
1428         if (millisElapsedSince(startTime) > timeoutMillis/2)
1429             throw new AssertionError("timed get did not return promptly");
1430     }
1431 
1432     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1433         checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1434     }
1435 
1436     /**
1437      * Returns a new started daemon Thread running the given runnable.
1438      */
1439     Thread newStartedThread(Runnable runnable) {
1440         Thread t = new Thread(runnable);
1441         t.setDaemon(true);
1442         t.start();
1443         return t;
1444     }
1445 
1446     /**
1447      * Waits for the specified time (in milliseconds) for the thread
1448      * to terminate (using {@link Thread#join(long)}), else interrupts
1449      * the thread (in the hope that it may terminate later) and fails.
1450      */
1451     void awaitTermination(Thread t, long timeoutMillis) {
1452         try {
1453             t.join(timeoutMillis);
1454         } catch (InterruptedException fail) {
1455             threadUnexpectedException(fail);







1456         } finally {
1457             if (t.getState() != Thread.State.TERMINATED) {
1458                 t.interrupt();
1459                 threadFail("timed out waiting for thread to terminate");
1460             }
1461         }
1462     }
1463 
1464     /**
1465      * Waits for LONG_DELAY_MS milliseconds for the thread to
1466      * terminate (using {@link Thread#join(long)}), else interrupts
1467      * the thread (in the hope that it may terminate later) and fails.
1468      */
1469     void awaitTermination(Thread t) {
1470         awaitTermination(t, LONG_DELAY_MS);
1471     }
1472 
1473     // Some convenient Runnable classes
1474 
1475     public abstract class CheckedRunnable implements Runnable {
1476         protected abstract void realRun() throws Throwable;
1477 
1478         public final void run() {
1479             try {




 294 
 295     public JSR166TestCase() { super(); }
 296     public JSR166TestCase(String name) { super(name); }
 297 
 298     /**
 299      * A filter for tests to run, matching strings of the form
 300      * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
 301      * Usefully combined with jsr166.runsPerTest.
 302      */
 303     private static final Pattern methodFilter = methodFilter();
 304 
 305     private static Pattern methodFilter() {
 306         String regex = System.getProperty("jsr166.methodFilter");
 307         return (regex == null) ? null : Pattern.compile(regex);
 308     }
 309 
 310     // Instrumentation to debug very rare, but very annoying hung test runs.
 311     static volatile TestCase currentTestCase;
 312     // static volatile int currentRun = 0;
 313     static {
 314         Runnable wedgedTestDetector = new Runnable() { public void run() {
 315             // Avoid spurious reports with enormous runsPerTest.
 316             // A single test case run should never take more than 1 second.
 317             // But let's cap it at the high end too ...
 318             final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1)
 319                 * Math.max((int) delayFactor, 1);
 320             final int timeoutMinutes = Math.min(15, timeoutMinutesMin);
 321             for (TestCase lastTestCase = currentTestCase;;) {
 322                 try { MINUTES.sleep(timeoutMinutes); }
 323                 catch (InterruptedException unexpected) { break; }
 324                 if (lastTestCase == currentTestCase) {
 325                     System.err.printf(
 326                         "Looks like we're stuck running test: %s%n",
 327                         lastTestCase);
 328 //                     System.err.printf(
 329 //                         "Looks like we're stuck running test: %s (%d/%d)%n",
 330 //                         lastTestCase, currentRun, runsPerTest);
 331 //                     System.err.println("availableProcessors=" +
 332 //                         Runtime.getRuntime().availableProcessors());
 333 //                     System.err.printf("cpu model = %s%n", cpuModel());
 334                     dumpTestThreads();
 335                     // one stack dump is probably enough; more would be spam
 336                     break;
 337                 }
 338                 lastTestCase = currentTestCase;
 339             }}};
 340         Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector");
 341         thread.setDaemon(true);
 342         thread.start();
 343     }
 344 
 345 //     public static String cpuModel() {
 346 //         try {
 347 //             java.util.regex.Matcher matcher
 348 //               = Pattern.compile("model name\\s*: (.*)")
 349 //                 .matcher(new String(
 350 //                     java.nio.file.Files.readAllBytes(
 351 //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
 352 //             matcher.find();
 353 //             return matcher.group(1);
 354 //         } catch (Exception ex) { return null; }
 355 //     }
 356 
 357     public void runBare() throws Throwable {
 358         currentTestCase = this;
 359         if (methodFilter == null
 360             || methodFilter.matcher(toString()).find())


 364     protected void runTest() throws Throwable {
 365         for (int i = 0; i < runsPerTest; i++) {
 366             // currentRun = i;
 367             if (profileTests)
 368                 runTestProfiled();
 369             else
 370                 super.runTest();
 371         }
 372     }
 373 
 374     protected void runTestProfiled() throws Throwable {
 375         for (int i = 0; i < 2; i++) {
 376             long startTime = System.nanoTime();
 377             super.runTest();
 378             long elapsedMillis = millisElapsedSince(startTime);
 379             if (elapsedMillis < profileThreshold)
 380                 break;
 381             // Never report first run of any test; treat it as a
 382             // warmup run, notably to trigger all needed classloading,
 383             if (i > 0)
 384                 System.out.printf("%s: %d%n", toString(), elapsedMillis);
 385         }
 386     }
 387 
 388     /**
 389      * Runs all JSR166 unit tests using junit.textui.TestRunner.
 390      */
 391     public static void main(String[] args) {
 392         main(suite(), args);
 393     }
 394 
 395     static class PithyResultPrinter extends junit.textui.ResultPrinter {
 396         PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
 397         long runTime;
 398         public void startTest(Test test) {}
 399         protected void printHeader(long runTime) {
 400             this.runTime = runTime; // defer printing for later
 401         }
 402         protected void printFooter(TestResult result) {
 403             if (result.wasSuccessful()) {
 404                 getWriter().println("OK (" + result.runCount() + " tests)"


 667             try {
 668                 return (Test)
 669                     Class.forName(name8)
 670                     .getMethod("testSuite", dataClass)
 671                     .invoke(null, data);
 672             } catch (ReflectiveOperationException e) {
 673                 throw new AssertionError(e);
 674             }
 675         } else {
 676             return new TestSuite();
 677         }
 678     }
 679 
 680     // Delays for timing-dependent tests, in milliseconds.
 681 
 682     public static long SHORT_DELAY_MS;
 683     public static long SMALL_DELAY_MS;
 684     public static long MEDIUM_DELAY_MS;
 685     public static long LONG_DELAY_MS;
 686 
 687     /**
 688      * A delay significantly longer than LONG_DELAY_MS.
 689      * Use this in a thread that is waited for via awaitTermination(Thread).
 690      */
 691     public static long LONGER_DELAY_MS;
 692 
 693     private static final long RANDOM_TIMEOUT;
 694     private static final long RANDOM_EXPIRED_TIMEOUT;
 695     private static final TimeUnit RANDOM_TIMEUNIT;
 696     static {
 697         ThreadLocalRandom rnd = ThreadLocalRandom.current();
 698         long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
 699         RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
 700         RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
 701         TimeUnit[] timeUnits = TimeUnit.values();
 702         RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
 703     }
 704 
 705     /**
 706      * Returns a timeout for use when any value at all will do.
 707      */
 708     static long randomTimeout() { return RANDOM_TIMEOUT; }
 709 
 710     /**
 711      * Returns a timeout that means "no waiting", i.e. not positive.
 712      */
 713     static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
 714 
 715     /**
 716      * Returns a random non-null TimeUnit.
 717      */
 718     static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
 719 
 720     /**
 721      * Returns a random boolean; a "coin flip".
 722      */
 723     static boolean randomBoolean() {
 724         return ThreadLocalRandom.current().nextBoolean();
 725     }
 726 
 727     /**
 728      * Returns a random element from given choices.
 729      */
 730     <T> T chooseRandomly(T... choices) {
 731         return choices[ThreadLocalRandom.current().nextInt(choices.length)];
 732     }
 733 
 734     /**
 735      * Returns the shortest timed delay. This can be scaled up for
 736      * slow machines using the jsr166.delay.factor system property,
 737      * or via jtreg's -timeoutFactor: flag.
 738      * http://openjdk.java.net/jtreg/command-help.html
 739      */
 740     protected long getShortDelay() {
 741         return (long) (50 * delayFactor);
 742     }
 743 
 744     /**
 745      * Sets delays as multiples of SHORT_DELAY.
 746      */
 747     protected void setDelays() {
 748         SHORT_DELAY_MS = getShortDelay();
 749         SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
 750         MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
 751         LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
 752         LONGER_DELAY_MS = 2 * LONG_DELAY_MS;
 753     }
 754 
 755     private static final long TIMEOUT_DELAY_MS
 756         = (long) (12.0 * Math.cbrt(delayFactor));
 757 
 758     /**
 759      * Returns a timeout in milliseconds to be used in tests that verify
 760      * that operations block or time out.  We want this to be longer
 761      * than the OS scheduling quantum, but not too long, so don't scale
 762      * linearly with delayFactor; we use "crazy" cube root instead.
 763      */
 764     static long timeoutMillis() {
 765         return TIMEOUT_DELAY_MS;
 766     }
 767 
 768     /**
 769      * Returns a new Date instance representing a time at least
 770      * delayMillis milliseconds in the future.
 771      */
 772     Date delayedDate(long delayMillis) {
 773         // Add 1 because currentTimeMillis is known to round into the past.
 774         return new Date(System.currentTimeMillis() + delayMillis + 1);
 775     }
 776 
 777     /**
 778      * The first exception encountered if any threadAssertXXX method fails.
 779      */
 780     private final AtomicReference<Throwable> threadFailure
 781         = new AtomicReference<>(null);
 782 
 783     /**
 784      * Records an exception so that it can be rethrown later in the test
 785      * harness thread, triggering a test case failure.  Only the first
 786      * failure is recorded; subsequent calls to this method from within
 787      * the same test have no effect.
 788      */
 789     public void threadRecordFailure(Throwable t) {
 790         System.err.println(t);
 791         if (threadFailure.compareAndSet(null, t))
 792             dumpTestThreads();

 793     }
 794 
 795     public void setUp() {
 796         setDelays();
 797     }
 798 
 799     void tearDownFail(String format, Object... args) {
 800         String msg = toString() + ": " + String.format(format, args);
 801         System.err.println(msg);
 802         dumpTestThreads();
 803         throw new AssertionError(msg);
 804     }
 805 
 806     /**
 807      * Extra checks that get done for all test cases.
 808      *
 809      * Triggers test case failure if any thread assertions have failed,
 810      * by rethrowing, in the test harness thread, any exception recorded
 811      * earlier by threadRecordFailure.
 812      *


1093      * necessarily individually slow because they must block.
1094      */
1095     void testInParallel(Action ... actions) {
1096         ExecutorService pool = Executors.newCachedThreadPool();
1097         try (PoolCleaner cleaner = cleaner(pool)) {
1098             ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
1099             for (final Action action : actions)
1100                 futures.add(pool.submit(new CheckedRunnable() {
1101                     public void realRun() throws Throwable { action.run();}}));
1102             for (Future<?> future : futures)
1103                 try {
1104                     assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
1105                 } catch (ExecutionException ex) {
1106                     threadUnexpectedException(ex.getCause());
1107                 } catch (Exception ex) {
1108                     threadUnexpectedException(ex);
1109                 }
1110         }
1111     }
1112 
1113     /** Returns true if thread info might be useful in a thread dump. */
1114     static boolean threadOfInterest(ThreadInfo info) {
1115         final String name = info.getThreadName();
1116         String lockName;
1117         if (name == null)
1118             return true;
1119         if (name.equals("Signal Dispatcher")
1120             || name.equals("WedgedTestDetector"))
1121             return false;
1122         if (name.equals("Reference Handler")) {
1123             // Reference Handler stacktrace changed in JDK-8156500
1124             StackTraceElement[] stackTrace; String methodName;
1125             if ((stackTrace = info.getStackTrace()) != null
1126                 && stackTrace.length > 0
1127                 && (methodName = stackTrace[0].getMethodName()) != null
1128                 && methodName.equals("waitForReferencePendingList"))
1129                 return false;
1130             // jdk8 Reference Handler stacktrace
1131             if ((lockName = info.getLockName()) != null
1132                 && lockName.startsWith("java.lang.ref"))
1133                 return false;
1134         }
1135         if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
1136             && (lockName = info.getLockName()) != null
1137             && lockName.startsWith("java.lang.ref"))
1138             return false;
1139         if (name.startsWith("ForkJoinPool.commonPool-worker")
1140             && (lockName = info.getLockName()) != null
1141             && lockName.startsWith("java.util.concurrent.ForkJoinPool"))
1142             return false;
1143         return true;
1144     }
1145 
1146     /**
1147      * A debugging tool to print stack traces of most threads, as jstack does.
1148      * Uninteresting threads are filtered out.
1149      */
1150     static void dumpTestThreads() {
1151         SecurityManager sm = System.getSecurityManager();
1152         if (sm != null) {
1153             try {
1154                 System.setSecurityManager(null);
1155             } catch (SecurityException giveUp) {
1156                 return;
1157             }
1158         }
1159 
1160         ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1161         System.err.println("------ stacktrace dump start ------");
1162         for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true))
1163             if (threadOfInterest(info))













1164                 System.err.print(info);

1165         System.err.println("------ stacktrace dump end ------");
1166 
1167         if (sm != null) System.setSecurityManager(sm);
1168     }
1169 
1170     /**
1171      * Checks that thread eventually enters the expected blocked thread state.
1172      */
1173     void assertThreadBlocks(Thread thread, Thread.State expected) {
1174         // always sleep at least 1 ms, with high probability avoiding
1175         // transitory states
1176         for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1177             try { delay(1); }
1178             catch (InterruptedException fail) {
1179                 throw new AssertionError("Unexpected InterruptedException", fail);
1180             }
1181             Thread.State s = thread.getState();
1182             if (s == expected)
1183                 return;
1184             else if (s == Thread.State.TERMINATED)


1417 
1418     /**
1419      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1420      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1421      */
1422     void waitForThreadToEnterWaitState(Thread thread) {
1423         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, null);
1424     }
1425 
1426     /**
1427      * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1428      * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1429      * and additionally satisfy the given condition.
1430      */
1431     void waitForThreadToEnterWaitState(Thread thread,
1432                                        Callable<Boolean> waitingForGodot) {
1433         waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1434     }
1435 
1436     /**
1437      * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1438      * be interrupted.  Clears the interrupt status before returning.
1439      */
1440     void awaitInterrupted() {
1441         for (long startTime = 0L; !Thread.interrupted(); ) {
1442             if (startTime == 0L)
1443                 startTime = System.nanoTime();
1444             else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1445                 fail("timed out waiting for thread interrupt");
1446             Thread.yield();
1447         }
1448     }
1449 
1450     /**
1451      * Returns the number of milliseconds since time given by
1452      * startNanoTime, which must have been previously returned from a
1453      * call to {@link System#nanoTime()}.
1454      */
1455     static long millisElapsedSince(long startNanoTime) {
1456         return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1457     }
1458 













1459     /**
1460      * Checks that timed f.get() returns the expected value, and does not
1461      * wait for the timeout to elapse before returning.
1462      */
1463     <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1464         long startTime = System.nanoTime();
1465         T actual = null;
1466         try {
1467             actual = f.get(timeoutMillis, MILLISECONDS);
1468         } catch (Throwable fail) { threadUnexpectedException(fail); }
1469         assertEquals(expectedValue, actual);
1470         if (millisElapsedSince(startTime) > timeoutMillis/2)
1471             throw new AssertionError("timed get did not return promptly");
1472     }
1473 
1474     <T> void checkTimedGet(Future<T> f, T expectedValue) {
1475         checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1476     }
1477 
1478     /**
1479      * Returns a new started daemon Thread running the given runnable.
1480      */
1481     Thread newStartedThread(Runnable runnable) {
1482         Thread t = new Thread(runnable);
1483         t.setDaemon(true);
1484         t.start();
1485         return t;
1486     }
1487 
1488     /**
1489      * Waits for the specified time (in milliseconds) for the thread
1490      * to terminate (using {@link Thread#join(long)}), else interrupts
1491      * the thread (in the hope that it may terminate later) and fails.
1492      */
1493     void awaitTermination(Thread thread, long timeoutMillis) {
1494         try {
1495             thread.join(timeoutMillis);
1496         } catch (InterruptedException fail) {
1497             threadUnexpectedException(fail);
1498         }
1499         if (thread.getState() != Thread.State.TERMINATED) {
1500             String detail = String.format(
1501                     "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1502                     thread, thread.getState());
1503             try {
1504                 threadFail(detail);
1505             } finally {
1506                 // Interrupt thread __after__ having reported its stack trace
1507                 thread.interrupt();

1508             }
1509         }
1510     }
1511 
1512     /**
1513      * Waits for LONG_DELAY_MS milliseconds for the thread to
1514      * terminate (using {@link Thread#join(long)}), else interrupts
1515      * the thread (in the hope that it may terminate later) and fails.
1516      */
1517     void awaitTermination(Thread t) {
1518         awaitTermination(t, LONG_DELAY_MS);
1519     }
1520 
1521     // Some convenient Runnable classes
1522 
1523     public abstract class CheckedRunnable implements Runnable {
1524         protected abstract void realRun() throws Throwable;
1525 
1526         public final void run() {
1527             try {


< prev index next >