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.198 by jsr166, Wed Jul 27 17:16:23 2016 UTC vs.
Revision 1.229 by jsr166, Sun May 14 03:15:37 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.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 30 | 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;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
57   import java.security.CodeSource;
58   import java.security.Permission;
59   import java.security.PermissionCollection;
# Line 41 | Line 63 | import java.security.ProtectionDomain;
63   import java.security.SecurityPermission;
64   import java.util.ArrayList;
65   import java.util.Arrays;
66 + import java.util.Collection;
67 + import java.util.Collections;
68   import java.util.Date;
69   import java.util.Enumeration;
70   import java.util.Iterator;
# Line 62 | Line 86 | import java.util.concurrent.RejectedExec
86   import java.util.concurrent.Semaphore;
87   import java.util.concurrent.SynchronousQueue;
88   import java.util.concurrent.ThreadFactory;
89 + import java.util.concurrent.ThreadLocalRandom;
90   import java.util.concurrent.ThreadPoolExecutor;
91   import java.util.concurrent.TimeoutException;
92   import java.util.concurrent.atomic.AtomicBoolean;
93   import java.util.concurrent.atomic.AtomicReference;
69 import java.util.regex.Matcher;
94   import java.util.regex.Pattern;
95  
96   import junit.framework.AssertionFailedError;
# Line 276 | Line 300 | public class JSR166TestCase extends Test
300  
301   //     public static String cpuModel() {
302   //         try {
303 < //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
303 > //             java.util.regex.Matcher matcher
304 > //               = Pattern.compile("model name\\s*: (.*)")
305   //                 .matcher(new String(
306 < //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
306 > //                     java.nio.file.Files.readAllBytes(
307 > //                         java.nio.file.Paths.get("/proc/cpuinfo")), "UTF-8"));
308   //             matcher.find();
309   //             return matcher.group(1);
310   //         } catch (Exception ex) { return null; }
# Line 445 | Line 471 | public class JSR166TestCase extends Test
471              AbstractQueuedLongSynchronizerTest.suite(),
472              ArrayBlockingQueueTest.suite(),
473              ArrayDequeTest.suite(),
474 +            ArrayListTest.suite(),
475              AtomicBooleanTest.suite(),
476              AtomicIntegerArrayTest.suite(),
477              AtomicIntegerFieldUpdaterTest.suite(),
# Line 467 | Line 494 | public class JSR166TestCase extends Test
494              CopyOnWriteArrayListTest.suite(),
495              CopyOnWriteArraySetTest.suite(),
496              CountDownLatchTest.suite(),
497 +            CountedCompleterTest.suite(),
498              CyclicBarrierTest.suite(),
499              DelayQueueTest.suite(),
500              EntryTest.suite(),
# Line 495 | Line 523 | public class JSR166TestCase extends Test
523              TreeMapTest.suite(),
524              TreeSetTest.suite(),
525              TreeSubMapTest.suite(),
526 <            TreeSubSetTest.suite());
526 >            TreeSubSetTest.suite(),
527 >            VectorTest.suite());
528  
529          // Java8+ test classes
530          if (atLeastJava8()) {
531              String[] java8TestClassNames = {
532 +                "ArrayDeque8Test",
533                  "Atomic8Test",
534                  "CompletableFutureTest",
535                  "ConcurrentHashMap8Test",
536 <                "CountedCompleterTest",
536 >                "CountedCompleter8Test",
537                  "DoubleAccumulatorTest",
538                  "DoubleAdderTest",
539                  "ForkJoinPool8Test",
540                  "ForkJoinTask8Test",
541 +                "LinkedBlockingDeque8Test",
542 +                "LinkedBlockingQueue8Test",
543                  "LongAccumulatorTest",
544                  "LongAdderTest",
545                  "SplittableRandomTest",
# Line 530 | Line 562 | public class JSR166TestCase extends Test
562                  "AtomicReference9Test",
563                  "AtomicReferenceArray9Test",
564                  "ExecutorCompletionService9Test",
565 +                "ForkJoinPool9Test",
566              };
567              addNamedTestClasses(suite, java9TestClassNames);
568          }
# Line 540 | Line 573 | public class JSR166TestCase extends Test
573      /** Returns list of junit-style test method names in given class. */
574      public static ArrayList<String> testMethodNames(Class<?> testClass) {
575          Method[] methods = testClass.getDeclaredMethods();
576 <        ArrayList<String> names = new ArrayList<String>(methods.length);
576 >        ArrayList<String> names = new ArrayList<>(methods.length);
577          for (Method method : methods) {
578              if (method.getName().startsWith("test")
579                  && Modifier.isPublic(method.getModifiers())
# Line 625 | Line 658 | public class JSR166TestCase extends Test
658          LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
659      }
660  
661 +    private static final long TIMEOUT_DELAY_MS
662 +        = (long) (12.0 * Math.cbrt(delayFactor));
663 +
664      /**
665 <     * Returns a timeout in milliseconds to be used in tests that
666 <     * verify that operations block or time out.
665 >     * Returns a timeout in milliseconds to be used in tests that verify
666 >     * that operations block or time out.  We want this to be longer
667 >     * than the OS scheduling quantum, but not too long, so don't scale
668 >     * linearly with delayFactor; we use "crazy" cube root instead.
669       */
670 <    long timeoutMillis() {
671 <        return SHORT_DELAY_MS / 4;
670 >    static long timeoutMillis() {
671 >        return TIMEOUT_DELAY_MS;
672      }
673  
674      /**
# Line 646 | Line 684 | public class JSR166TestCase extends Test
684       * The first exception encountered if any threadAssertXXX method fails.
685       */
686      private final AtomicReference<Throwable> threadFailure
687 <        = new AtomicReference<Throwable>(null);
687 >        = new AtomicReference<>(null);
688  
689      /**
690       * Records an exception so that it can be rethrown later in the test
# Line 1003 | Line 1041 | public class JSR166TestCase extends Test
1041          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1042          System.err.println("------ stacktrace dump start ------");
1043          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1044 <            String name = info.getThreadName();
1044 >            final String name = info.getThreadName();
1045 >            String lockName;
1046              if ("Signal Dispatcher".equals(name))
1047                  continue;
1048              if ("Reference Handler".equals(name)
1049 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1049 >                && (lockName = info.getLockName()) != null
1050 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1051                  continue;
1052              if ("Finalizer".equals(name)
1053 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1053 >                && (lockName = info.getLockName()) != null
1054 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1055                  continue;
1056              if ("checkForWedgedTest".equals(name))
1057                  continue;
# Line 1022 | Line 1063 | public class JSR166TestCase extends Test
1063      }
1064  
1065      /**
1066 <     * Checks that thread does not terminate within the default
1026 <     * millisecond delay of {@code timeoutMillis()}.
1027 <     */
1028 <    void assertThreadStaysAlive(Thread thread) {
1029 <        assertThreadStaysAlive(thread, timeoutMillis());
1030 <    }
1031 <
1032 <    /**
1033 <     * Checks that thread does not terminate within the given millisecond delay.
1034 <     */
1035 <    void assertThreadStaysAlive(Thread thread, long millis) {
1036 <        try {
1037 <            // No need to optimize the failing case via Thread.join.
1038 <            delay(millis);
1039 <            assertTrue(thread.isAlive());
1040 <        } catch (InterruptedException fail) {
1041 <            threadFail("Unexpected InterruptedException");
1042 <        }
1043 <    }
1044 <
1045 <    /**
1046 <     * Checks that the threads do not terminate within the default
1047 <     * millisecond delay of {@code timeoutMillis()}.
1048 <     */
1049 <    void assertThreadsStayAlive(Thread... threads) {
1050 <        assertThreadsStayAlive(timeoutMillis(), threads);
1051 <    }
1052 <
1053 <    /**
1054 <     * Checks that the threads do not terminate within the given millisecond delay.
1066 >     * Checks that thread eventually enters the expected blocked thread state.
1067       */
1068 <    void assertThreadsStayAlive(long millis, Thread... threads) {
1069 <        try {
1070 <            // No need to optimize the failing case via Thread.join.
1071 <            delay(millis);
1072 <            for (Thread thread : threads)
1073 <                assertTrue(thread.isAlive());
1074 <        } catch (InterruptedException fail) {
1075 <            threadFail("Unexpected InterruptedException");
1068 >    void assertThreadBlocks(Thread thread, Thread.State expected) {
1069 >        // always sleep at least 1 ms, with high probability avoiding
1070 >        // transitory states
1071 >        for (long retries = LONG_DELAY_MS * 3 / 4; retries-->0; ) {
1072 >            try { delay(1); }
1073 >            catch (InterruptedException fail) {
1074 >                fail("Unexpected InterruptedException");
1075 >            }
1076 >            Thread.State s = thread.getState();
1077 >            if (s == expected)
1078 >                return;
1079 >            else if (s == Thread.State.TERMINATED)
1080 >                fail("Unexpected thread termination");
1081          }
1082 +        fail("timed out waiting for thread to enter thread state " + expected);
1083      }
1084  
1085      /**
# Line 1102 | Line 1120 | public class JSR166TestCase extends Test
1120      }
1121  
1122      /**
1123 +     * The maximum number of consecutive spurious wakeups we should
1124 +     * tolerate (from APIs like LockSupport.park) before failing a test.
1125 +     */
1126 +    static final int MAX_SPURIOUS_WAKEUPS = 10;
1127 +
1128 +    /**
1129       * The number of elements to place in collections, arrays, etc.
1130       */
1131      public static final int SIZE = 20;
# Line 1205 | Line 1229 | public class JSR166TestCase extends Test
1229          }
1230          public void refresh() {}
1231          public String toString() {
1232 <            List<Permission> ps = new ArrayList<Permission>();
1232 >            List<Permission> ps = new ArrayList<>();
1233              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1234                  ps.add(e.nextElement());
1235              return "AdjustablePolicy with permissions " + ps;
# Line 1235 | Line 1259 | public class JSR166TestCase extends Test
1259       * Sleeps until the given time has elapsed.
1260       * Throws AssertionFailedError if interrupted.
1261       */
1262 <    void sleep(long millis) {
1262 >    static void sleep(long millis) {
1263          try {
1264              delay(millis);
1265          } catch (InterruptedException fail) {
# Line 1251 | Line 1275 | public class JSR166TestCase extends Test
1275       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1276       */
1277      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1278 <        long startTime = System.nanoTime();
1278 >        long startTime = 0L;
1279          for (;;) {
1280              Thread.State s = thread.getState();
1281              if (s == Thread.State.BLOCKED ||
# Line 1260 | Line 1284 | public class JSR166TestCase extends Test
1284                  return;
1285              else if (s == Thread.State.TERMINATED)
1286                  fail("Unexpected thread termination");
1287 +            else if (startTime == 0L)
1288 +                startTime = System.nanoTime();
1289              else if (millisElapsedSince(startTime) > timeoutMillis) {
1290                  threadAssertTrue(thread.isAlive());
1291 <                return;
1291 >                fail("timed out waiting for thread to enter wait state");
1292 >            }
1293 >            Thread.yield();
1294 >        }
1295 >    }
1296 >
1297 >    /**
1298 >     * Spin-waits up to the specified number of milliseconds for the given
1299 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1300 >     * and additionally satisfy the given condition.
1301 >     */
1302 >    void waitForThreadToEnterWaitState(
1303 >        Thread thread, long timeoutMillis, Callable<Boolean> waitingForGodot) {
1304 >        long startTime = 0L;
1305 >        for (;;) {
1306 >            Thread.State s = thread.getState();
1307 >            if (s == Thread.State.BLOCKED ||
1308 >                s == Thread.State.WAITING ||
1309 >                s == Thread.State.TIMED_WAITING) {
1310 >                try {
1311 >                    if (waitingForGodot.call())
1312 >                        return;
1313 >                } catch (Throwable fail) { threadUnexpectedException(fail); }
1314 >            }
1315 >            else if (s == Thread.State.TERMINATED)
1316 >                fail("Unexpected thread termination");
1317 >            else if (startTime == 0L)
1318 >                startTime = System.nanoTime();
1319 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1320 >                threadAssertTrue(thread.isAlive());
1321 >                fail("timed out waiting for thread to enter wait state");
1322              }
1323              Thread.yield();
1324          }
1325      }
1326  
1327      /**
1328 <     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1329 <     * state: BLOCKED, WAITING, or TIMED_WAITING.
1328 >     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1329 >     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1330       */
1331      void waitForThreadToEnterWaitState(Thread thread) {
1332          waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1333      }
1334  
1335      /**
1336 +     * Spin-waits up to LONG_DELAY_MS milliseconds for the given thread to
1337 +     * enter a wait state: BLOCKED, WAITING, or TIMED_WAITING,
1338 +     * and additionally satisfy the given condition.
1339 +     */
1340 +    void waitForThreadToEnterWaitState(
1341 +        Thread thread, Callable<Boolean> waitingForGodot) {
1342 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS, waitingForGodot);
1343 +    }
1344 +
1345 +    /**
1346       * Returns the number of milliseconds since time given by
1347       * startNanoTime, which must have been previously returned from a
1348       * call to {@link System#nanoTime()}.
# Line 1528 | Line 1594 | public class JSR166TestCase extends Test
1594          }
1595      }
1596  
1597 +    public void await(CyclicBarrier barrier) {
1598 +        try {
1599 +            barrier.await(LONG_DELAY_MS, MILLISECONDS);
1600 +        } catch (Throwable fail) {
1601 +            threadUnexpectedException(fail);
1602 +        }
1603 +    }
1604 +
1605   //     /**
1606   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1607   //      */
# Line 1752 | Line 1826 | public class JSR166TestCase extends Test
1826       * A CyclicBarrier that uses timed await and fails with
1827       * AssertionFailedErrors instead of throwing checked exceptions.
1828       */
1829 <    public class CheckedBarrier extends CyclicBarrier {
1829 >    public static class CheckedBarrier extends CyclicBarrier {
1830          public CheckedBarrier(int parties) { super(parties); }
1831  
1832          public int await() {
# Line 1816 | Line 1890 | public class JSR166TestCase extends Test
1890          }
1891      }
1892  
1893 +    void assertImmutable(final Object o) {
1894 +        if (o instanceof Collection) {
1895 +            assertThrows(
1896 +                UnsupportedOperationException.class,
1897 +                new Runnable() { public void run() {
1898 +                        ((Collection) o).add(null);}});
1899 +        }
1900 +    }
1901 +
1902      @SuppressWarnings("unchecked")
1903      <T> T serialClone(T o) {
1904          try {
1905              ObjectInputStream ois = new ObjectInputStream
1906                  (new ByteArrayInputStream(serialBytes(o)));
1907              T clone = (T) ois.readObject();
1908 +            if (o == clone) assertImmutable(o);
1909              assertSame(o.getClass(), clone.getClass());
1910              return clone;
1911          } catch (Throwable fail) {
# Line 1830 | Line 1914 | public class JSR166TestCase extends Test
1914          }
1915      }
1916  
1917 +    /**
1918 +     * A version of serialClone that leaves error handling (for
1919 +     * e.g. NotSerializableException) up to the caller.
1920 +     */
1921 +    @SuppressWarnings("unchecked")
1922 +    <T> T serialClonePossiblyFailing(T o)
1923 +        throws ReflectiveOperationException, java.io.IOException {
1924 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1925 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1926 +        oos.writeObject(o);
1927 +        oos.flush();
1928 +        oos.close();
1929 +        ObjectInputStream ois = new ObjectInputStream
1930 +            (new ByteArrayInputStream(bos.toByteArray()));
1931 +        T clone = (T) ois.readObject();
1932 +        if (o == clone) assertImmutable(o);
1933 +        assertSame(o.getClass(), clone.getClass());
1934 +        return clone;
1935 +    }
1936 +
1937 +    /**
1938 +     * If o implements Cloneable and has a public clone method,
1939 +     * returns a clone of o, else null.
1940 +     */
1941 +    @SuppressWarnings("unchecked")
1942 +    <T> T cloneableClone(T o) {
1943 +        if (!(o instanceof Cloneable)) return null;
1944 +        final T clone;
1945 +        try {
1946 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1947 +        } catch (NoSuchMethodException ok) {
1948 +            return null;
1949 +        } catch (ReflectiveOperationException unexpected) {
1950 +            throw new Error(unexpected);
1951 +        }
1952 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1953 +        assertSame(o.getClass(), clone.getClass());
1954 +        return clone;
1955 +    }
1956 +
1957      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1958                               Runnable... throwingActions) {
1959          for (Runnable throwingAction : throwingActions) {
# Line 1873 | Line 1997 | public class JSR166TestCase extends Test
1997                                 1000L, MILLISECONDS,
1998                                 new SynchronousQueue<Runnable>());
1999  
2000 +    static <T> void shuffle(T[] array) {
2001 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
2002 +    }
2003   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines