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.186 by jsr166, Mon Feb 22 19:43:27 2016 UTC vs.
Revision 1.217 by jsr166, Tue Jan 24 22:57:02 2017 UTC

# Line 8 | Line 8
8  
9   /*
10   * @test
11 < * @summary JSR-166 tck tests
11 > * @summary JSR-166 tck tests (conformance testing mode)
12 > * @build *
13   * @modules java.management
14 + * @run junit/othervm/timeout=1000 JSR166TestCase
15 + */
16 +
17 + /*
18 + * @test
19 + * @summary JSR-166 tck tests (whitebox tests allowed)
20   * @build *
21 < * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
21 > * @modules java.base/java.util.concurrent:open
22 > *          java.management
23 > * @run junit/othervm/timeout=1000
24 > *      -Djsr166.testImplementationDetails=true
25 > *      JSR166TestCase
26 > * @run junit/othervm/timeout=1000
27 > *      -Djsr166.testImplementationDetails=true
28 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=0
29 > *      JSR166TestCase
30 > * @run junit/othervm/timeout=1000
31 > *      -Djsr166.testImplementationDetails=true
32 > *      -Djava.util.concurrent.ForkJoinPool.common.parallelism=1
33 > *      -Djava.util.secureRandomSeed=true
34 > *      JSR166TestCase
35 > * @run junit/othervm/timeout=1000/policy=tck.policy
36 > *      -Djsr166.testImplementationDetails=true
37 > *      JSR166TestCase
38   */
39  
40   import static java.util.concurrent.TimeUnit.MILLISECONDS;
# Line 39 | Line 62 | import java.security.ProtectionDomain;
62   import java.security.SecurityPermission;
63   import java.util.ArrayList;
64   import java.util.Arrays;
65 + import java.util.Collection;
66 + import java.util.Collections;
67   import java.util.Date;
68   import java.util.Enumeration;
69   import java.util.Iterator;
# Line 58 | Line 83 | import java.util.concurrent.RecursiveAct
83   import java.util.concurrent.RecursiveTask;
84   import java.util.concurrent.RejectedExecutionHandler;
85   import java.util.concurrent.Semaphore;
86 + import java.util.concurrent.SynchronousQueue;
87   import java.util.concurrent.ThreadFactory;
88 + import java.util.concurrent.ThreadLocalRandom;
89   import java.util.concurrent.ThreadPoolExecutor;
90   import java.util.concurrent.TimeoutException;
91   import java.util.concurrent.atomic.AtomicBoolean;
# Line 184 | Line 211 | public class JSR166TestCase extends Test
211      private static final int suiteRuns =
212          Integer.getInteger("jsr166.suiteRuns", 1);
213  
214 <    private static float systemPropertyValue(String name, float defaultValue) {
214 >    /**
215 >     * Returns the value of the system property, or NaN if not defined.
216 >     */
217 >    private static float systemPropertyValue(String name) {
218          String floatString = System.getProperty(name);
219          if (floatString == null)
220 <            return defaultValue;
220 >            return Float.NaN;
221          try {
222              return Float.parseFloat(floatString);
223          } catch (NumberFormatException ex) {
# Line 199 | Line 229 | public class JSR166TestCase extends Test
229  
230      /**
231       * The scaling factor to apply to standard delays used in tests.
232 <     */
233 <    private static final float delayFactor =
234 <        systemPropertyValue("jsr166.delay.factor", 1.0f);
235 <
236 <    /**
237 <     * The timeout factor as used in the jtreg test harness.
238 <     * See: http://openjdk.java.net/jtreg/tag-spec.html
239 <     */
240 <    private static final float jtregTestTimeoutFactor
241 <        = systemPropertyValue("test.timeout.factor", 1.0f);
232 >     * May be initialized from any of:
233 >     * - the "jsr166.delay.factor" system property
234 >     * - the "test.timeout.factor" system property (as used by jtreg)
235 >     *   See: http://openjdk.java.net/jtreg/tag-spec.html
236 >     * - hard-coded fuzz factor when using a known slowpoke VM
237 >     */
238 >    private static final float delayFactor = delayFactor();
239 >
240 >    private static float delayFactor() {
241 >        float x;
242 >        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
243 >            return x;
244 >        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
245 >            return x;
246 >        String prop = System.getProperty("java.vm.version");
247 >        if (prop != null && prop.matches(".*debug.*"))
248 >            return 4.0f; // How much slower is fastdebug than product?!
249 >        return 1.0f;
250 >    }
251  
252      public JSR166TestCase() { super(); }
253      public JSR166TestCase(String name) { super(name); }
# Line 430 | Line 469 | public class JSR166TestCase extends Test
469              AbstractQueuedLongSynchronizerTest.suite(),
470              ArrayBlockingQueueTest.suite(),
471              ArrayDequeTest.suite(),
472 +            ArrayListTest.suite(),
473              AtomicBooleanTest.suite(),
474              AtomicIntegerArrayTest.suite(),
475              AtomicIntegerFieldUpdaterTest.suite(),
# Line 452 | Line 492 | public class JSR166TestCase extends Test
492              CopyOnWriteArrayListTest.suite(),
493              CopyOnWriteArraySetTest.suite(),
494              CountDownLatchTest.suite(),
495 +            CountedCompleterTest.suite(),
496              CyclicBarrierTest.suite(),
497              DelayQueueTest.suite(),
498              EntryTest.suite(),
# Line 480 | Line 521 | public class JSR166TestCase extends Test
521              TreeMapTest.suite(),
522              TreeSetTest.suite(),
523              TreeSubMapTest.suite(),
524 <            TreeSubSetTest.suite());
524 >            TreeSubSetTest.suite(),
525 >            VectorTest.suite());
526  
527          // Java8+ test classes
528          if (atLeastJava8()) {
529              String[] java8TestClassNames = {
530 +                "ArrayDeque8Test",
531                  "Atomic8Test",
532                  "CompletableFutureTest",
533                  "ConcurrentHashMap8Test",
534 <                "CountedCompleterTest",
534 >                "CountedCompleter8Test",
535                  "DoubleAccumulatorTest",
536                  "DoubleAdderTest",
537                  "ForkJoinPool8Test",
538                  "ForkJoinTask8Test",
539 +                "LinkedBlockingDeque8Test",
540 +                "LinkedBlockingQueue8Test",
541                  "LongAccumulatorTest",
542                  "LongAdderTest",
543                  "SplittableRandomTest",
544                  "StampedLockTest",
545                  "SubmissionPublisherTest",
546                  "ThreadLocalRandom8Test",
547 +                "TimeUnit8Test",
548              };
549              addNamedTestClasses(suite, java8TestClassNames);
550          }
# Line 506 | Line 552 | public class JSR166TestCase extends Test
552          // Java9+ test classes
553          if (atLeastJava9()) {
554              String[] java9TestClassNames = {
555 <                // Currently empty, but expecting varhandle tests
555 >                "AtomicBoolean9Test",
556 >                "AtomicInteger9Test",
557 >                "AtomicIntegerArray9Test",
558 >                "AtomicLong9Test",
559 >                "AtomicLongArray9Test",
560 >                "AtomicReference9Test",
561 >                "AtomicReferenceArray9Test",
562 >                "ExecutorCompletionService9Test",
563              };
564              addNamedTestClasses(suite, java9TestClassNames);
565          }
# Line 517 | Line 570 | public class JSR166TestCase extends Test
570      /** Returns list of junit-style test method names in given class. */
571      public static ArrayList<String> testMethodNames(Class<?> testClass) {
572          Method[] methods = testClass.getDeclaredMethods();
573 <        ArrayList<String> names = new ArrayList<String>(methods.length);
573 >        ArrayList<String> names = new ArrayList<>(methods.length);
574          for (Method method : methods) {
575              if (method.getName().startsWith("test")
576                  && Modifier.isPublic(method.getModifiers())
# Line 585 | Line 638 | public class JSR166TestCase extends Test
638      /**
639       * Returns the shortest timed delay. This can be scaled up for
640       * slow machines using the jsr166.delay.factor system property,
641 <     * or via jtreg's -timeoutFactor:<val> flag.
641 >     * or via jtreg's -timeoutFactor: flag.
642       * http://openjdk.java.net/jtreg/command-help.html
643       */
644      protected long getShortDelay() {
645 <        return (long) (50 * delayFactor * jtregTestTimeoutFactor);
645 >        return (long) (50 * delayFactor);
646      }
647  
648      /**
# Line 623 | Line 676 | public class JSR166TestCase extends Test
676       * The first exception encountered if any threadAssertXXX method fails.
677       */
678      private final AtomicReference<Throwable> threadFailure
679 <        = new AtomicReference<Throwable>(null);
679 >        = new AtomicReference<>(null);
680  
681      /**
682       * Records an exception so that it can be rethrown later in the test
# Line 933 | Line 986 | public class JSR166TestCase extends Test
986          }
987      }
988  
989 <    /** Like Runnable, but with the freedom to throw anything */
989 >    /**
990 >     * Like Runnable, but with the freedom to throw anything.
991 >     * junit folks had the same idea:
992 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
993 >     */
994      interface Action { public void run() throws Throwable; }
995  
996      /**
# Line 964 | Line 1021 | public class JSR166TestCase extends Test
1021       * Uninteresting threads are filtered out.
1022       */
1023      static void dumpTestThreads() {
1024 +        SecurityManager sm = System.getSecurityManager();
1025 +        if (sm != null) {
1026 +            try {
1027 +                System.setSecurityManager(null);
1028 +            } catch (SecurityException giveUp) {
1029 +                return;
1030 +            }
1031 +        }
1032 +
1033          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1034          System.err.println("------ stacktrace dump start ------");
1035          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1036 <            String name = info.getThreadName();
1036 >            final String name = info.getThreadName();
1037 >            String lockName;
1038              if ("Signal Dispatcher".equals(name))
1039                  continue;
1040              if ("Reference Handler".equals(name)
1041 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1041 >                && (lockName = info.getLockName()) != null
1042 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1043                  continue;
1044              if ("Finalizer".equals(name)
1045 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1045 >                && (lockName = info.getLockName()) != null
1046 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1047                  continue;
1048              if ("checkForWedgedTest".equals(name))
1049                  continue;
1050              System.err.print(info);
1051          }
1052          System.err.println("------ stacktrace dump end ------");
1053 +
1054 +        if (sm != null) System.setSecurityManager(sm);
1055      }
1056  
1057      /**
# Line 1167 | Line 1238 | public class JSR166TestCase extends Test
1238          }
1239          public void refresh() {}
1240          public String toString() {
1241 <            List<Permission> ps = new ArrayList<Permission>();
1241 >            List<Permission> ps = new ArrayList<>();
1242              for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1243                  ps.add(e.nextElement());
1244              return "AdjustablePolicy with permissions " + ps;
# Line 1197 | Line 1268 | public class JSR166TestCase extends Test
1268       * Sleeps until the given time has elapsed.
1269       * Throws AssertionFailedError if interrupted.
1270       */
1271 <    void sleep(long millis) {
1271 >    static void sleep(long millis) {
1272          try {
1273              delay(millis);
1274          } catch (InterruptedException fail) {
# Line 1213 | Line 1284 | public class JSR166TestCase extends Test
1284       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1285       */
1286      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1287 <        long startTime = System.nanoTime();
1287 >        long startTime = 0L;
1288          for (;;) {
1289              Thread.State s = thread.getState();
1290              if (s == Thread.State.BLOCKED ||
# Line 1222 | Line 1293 | public class JSR166TestCase extends Test
1293                  return;
1294              else if (s == Thread.State.TERMINATED)
1295                  fail("Unexpected thread termination");
1296 +            else if (startTime == 0L)
1297 +                startTime = System.nanoTime();
1298              else if (millisElapsedSince(startTime) > timeoutMillis) {
1299                  threadAssertTrue(thread.isAlive());
1300                  return;
# Line 1466 | Line 1539 | public class JSR166TestCase extends Test
1539          return new LatchAwaiter(latch);
1540      }
1541  
1542 <    public void await(CountDownLatch latch) {
1542 >    public void await(CountDownLatch latch, long timeoutMillis) {
1543          try {
1544 <            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1544 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1545                  fail("timed out waiting for CountDownLatch for "
1546 <                     + (LONG_DELAY_MS/1000) + " sec");
1546 >                     + (timeoutMillis/1000) + " sec");
1547          } catch (Throwable fail) {
1548              threadUnexpectedException(fail);
1549          }
1550      }
1551  
1552 +    public void await(CountDownLatch latch) {
1553 +        await(latch, LONG_DELAY_MS);
1554 +    }
1555 +
1556      public void await(Semaphore semaphore) {
1557          try {
1558              if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
# Line 1710 | Line 1787 | public class JSR166TestCase extends Test
1787       * A CyclicBarrier that uses timed await and fails with
1788       * AssertionFailedErrors instead of throwing checked exceptions.
1789       */
1790 <    public class CheckedBarrier extends CyclicBarrier {
1790 >    public static class CheckedBarrier extends CyclicBarrier {
1791          public CheckedBarrier(int parties) { super(parties); }
1792  
1793          public int await() {
# Line 1774 | Line 1851 | public class JSR166TestCase extends Test
1851          }
1852      }
1853  
1854 +    void assertImmutable(final Object o) {
1855 +        if (o instanceof Collection) {
1856 +            assertThrows(
1857 +                UnsupportedOperationException.class,
1858 +                new Runnable() { public void run() {
1859 +                        ((Collection) o).add(null);}});
1860 +        }
1861 +    }
1862 +
1863      @SuppressWarnings("unchecked")
1864      <T> T serialClone(T o) {
1865          try {
1866              ObjectInputStream ois = new ObjectInputStream
1867                  (new ByteArrayInputStream(serialBytes(o)));
1868              T clone = (T) ois.readObject();
1869 +            if (o == clone) assertImmutable(o);
1870              assertSame(o.getClass(), clone.getClass());
1871              return clone;
1872          } catch (Throwable fail) {
# Line 1788 | Line 1875 | public class JSR166TestCase extends Test
1875          }
1876      }
1877  
1878 +    /**
1879 +     * A version of serialClone that leaves error handling (for
1880 +     * e.g. NotSerializableException) up to the caller.
1881 +     */
1882 +    @SuppressWarnings("unchecked")
1883 +    <T> T serialClonePossiblyFailing(T o)
1884 +        throws ReflectiveOperationException, java.io.IOException {
1885 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1886 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1887 +        oos.writeObject(o);
1888 +        oos.flush();
1889 +        oos.close();
1890 +        ObjectInputStream ois = new ObjectInputStream
1891 +            (new ByteArrayInputStream(bos.toByteArray()));
1892 +        T clone = (T) ois.readObject();
1893 +        if (o == clone) assertImmutable(o);
1894 +        assertSame(o.getClass(), clone.getClass());
1895 +        return clone;
1896 +    }
1897 +
1898 +    /**
1899 +     * If o implements Cloneable and has a public clone method,
1900 +     * returns a clone of o, else null.
1901 +     */
1902 +    @SuppressWarnings("unchecked")
1903 +    <T> T cloneableClone(T o) {
1904 +        if (!(o instanceof Cloneable)) return null;
1905 +        final T clone;
1906 +        try {
1907 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1908 +        } catch (NoSuchMethodException ok) {
1909 +            return null;
1910 +        } catch (ReflectiveOperationException unexpected) {
1911 +            throw new Error(unexpected);
1912 +        }
1913 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1914 +        assertSame(o.getClass(), clone.getClass());
1915 +        return clone;
1916 +    }
1917 +
1918      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1919                               Runnable... throwingActions) {
1920          for (Runnable throwingAction : throwingActions) {
# Line 1816 | Line 1943 | public class JSR166TestCase extends Test
1943          } catch (NoSuchElementException success) {}
1944          assertFalse(it.hasNext());
1945      }
1946 +
1947 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1948 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1949 +    }
1950 +
1951 +    public Runnable runnableThrowing(final RuntimeException ex) {
1952 +        return new Runnable() { public void run() { throw ex; }};
1953 +    }
1954 +
1955 +    /** A reusable thread pool to be shared by tests. */
1956 +    static final ExecutorService cachedThreadPool =
1957 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1958 +                               1000L, MILLISECONDS,
1959 +                               new SynchronousQueue<Runnable>());
1960 +
1961 +    static <T> void shuffle(T[] array) {
1962 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1963 +    }
1964   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines