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.212 by jsr166, Fri Dec 9 04:24:07 2016 UTC vs.
Revision 1.232 by jsr166, Mon May 29 19:15:02 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Written by Doug Lea with assistance from members of JCP JSR-166
3 < * Expert Group and released to the public domain, as explained at
2 > * Written by Doug Lea and Martin Buchholz with assistance from
3 > * members of JCP JSR-166 Expert Group and released to the public
4 > * domain, as explained at
5   * http://creativecommons.org/publicdomain/zero/1.0/
6   * Other contributors include Andrew Wright, Jeffrey Hayes,
7   * Pat Fisher, Mike Judd.
# Line 8 | Line 9
9  
10   /*
11   * @test
12 < * @summary JSR-166 tck tests
13 < * @modules java.base/java.util.concurrent:open
14 < *          java.management
12 > * @summary JSR-166 tck tests, in a number of variations.
13 > *          The first is the conformance testing variant,
14 > *          while others also test implementation details.
15   * @build *
16 < * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
17 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
18 < * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -Djava.util.secureRandomSeed=true JSR166TestCase
16 > * @modules java.management
17 > * @run junit/othervm/timeout=1000 JSR166TestCase
18 > * @run junit/othervm/timeout=1000
19 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
20 > *      --add-opens java.base/java.lang=ALL-UNNAMED
21 > *      -Djsr166.testImplementationDetails=true
22 > *      JSR166TestCase
23 > * @run junit/othervm/timeout=1000
24 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
25 > *      --add-opens java.base/java.lang=ALL-UNNAMED
26 > *      -Djsr166.testImplementationDetails=true
27 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
28 > *      JSR166TestCase
29 > * @run junit/othervm/timeout=1000
30 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
31 > *      --add-opens java.base/java.lang=ALL-UNNAMED
32 > *      -Djsr166.testImplementationDetails=true
33 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
34 > *      -Djava.util.secureRandomSeed=true
35 > *      JSR166TestCase
36 > * @run junit/othervm/timeout=1000/policy=tck.policy
37 > *      --add-opens java.base/java.util.concurrent=ALL-UNNAMED
38 > *      --add-opens java.base/java.lang=ALL-UNNAMED
39 > *      -Djsr166.testImplementationDetails=true
40 > *      JSR166TestCase
41   */
42  
43   import static java.util.concurrent.TimeUnit.MILLISECONDS;
# Line 31 | Line 54 | import java.lang.management.ThreadMXBean
54   import java.lang.reflect.Constructor;
55   import java.lang.reflect.Method;
56   import java.lang.reflect.Modifier;
34 import java.nio.file.Files;
35 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 67 | Line 88 | import java.util.concurrent.SynchronousQ
88   import java.util.concurrent.ThreadFactory;
89   import java.util.concurrent.ThreadLocalRandom;
90   import java.util.concurrent.ThreadPoolExecutor;
91 + import java.util.concurrent.TimeUnit;
92   import java.util.concurrent.TimeoutException;
93   import java.util.concurrent.atomic.AtomicBoolean;
94   import java.util.concurrent.atomic.AtomicReference;
73 import java.util.regex.Matcher;
95   import java.util.regex.Pattern;
96  
97   import junit.framework.AssertionFailedError;
# Line 280 | Line 301 | public class JSR166TestCase extends Test
301  
302   //     public static String cpuModel() {
303   //         try {
304 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
304 > //             java.util.regex.Matcher matcher
305 > //               = Pattern.compile("model name\\s*: (.*)")
306   //                 .matcher(new String(
307 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
307 > //                     java.nio.file.Files.readAllBytes(
308 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
309   //             matcher.find();
310   //             return matcher.group(1);
311   //         } catch (Exception ex) { return null; }
# Line 516 | Line 539 | public class JSR166TestCase extends Test
539                  "DoubleAdderTest",
540                  "ForkJoinPool8Test",
541                  "ForkJoinTask8Test",
542 +                "LinkedBlockingDeque8Test",
543 +                "LinkedBlockingQueue8Test",
544                  "LongAccumulatorTest",
545                  "LongAdderTest",
546                  "SplittableRandomTest",
# Line 538 | Line 563 | public class JSR166TestCase extends Test
563                  "AtomicReference9Test",
564                  "AtomicReferenceArray9Test",
565                  "ExecutorCompletionService9Test",
566 +                "ForkJoinPool9Test",
567              };
568              addNamedTestClasses(suite, java9TestClassNames);
569          }
# Line 548 | Line 574 | public class JSR166TestCase extends Test
574      /** Returns list of junit-style test method names in given class. */
575      public static ArrayList<String> testMethodNames(Class<?> testClass) {
576          Method[] methods = testClass.getDeclaredMethods();
577 <        ArrayList<String> names = new ArrayList<String>(methods.length);
577 >        ArrayList<String> names = new ArrayList<>(methods.length);
578          for (Method method : methods) {
579              if (method.getName().startsWith("test")
580                  && Modifier.isPublic(method.getModifiers())
# Line 613 | Line 639 | public class JSR166TestCase extends Test
639      public static long MEDIUM_DELAY_MS;
640      public static long LONG_DELAY_MS;
641  
642 +    private static final long RANDOM_TIMEOUT;
643 +    private static final long RANDOM_EXPIRED_TIMEOUT;
644 +    private static final TimeUnit RANDOM_TIMEUNIT;
645 +    static {
646 +        ThreadLocalRandom rnd = ThreadLocalRandom.current();
647 +        long[] timeouts = { Long.MIN_VALUE, -1, 0, 1, Long.MAX_VALUE };
648 +        RANDOM_TIMEOUT = timeouts[rnd.nextInt(timeouts.length)];
649 +        RANDOM_EXPIRED_TIMEOUT = timeouts[rnd.nextInt(3)];
650 +        TimeUnit[] timeUnits = TimeUnit.values();
651 +        RANDOM_TIMEUNIT = timeUnits[rnd.nextInt(timeUnits.length)];
652 +    }
653 +
654 +    /**
655 +     * Returns a timeout for use when any value at all will do.
656 +     */
657 +    static long randomTimeout() { return RANDOM_TIMEOUT; }
658 +
659 +    /**
660 +     * Returns a timeout that means "no waiting", i.e. not positive.
661 +     */
662 +    static long randomExpiredTimeout() { return RANDOM_EXPIRED_TIMEOUT; }
663 +
664 +    /**
665 +     * Returns a random non-null TimeUnit.
666 +     */
667 +    static TimeUnit randomTimeUnit() { return RANDOM_TIMEUNIT; }
668 +
669      /**
670       * Returns the shortest timed delay. This can be scaled up for
671       * slow machines using the jsr166.delay.factor system property,
# Line 633 | Line 686 | public class JSR166TestCase extends Test
686          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
687      }
688  
689 +    private static final long TIMEOUT_DELAY_MS
690 +        = (long) (12.0 * Math.cbrt(delayFactor));
691 +
692      /**
693 <     * Returns a timeout in milliseconds to be used in tests that
694 <     * verify that operations block or time out.
693 >     * Returns a timeout in milliseconds to be used in tests that verify
694 >     * that operations block or time out.  We want this to be longer
695 >     * than the OS scheduling quantum, but not too long, so don't scale
696 >     * linearly with delayFactor; we use "crazy" cube root instead.
697       */
698 <    long timeoutMillis() {
699 <        return SHORT_DELAY_MS / 4;
698 >    static long timeoutMillis() {
699 >        return TIMEOUT_DELAY_MS;
700      }
701  
702      /**
# Line 654 | Line 712 | public class JSR166TestCase extends Test
712       * The first exception encountered if any threadAssertXXX method fails.
713       */
714      private final AtomicReference<Throwable> threadFailure
715 <        = new AtomicReference<Throwable>(null);
715 >        = new AtomicReference<>(null);
716  
717      /**
718       * Records an exception so that it can be rethrown later in the test
# Line 1033 | Line 1091 | public class JSR166TestCase extends Test
1091      }
1092  
1093      /**
1094 +     * Checks that thread eventually enters the expected blocked thread state.
1095 +     */
1096 +    void assertThreadBlocks(Thread thread, Thread.State expected) {
1097 +        // always sleep at least 1 ms, with high probability avoiding
1098 +        // transitory states
1099 +        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1100 +            try { delay(1); }
1101 +            catch (InterruptedException fail) {
1102 +                fail("Unexpected InterruptedException");
1103 +            }
1104 +            Thread.State s = thread.getState();
1105 +            if (s == expected)
1106 +                return;
1107 +            else if (s == Thread.State.TERMINATED)
1108 +                fail("Unexpected thread termination");
1109 +        }
1110 +        fail("timed out waiting for thread to enter thread state " + expected);
1111 +    }
1112 +
1113 +    /**
1114       * Checks that thread does not terminate within the default
1115       * millisecond delay of {@code timeoutMillis()}.
1116 +     * TODO: REMOVEME
1117       */
1118      void assertThreadStaysAlive(Thread thread) {
1119          assertThreadStaysAlive(thread, timeoutMillis());
# Line 1042 | Line 1121 | public class JSR166TestCase extends Test
1121  
1122      /**
1123       * Checks that thread does not terminate within the given millisecond delay.
1124 +     * TODO: REMOVEME
1125       */
1126      void assertThreadStaysAlive(Thread thread, long millis) {
1127          try {
# Line 1056 | Line 1136 | public class JSR166TestCase extends Test
1136      /**
1137       * Checks that the threads do not terminate within the default
1138       * millisecond delay of {@code timeoutMillis()}.
1139 +     * TODO: REMOVEME
1140       */
1141      void assertThreadsStayAlive(Thread... threads) {
1142          assertThreadsStayAlive(timeoutMillis(), threads);
# Line 1063 | Line 1144 | public class JSR166TestCase extends Test
1144  
1145      /**
1146       * Checks that the threads do not terminate within the given millisecond delay.
1147 +     * TODO: REMOVEME
1148       */
1149      void assertThreadsStayAlive(long millis, Thread... threads) {
1150          try {
# Line 1113 | Line 1195 | public class JSR166TestCase extends Test
1195      }
1196  
1197      /**
1198 +     * The maximum number of consecutive spurious wakeups we should
1199 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1200 +     */
1201 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1202 +
1203 +    /**
1204       * The number of elements to place in collections, arrays, etc.
1205       */
1206      public static final int SIZE = 20;
# Line 1216 | Line 1304 | public class JSR166TestCase extends Test
1304          }
1305          public void refresh() {}
1306          public String toString() {
1307 <            List<Permission> ps = new ArrayList<Permission>();
1307 >            List<Permission> ps = new ArrayList<>();
1308              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1309                  ps.add(e.nextElement());
1310              return "AdjustablePolicy with permissions " + ps;
# Line 1275 | Line 1363 | public class JSR166TestCase extends Test
1363                  startTime = System.nanoTime();
1364              else if (millisElapsedSince(startTime) > timeoutMillis) {
1365                  threadAssertTrue(thread.isAlive());
1366 <                return;
1366 >                fail("timed out waiting for thread to enter wait state");
1367              }
1368              Thread.yield();
1369          }
1370      }
1371  
1372      /**
1373 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1374 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1373 >     * Spin-waits up to the specified number of milliseconds for the given
1374 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1375 >     * and additionally satisfy the given condition.
1376 >     */
1377 >    void waitForThreadToEnterWaitState(
1378 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1379 >        long startTime = 0L;
1380 >        for (;;) {
1381 >            Thread.State s = thread.getState();
1382 >            if (s == Thread.State.BLOCKED ||
1383 >                s == Thread.State.WAITING ||
1384 >                s == Thread.State.TIMED_WAITING) {
1385 >                try {
1386 >                    if (waitingForGodot.call())
1387 >                        return;
1388 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1389 >            }
1390 >            else if (s == Thread.State.TERMINATED)
1391 >                fail("Unexpected thread termination");
1392 >            else if (startTime == 0L)
1393 >                startTime = System.nanoTime();
1394 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1395 >                threadAssertTrue(thread.isAlive());
1396 >                fail("timed out waiting for thread to enter wait state");
1397 >            }
1398 >            Thread.yield();
1399 >        }
1400 >    }
1401 >
1402 >    /**
1403 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1404 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1405       */
1406      void waitForThreadToEnterWaitState(Thread thread) {
1407          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1408      }
1409  
1410      /**
1411 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1412 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1413 +     * and additionally satisfy the given condition.
1414 +     */
1415 +    void waitForThreadToEnterWaitState(
1416 +        Thread thread, Callable<Boolean> waitingForGodot) {
1417 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1418 +    }
1419 +
1420 +    /**
1421       * Returns the number of milliseconds since time given by
1422       * startNanoTime, which must have been previously returned from a
1423       * call to {@link System#nanoTime()}.
# Line 1541 | Line 1669 | public class JSR166TestCase extends Test
1669          }
1670      }
1671  
1672 +    public void await(CyclicBarrier barrier) {
1673 +        try {
1674 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1675 +        } catch (Throwable fail) {
1676 +            threadUnexpectedException(fail);
1677 +        }
1678 +    }
1679 +
1680   //     /**
1681   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1682   //      */
# Line 1564 | Line 1700 | public class JSR166TestCase extends Test
1700          public String call() { throw new NullPointerException(); }
1701      }
1702  
1567    public static class CallableOne implements Callable<Integer> {
1568        public Integer call() { return one; }
1569    }
1570
1571    public class ShortRunnable extends CheckedRunnable {
1572        protected void realRun() throws Throwable {
1573            delay(SHORT_DELAY_MS);
1574        }
1575    }
1576
1577    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1578        protected void realRun() throws InterruptedException {
1579            delay(SHORT_DELAY_MS);
1580        }
1581    }
1582
1583    public class SmallRunnable extends CheckedRunnable {
1584        protected void realRun() throws Throwable {
1585            delay(SMALL_DELAY_MS);
1586        }
1587    }
1588
1703      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1704          protected void realRun() {
1705              try {
# Line 1594 | Line 1708 | public class JSR166TestCase extends Test
1708          }
1709      }
1710  
1597    public class SmallCallable extends CheckedCallable {
1598        protected Object realCall() throws InterruptedException {
1599            delay(SMALL_DELAY_MS);
1600            return Boolean.TRUE;
1601        }
1602    }
1603
1604    public class MediumRunnable extends CheckedRunnable {
1605        protected void realRun() throws Throwable {
1606            delay(MEDIUM_DELAY_MS);
1607        }
1608    }
1609
1610    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1611        protected void realRun() throws InterruptedException {
1612            delay(MEDIUM_DELAY_MS);
1613        }
1614    }
1615
1711      public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1712          return new CheckedRunnable() {
1713              protected void realRun() {
# Line 1622 | Line 1717 | public class JSR166TestCase extends Test
1717              }};
1718      }
1719  
1625    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1626        protected void realRun() {
1627            try {
1628                delay(MEDIUM_DELAY_MS);
1629            } catch (InterruptedException ok) {}
1630        }
1631    }
1632
1633    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1634        protected void realRun() {
1635            try {
1636                delay(LONG_DELAY_MS);
1637            } catch (InterruptedException ok) {}
1638        }
1639    }
1640
1720      /**
1721       * For use as ThreadFactory in constructors
1722       */
# Line 1651 | Line 1730 | public class JSR166TestCase extends Test
1730          boolean isDone();
1731      }
1732  
1654    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1655        return new TrackedRunnable() {
1656                private volatile boolean done = false;
1657                public boolean isDone() { return done; }
1658                public void run() {
1659                    try {
1660                        delay(timeoutMillis);
1661                        done = true;
1662                    } catch (InterruptedException ok) {}
1663                }
1664            };
1665    }
1666
1667    public static class TrackedShortRunnable implements Runnable {
1668        public volatile boolean done = false;
1669        public void run() {
1670            try {
1671                delay(SHORT_DELAY_MS);
1672                done = true;
1673            } catch (InterruptedException ok) {}
1674        }
1675    }
1676
1677    public static class TrackedSmallRunnable implements Runnable {
1678        public volatile boolean done = false;
1679        public void run() {
1680            try {
1681                delay(SMALL_DELAY_MS);
1682                done = true;
1683            } catch (InterruptedException ok) {}
1684        }
1685    }
1686
1687    public static class TrackedMediumRunnable implements Runnable {
1688        public volatile boolean done = false;
1689        public void run() {
1690            try {
1691                delay(MEDIUM_DELAY_MS);
1692                done = true;
1693            } catch (InterruptedException ok) {}
1694        }
1695    }
1696
1697    public static class TrackedLongRunnable implements Runnable {
1698        public volatile boolean done = false;
1699        public void run() {
1700            try {
1701                delay(LONG_DELAY_MS);
1702                done = true;
1703            } catch (InterruptedException ok) {}
1704        }
1705    }
1706
1733      public static class TrackedNoOpRunnable implements Runnable {
1734          public volatile boolean done = false;
1735          public void run() {
# Line 1711 | Line 1737 | public class JSR166TestCase extends Test
1737          }
1738      }
1739  
1714    public static class TrackedCallable implements Callable {
1715        public volatile boolean done = false;
1716        public Object call() {
1717            try {
1718                delay(SMALL_DELAY_MS);
1719                done = true;
1720            } catch (InterruptedException ok) {}
1721            return Boolean.TRUE;
1722        }
1723    }
1724
1740      /**
1741       * Analog of CheckedRunnable for RecursiveAction
1742       */
# Line 1788 | Line 1803 | public class JSR166TestCase extends Test
1803              assertEquals(0, q.size());
1804              assertNull(q.peek());
1805              assertNull(q.poll());
1806 <            assertNull(q.poll(0, MILLISECONDS));
1806 >            assertNull(q.poll(randomExpiredTimeout(), randomTimeUnit()));
1807              assertEquals(q.toString(), "[]");
1808              assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1809              assertFalse(q.iterator().hasNext());

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines