ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
(Generate patch)

Comparing jsr166/src/test/tck/JSR166TestCase.java (file contents):
Revision 1.250 by jsr166, Sat Nov 24 21:48:19 2018 UTC vs.
Revision 1.269 by jsr166, Thu Sep 26 20:48:52 2019 UTC

# Line 49 | Line 49 | import java.io.ByteArrayOutputStream;
49   import java.io.ObjectInputStream;
50   import java.io.ObjectOutputStream;
51   import java.lang.management.ManagementFactory;
52 + import java.lang.management.LockInfo;
53   import java.lang.management.ThreadInfo;
54   import java.lang.management.ThreadMXBean;
55   import java.lang.reflect.Constructor;
# Line 243 | Line 244 | public class JSR166TestCase extends Test
244          }
245      }
246  
247 +    private static final ThreadMXBean THREAD_MXBEAN
248 +        = ManagementFactory.getThreadMXBean();
249 +
250      /**
251       * The scaling factor to apply to standard delays used in tests.
252       * May be initialized from any of:
# Line 284 | Line 288 | public class JSR166TestCase extends Test
288      static volatile TestCase currentTestCase;
289      // static volatile int currentRun = 0;
290      static {
291 <        Runnable checkForWedgedTest = new Runnable() { public void run() {
291 >        Runnable wedgedTestDetector = new Runnable() { public void run() {
292              // Avoid spurious reports with enormous runsPerTest.
293              // A single test case run should never take more than 1 second.
294              // But let's cap it at the high end too ...
295 <            final int timeoutMinutes =
296 <                Math.min(15, Math.max(runsPerTest / 60, 1));
295 >            final int timeoutMinutesMin = Math.max(runsPerTest / 60, 1)
296 >                * Math.max((int) delayFactor, 1);
297 >            final int timeoutMinutes = Math.min(15, timeoutMinutesMin);
298              for (TestCase lastTestCase = currentTestCase;;) {
299                  try { MINUTES.sleep(timeoutMinutes); }
300                  catch (InterruptedException unexpected) { break; }
# Line 309 | Line 314 | public class JSR166TestCase extends Test
314                  }
315                  lastTestCase = currentTestCase;
316              }}};
317 <        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
317 >        Thread thread = new Thread(wedgedTestDetector, "WedgedTestDetector");
318          thread.setDaemon(true);
319          thread.start();
320      }
# Line 353 | Line 358 | public class JSR166TestCase extends Test
358              // Never report first run of any test; treat it as a
359              // warmup run, notably to trigger all needed classloading,
360              if (i > 0)
361 <                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
361 >                System.out.printf("%s: %d%n", toString(), elapsedMillis);
362          }
363      }
364  
# Line 460 | Line 465 | public class JSR166TestCase extends Test
465      public static boolean atLeastJava9()  { return JAVA_CLASS_VERSION >= 53.0; }
466      public static boolean atLeastJava10() { return JAVA_CLASS_VERSION >= 54.0; }
467      public static boolean atLeastJava11() { return JAVA_CLASS_VERSION >= 55.0; }
468 +    public static boolean atLeastJava12() { return JAVA_CLASS_VERSION >= 56.0; }
469 +    public static boolean atLeastJava13() { return JAVA_CLASS_VERSION >= 57.0; }
470 +    public static boolean atLeastJava14() { return JAVA_CLASS_VERSION >= 58.0; }
471 +    public static boolean atLeastJava15() { return JAVA_CLASS_VERSION >= 59.0; }
472 +    public static boolean atLeastJava16() { return JAVA_CLASS_VERSION >= 60.0; }
473 +    public static boolean atLeastJava17() { return JAVA_CLASS_VERSION >= 61.0; }
474  
475      /**
476       * Collects all JSR166 unit tests as one suite.
# Line 511 | Line 522 | public class JSR166TestCase extends Test
522              ExecutorsTest.suite(),
523              ExecutorCompletionServiceTest.suite(),
524              FutureTaskTest.suite(),
525 +            HashtableTest.suite(),
526              LinkedBlockingDequeTest.suite(),
527              LinkedBlockingQueueTest.suite(),
528              LinkedListTest.suite(),
# Line 550 | Line 562 | public class JSR166TestCase extends Test
562                  "HashMapTest",
563                  "LinkedBlockingDeque8Test",
564                  "LinkedBlockingQueue8Test",
565 +                "LinkedHashMapTest",
566                  "LongAccumulatorTest",
567                  "LongAdderTest",
568                  "SplittableRandomTest",
# Line 648 | Line 661 | public class JSR166TestCase extends Test
661      public static long MEDIUM_DELAY_MS;
662      public static long LONG_DELAY_MS;
663  
664 +    /**
665 +     * A delay significantly longer than LONG_DELAY_MS.
666 +     * Use this in a thread that is waited for via awaitTermination(Thread).
667 +     */
668 +    public static long LONGER_DELAY_MS;
669 +
670      private static final long RANDOM_TIMEOUT;
671      private static final long RANDOM_EXPIRED_TIMEOUT;
672      private static final TimeUnit RANDOM_TIMEUNIT;
# Line 676 | Line 695 | public class JSR166TestCase extends Test
695      static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
696  
697      /**
698 +     * Returns a random boolean; a "coin flip".
699 +     */
700 +    static boolean randomBoolean() {
701 +        return ThreadLocalRandom.current().nextBoolean();
702 +    }
703 +
704 +    /**
705 +     * Returns a random element from given choices.
706 +     */
707 +    <T> T chooseRandomly(T... choices) {
708 +        return choices[ThreadLocalRandom.current().nextInt(choices.length)];
709 +    }
710 +
711 +    /**
712       * Returns the shortest timed delay. This can be scaled up for
713       * slow machines using the jsr166.delay.factor system property,
714       * or via jtreg's -timeoutFactor: flag.
# Line 693 | Line 726 | public class JSR166TestCase extends Test
726          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
727          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
728          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
729 +        LONGER_DELAY_MS = 2 * LONG_DELAY_MS;
730      }
731  
732      private static final long TIMEOUT_DELAY_MS
# Line 731 | Line 765 | public class JSR166TestCase extends Test
765       */
766      public void threadRecordFailure(Throwable t) {
767          System.err.println(t);
768 <        dumpTestThreads();
769 <        threadFailure.compareAndSet(null, t);
768 >        if (threadFailure.compareAndSet(null, t))
769 >            dumpTestThreads();
770      }
771  
772      public void setUp() {
# Line 1053 | Line 1087 | public class JSR166TestCase extends Test
1087          }
1088      }
1089  
1090 +    /** Returns true if thread info might be useful in a thread dump. */
1091 +    static boolean threadOfInterest(ThreadInfo info) {
1092 +        final String name = info.getThreadName();
1093 +        String lockName;
1094 +        if (name == null)
1095 +            return true;
1096 +        if (name.equals("Signal Dispatcher")
1097 +            || name.equals("WedgedTestDetector"))
1098 +            return false;
1099 +        if (name.equals("Reference Handler")) {
1100 +            // Reference Handler stacktrace changed in JDK-8156500
1101 +            StackTraceElement[] stackTrace; String methodName;
1102 +            if ((stackTrace = info.getStackTrace()) != null
1103 +                && stackTrace.length > 0
1104 +                && (methodName = stackTrace[0].getMethodName()) != null
1105 +                && methodName.equals("waitForReferencePendingList"))
1106 +                return false;
1107 +            // jdk8 Reference Handler stacktrace
1108 +            if ((lockName = info.getLockName()) != null
1109 +                && lockName.startsWith("java.lang.ref"))
1110 +                return false;
1111 +        }
1112 +        if ((name.equals("Finalizer") || name.equals("Common-Cleaner"))
1113 +            && (lockName = info.getLockName()) != null
1114 +            && lockName.startsWith("java.lang.ref"))
1115 +            return false;
1116 +        if (name.startsWith("ForkJoinPool.commonPool-worker")
1117 +            && (lockName = info.getLockName()) != null
1118 +            && lockName.startsWith("java.util.concurrent.ForkJoinPool"))
1119 +            return false;
1120 +        return true;
1121 +    }
1122 +
1123      /**
1124       * A debugging tool to print stack traces of most threads, as jstack does.
1125       * Uninteresting threads are filtered out.
# Line 1067 | Line 1134 | public class JSR166TestCase extends Test
1134              }
1135          }
1136  
1070        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1137          System.err.println("------ stacktrace dump start ------");
1138 <        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1139 <            final String name = info.getThreadName();
1140 <            String lockName;
1075 <            if ("Signal Dispatcher".equals(name))
1076 <                continue;
1077 <            if ("Reference Handler".equals(name)
1078 <                && (lockName = info.getLockName()) != null
1079 <                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1080 <                continue;
1081 <            if ("Finalizer".equals(name)
1082 <                && (lockName = info.getLockName()) != null
1083 <                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1084 <                continue;
1085 <            if ("checkForWedgedTest".equals(name))
1086 <                continue;
1087 <            System.err.print(info);
1088 <        }
1138 >        for (ThreadInfo info : THREAD_MXBEAN.dumpAllThreads(true, true))
1139 >            if (threadOfInterest(info))
1140 >                System.err.print(info);
1141          System.err.println("------ stacktrace dump end ------");
1142  
1143          if (sm != null) System.setSecurityManager(sm);
# Line 1112 | Line 1164 | public class JSR166TestCase extends Test
1164      }
1165  
1166      /**
1167 +     * Returns the thread's blocker's class name, if any, else null.
1168 +     */
1169 +    String blockerClassName(Thread thread) {
1170 +        ThreadInfo threadInfo; LockInfo lockInfo;
1171 +        if ((threadInfo = THREAD_MXBEAN.getThreadInfo(thread.getId(), 0)) != null
1172 +            && (lockInfo = threadInfo.getLockInfo()) != null)
1173 +            return lockInfo.getClassName();
1174 +        return null;
1175 +    }
1176 +
1177 +    /**
1178       * Checks that future.get times out, with the default timeout of
1179       * {@code timeoutMillis()}.
1180       */
# Line 1358 | Line 1421 | public class JSR166TestCase extends Test
1421      }
1422  
1423      /**
1424 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the current thread to
1425 +     * be interrupted.  Clears the interrupt status before returning.
1426 +     */
1427 +    void awaitInterrupted() {
1428 +        for (long startTime = 0L; !Thread.interrupted(); ) {
1429 +            if (startTime == 0L)
1430 +                startTime = System.nanoTime();
1431 +            else if (millisElapsedSince(startTime) > LONG_DELAY_MS)
1432 +                fail("timed out waiting for thread interrupt");
1433 +            Thread.yield();
1434 +        }
1435 +    }
1436 +
1437 +    /**
1438       * Returns the number of milliseconds since time given by
1439       * startNanoTime, which must have been previously returned from a
1440       * call to {@link System#nanoTime()}.
# Line 1366 | Line 1443 | public class JSR166TestCase extends Test
1443          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1444      }
1445  
1369 //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1370 //         long startTime = System.nanoTime();
1371 //         try {
1372 //             r.run();
1373 //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1374 //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1375 //             throw new AssertionError("did not return promptly");
1376 //     }
1377
1378 //     void assertTerminatesPromptly(Runnable r) {
1379 //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1380 //     }
1381
1446      /**
1447       * Checks that timed f.get() returns the expected value, and does not
1448       * wait for the timeout to elapse before returning.
# Line 1409 | Line 1473 | public class JSR166TestCase extends Test
1473      }
1474  
1475      /**
1476 +     * Returns a new started daemon Thread running the given action,
1477 +     * wrapped in a CheckedRunnable.
1478 +     */
1479 +    Thread newStartedThread(Action action) {
1480 +        return newStartedThread(checkedRunnable(action));
1481 +    }
1482 +
1483 +    /**
1484       * Waits for the specified time (in milliseconds) for the thread
1485       * to terminate (using {@link Thread#join(long)}), else interrupts
1486       * the thread (in the hope that it may terminate later) and fails.
1487       */
1488 <    void awaitTermination(Thread t, long timeoutMillis) {
1488 >    void awaitTermination(Thread thread, long timeoutMillis) {
1489          try {
1490 <            t.join(timeoutMillis);
1490 >            thread.join(timeoutMillis);
1491          } catch (InterruptedException fail) {
1492              threadUnexpectedException(fail);
1493 <        } finally {
1494 <            if (t.getState() != Thread.State.TERMINATED) {
1495 <                t.interrupt();
1496 <                threadFail("timed out waiting for thread to terminate");
1493 >        }
1494 >        if (thread.getState() != Thread.State.TERMINATED) {
1495 >            String detail = String.format(
1496 >                    "timed out waiting for thread to terminate, thread=%s, state=%s" ,
1497 >                    thread, thread.getState());
1498 >            try {
1499 >                threadFail(detail);
1500 >            } finally {
1501 >                // Interrupt thread __after__ having reported its stack trace
1502 >                thread.interrupt();
1503              }
1504          }
1505      }
# Line 1449 | Line 1527 | public class JSR166TestCase extends Test
1527          }
1528      }
1529  
1530 +    Runnable checkedRunnable(Action action) {
1531 +        return new CheckedRunnable() {
1532 +            public void realRun() throws Throwable {
1533 +                action.run();
1534 +            }};
1535 +    }
1536 +
1537      public abstract class ThreadShouldThrow extends Thread {
1538          protected abstract void realRun() throws Throwable;
1539  
# Line 1743 | Line 1828 | public class JSR166TestCase extends Test
1828          }
1829      }
1830  
1831 <    void assertImmutable(final Object o) {
1831 >    void assertImmutable(Object o) {
1832          if (o instanceof Collection) {
1833              assertThrows(
1834                  UnsupportedOperationException.class,
1835 <                new Runnable() { public void run() {
1751 <                        ((Collection) o).add(null);}});
1835 >                () -> ((Collection) o).add(null));
1836          }
1837      }
1838  
# Line 1808 | Line 1892 | public class JSR166TestCase extends Test
1892      }
1893  
1894      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1895 <                             Runnable... throwingActions) {
1896 <        for (Runnable throwingAction : throwingActions) {
1895 >                             Action... throwingActions) {
1896 >        for (Action throwingAction : throwingActions) {
1897              boolean threw = false;
1898              try { throwingAction.run(); }
1899              catch (Throwable t) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines