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.176 by jsr166, Mon Oct 12 07:16:39 2015 UTC vs.
Revision 1.214 by jsr166, Fri Dec 9 07:26:04 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 + /*
10 + * @test
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 + * @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 + */
36 +
37   import static java.util.concurrent.TimeUnit.MILLISECONDS;
38   import static java.util.concurrent.TimeUnit.MINUTES;
39   import static java.util.concurrent.TimeUnit.NANOSECONDS;
# Line 31 | Line 59 | import java.security.ProtectionDomain;
59   import java.security.SecurityPermission;
60   import java.util.ArrayList;
61   import java.util.Arrays;
62 + import java.util.Collection;
63 + import java.util.Collections;
64   import java.util.Date;
65   import java.util.Enumeration;
66   import java.util.Iterator;
# Line 50 | Line 80 | import java.util.concurrent.RecursiveAct
80   import java.util.concurrent.RecursiveTask;
81   import java.util.concurrent.RejectedExecutionHandler;
82   import java.util.concurrent.Semaphore;
83 + import java.util.concurrent.SynchronousQueue;
84   import java.util.concurrent.ThreadFactory;
85 + import java.util.concurrent.ThreadLocalRandom;
86   import java.util.concurrent.ThreadPoolExecutor;
87   import java.util.concurrent.TimeoutException;
88 + import java.util.concurrent.atomic.AtomicBoolean;
89   import java.util.concurrent.atomic.AtomicReference;
90   import java.util.regex.Matcher;
91   import java.util.regex.Pattern;
# Line 112 | Line 145 | import junit.framework.TestSuite;
145   * methods as there are exceptions the method can throw. Sometimes
146   * there are multiple tests per JSR166 method when the different
147   * "normal" behaviors differ significantly. And sometimes testcases
148 < * cover multiple methods when they cannot be tested in
116 < * isolation.
148 > * cover multiple methods when they cannot be tested in isolation.
149   *
150   * <li>The documentation style for testcases is to provide as javadoc
151   * a simple sentence or two describing the property that the testcase
# Line 176 | Line 208 | public class JSR166TestCase extends Test
208      private static final int suiteRuns =
209          Integer.getInteger("jsr166.suiteRuns", 1);
210  
211 +    /**
212 +     * Returns the value of the system property, or NaN if not defined.
213 +     */
214 +    private static float systemPropertyValue(String name) {
215 +        String floatString = System.getProperty(name);
216 +        if (floatString == null)
217 +            return Float.NaN;
218 +        try {
219 +            return Float.parseFloat(floatString);
220 +        } catch (NumberFormatException ex) {
221 +            throw new IllegalArgumentException(
222 +                String.format("Bad float value in system property %s=%s",
223 +                              name, floatString));
224 +        }
225 +    }
226 +
227 +    /**
228 +     * The scaling factor to apply to standard delays used in tests.
229 +     * May be initialized from any of:
230 +     * - the "jsr166.delay.factor" system property
231 +     * - the "test.timeout.factor" system property (as used by jtreg)
232 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
233 +     * - hard-coded fuzz factor when using a known slowpoke VM
234 +     */
235 +    private static final float delayFactor = delayFactor();
236 +
237 +    private static float delayFactor() {
238 +        float x;
239 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
240 +            return x;
241 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
242 +            return x;
243 +        String prop = System.getProperty("java.vm.version");
244 +        if (prop != null && prop.matches(".*debug.*"))
245 +            return 4.0f; // How much slower is fastdebug than product?!
246 +        return 1.0f;
247 +    }
248 +
249      public JSR166TestCase() { super(); }
250      public JSR166TestCase(String name) { super(name); }
251  
# Line 273 | Line 343 | public class JSR166TestCase extends Test
343          main(suite(), args);
344      }
345  
346 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
347 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
348 +        long runTime;
349 +        public void startTest(Test test) {}
350 +        protected void printHeader(long runTime) {
351 +            this.runTime = runTime; // defer printing for later
352 +        }
353 +        protected void printFooter(TestResult result) {
354 +            if (result.wasSuccessful()) {
355 +                getWriter().println("OK (" + result.runCount() + " tests)"
356 +                    + "  Time: " + elapsedTimeAsString(runTime));
357 +            } else {
358 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
359 +                super.printFooter(result);
360 +            }
361 +        }
362 +    }
363 +
364 +    /**
365 +     * Returns a TestRunner that doesn't bother with unnecessary
366 +     * fluff, like printing a "." for each test case.
367 +     */
368 +    static junit.textui.TestRunner newPithyTestRunner() {
369 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
370 +        runner.setPrinter(new PithyResultPrinter(System.out));
371 +        return runner;
372 +    }
373 +
374      /**
375       * Runs all unit tests in the given test suite.
376       * Actual behavior influenced by jsr166.* system properties.
# Line 284 | Line 382 | public class JSR166TestCase extends Test
382              System.setSecurityManager(new SecurityManager());
383          }
384          for (int i = 0; i < suiteRuns; i++) {
385 <            TestResult result = junit.textui.TestRunner.run(suite);
385 >            TestResult result = newPithyTestRunner().doRun(suite);
386              if (!result.wasSuccessful())
387                  System.exit(1);
388              System.gc();
# Line 368 | Line 466 | public class JSR166TestCase extends Test
466              AbstractQueuedLongSynchronizerTest.suite(),
467              ArrayBlockingQueueTest.suite(),
468              ArrayDequeTest.suite(),
469 +            ArrayListTest.suite(),
470              AtomicBooleanTest.suite(),
471              AtomicIntegerArrayTest.suite(),
472              AtomicIntegerFieldUpdaterTest.suite(),
# Line 390 | Line 489 | public class JSR166TestCase extends Test
489              CopyOnWriteArrayListTest.suite(),
490              CopyOnWriteArraySetTest.suite(),
491              CountDownLatchTest.suite(),
492 +            CountedCompleterTest.suite(),
493              CyclicBarrierTest.suite(),
494              DelayQueueTest.suite(),
495              EntryTest.suite(),
# Line 418 | Line 518 | public class JSR166TestCase extends Test
518              TreeMapTest.suite(),
519              TreeSetTest.suite(),
520              TreeSubMapTest.suite(),
521 <            TreeSubSetTest.suite());
521 >            TreeSubSetTest.suite(),
522 >            VectorTest.suite());
523  
524          // Java8+ test classes
525          if (atLeastJava8()) {
526              String[] java8TestClassNames = {
527 +                "ArrayDeque8Test",
528                  "Atomic8Test",
529                  "CompletableFutureTest",
530                  "ConcurrentHashMap8Test",
531 <                "CountedCompleterTest",
531 >                "CountedCompleter8Test",
532                  "DoubleAccumulatorTest",
533                  "DoubleAdderTest",
534                  "ForkJoinPool8Test",
# Line 437 | Line 539 | public class JSR166TestCase extends Test
539                  "StampedLockTest",
540                  "SubmissionPublisherTest",
541                  "ThreadLocalRandom8Test",
542 +                "TimeUnit8Test",
543              };
544              addNamedTestClasses(suite, java8TestClassNames);
545          }
# Line 444 | Line 547 | public class JSR166TestCase extends Test
547          // Java9+ test classes
548          if (atLeastJava9()) {
549              String[] java9TestClassNames = {
550 <                // Currently empty, but expecting varhandle tests
550 >                "AtomicBoolean9Test",
551 >                "AtomicInteger9Test",
552 >                "AtomicIntegerArray9Test",
553 >                "AtomicLong9Test",
554 >                "AtomicLongArray9Test",
555 >                "AtomicReference9Test",
556 >                "AtomicReferenceArray9Test",
557 >                "ExecutorCompletionService9Test",
558              };
559              addNamedTestClasses(suite, java9TestClassNames);
560          }
# Line 521 | Line 631 | public class JSR166TestCase extends Test
631      public static long LONG_DELAY_MS;
632  
633      /**
634 <     * Returns the shortest timed delay. This could
635 <     * be reimplemented to use for example a Property.
634 >     * Returns the shortest timed delay. This can be scaled up for
635 >     * slow machines using the jsr166.delay.factor system property,
636 >     * or via jtreg's -timeoutFactor: flag.
637 >     * http://openjdk.java.net/jtreg/command-help.html
638       */
639      protected long getShortDelay() {
640 <        return 50;
640 >        return (long) (50 * delayFactor);
641      }
642  
643      /**
# Line 838 | Line 950 | public class JSR166TestCase extends Test
950          }};
951      }
952  
953 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
954 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
955 +    }
956 +
957 +    Runnable releaser(final AtomicBoolean flag) {
958 +        return new Runnable() { public void run() { flag.set(true); }};
959 +    }
960 +
961      /**
962       * Waits out termination of a thread pool or fails doing so.
963       */
# Line 861 | Line 981 | public class JSR166TestCase extends Test
981          }
982      }
983  
984 <    /** Like Runnable, but with the freedom to throw anything */
984 >    /**
985 >     * Like Runnable, but with the freedom to throw anything.
986 >     * junit folks had the same idea:
987 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
988 >     */
989      interface Action { public void run() throws Throwable; }
990  
991      /**
# Line 892 | Line 1016 | public class JSR166TestCase extends Test
1016       * Uninteresting threads are filtered out.
1017       */
1018      static void dumpTestThreads() {
1019 +        SecurityManager sm = System.getSecurityManager();
1020 +        if (sm != null) {
1021 +            try {
1022 +                System.setSecurityManager(null);
1023 +            } catch (SecurityException giveUp) {
1024 +                return;
1025 +            }
1026 +        }
1027 +
1028          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1029          System.err.println("------ stacktrace dump start ------");
1030          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1031 <            String name = info.getThreadName();
1031 >            final String name = info.getThreadName();
1032 >            String lockName;
1033              if ("Signal Dispatcher".equals(name))
1034                  continue;
1035              if ("Reference Handler".equals(name)
1036 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1036 >                && (lockName = info.getLockName()) != null
1037 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1038                  continue;
1039              if ("Finalizer".equals(name)
1040 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1040 >                && (lockName = info.getLockName()) != null
1041 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1042                  continue;
1043              if ("checkForWedgedTest".equals(name))
1044                  continue;
1045              System.err.print(info);
1046          }
1047          System.err.println("------ stacktrace dump end ------");
1048 +
1049 +        if (sm != null) System.setSecurityManager(sm);
1050      }
1051  
1052      /**
# Line 1125 | Line 1263 | public class JSR166TestCase extends Test
1263       * Sleeps until the given time has elapsed.
1264       * Throws AssertionFailedError if interrupted.
1265       */
1266 <    void sleep(long millis) {
1266 >    static void sleep(long millis) {
1267          try {
1268              delay(millis);
1269          } catch (InterruptedException fail) {
# Line 1141 | Line 1279 | public class JSR166TestCase extends Test
1279       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1280       */
1281      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1282 <        long startTime = System.nanoTime();
1282 >        long startTime = 0L;
1283          for (;;) {
1284              Thread.State s = thread.getState();
1285              if (s == Thread.State.BLOCKED ||
# Line 1150 | Line 1288 | public class JSR166TestCase extends Test
1288                  return;
1289              else if (s == Thread.State.TERMINATED)
1290                  fail("Unexpected thread termination");
1291 +            else if (startTime == 0L)
1292 +                startTime = System.nanoTime();
1293              else if (millisElapsedSince(startTime) > timeoutMillis) {
1294                  threadAssertTrue(thread.isAlive());
1295                  return;
# Line 1228 | Line 1368 | public class JSR166TestCase extends Test
1368          } finally {
1369              if (t.getState() != Thread.State.TERMINATED) {
1370                  t.interrupt();
1371 <                threadFail("Test timed out");
1371 >                threadFail("timed out waiting for thread to terminate");
1372              }
1373          }
1374      }
# Line 1394 | Line 1534 | public class JSR166TestCase extends Test
1534          return new LatchAwaiter(latch);
1535      }
1536  
1537 <    public void await(CountDownLatch latch) {
1537 >    public void await(CountDownLatch latch, long timeoutMillis) {
1538          try {
1539 <            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1539 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1540                  fail("timed out waiting for CountDownLatch for "
1541 <                     + (LONG_DELAY_MS/1000) + " sec");
1541 >                     + (timeoutMillis/1000) + " sec");
1542          } catch (Throwable fail) {
1543              threadUnexpectedException(fail);
1544          }
1545      }
1546  
1547 +    public void await(CountDownLatch latch) {
1548 +        await(latch, LONG_DELAY_MS);
1549 +    }
1550 +
1551      public void await(Semaphore semaphore) {
1552          try {
1553              if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
# Line 1638 | Line 1782 | public class JSR166TestCase extends Test
1782       * A CyclicBarrier that uses timed await and fails with
1783       * AssertionFailedErrors instead of throwing checked exceptions.
1784       */
1785 <    public class CheckedBarrier extends CyclicBarrier {
1785 >    public static class CheckedBarrier extends CyclicBarrier {
1786          public CheckedBarrier(int parties) { super(parties); }
1787  
1788          public int await() {
# Line 1702 | Line 1846 | public class JSR166TestCase extends Test
1846          }
1847      }
1848  
1849 +    void assertImmutable(final Object o) {
1850 +        if (o instanceof Collection) {
1851 +            assertThrows(
1852 +                UnsupportedOperationException.class,
1853 +                new Runnable() { public void run() {
1854 +                        ((Collection) o).add(null);}});
1855 +        }
1856 +    }
1857 +
1858      @SuppressWarnings("unchecked")
1859      <T> T serialClone(T o) {
1860          try {
1861              ObjectInputStream ois = new ObjectInputStream
1862                  (new ByteArrayInputStream(serialBytes(o)));
1863              T clone = (T) ois.readObject();
1864 +            if (o == clone) assertImmutable(o);
1865              assertSame(o.getClass(), clone.getClass());
1866              return clone;
1867          } catch (Throwable fail) {
# Line 1716 | Line 1870 | public class JSR166TestCase extends Test
1870          }
1871      }
1872  
1873 +    /**
1874 +     * A version of serialClone that leaves error handling (for
1875 +     * e.g. NotSerializableException) up to the caller.
1876 +     */
1877 +    @SuppressWarnings("unchecked")
1878 +    <T> T serialClonePossiblyFailing(T o)
1879 +        throws ReflectiveOperationException, java.io.IOException {
1880 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1881 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1882 +        oos.writeObject(o);
1883 +        oos.flush();
1884 +        oos.close();
1885 +        ObjectInputStream ois = new ObjectInputStream
1886 +            (new ByteArrayInputStream(bos.toByteArray()));
1887 +        T clone = (T) ois.readObject();
1888 +        if (o == clone) assertImmutable(o);
1889 +        assertSame(o.getClass(), clone.getClass());
1890 +        return clone;
1891 +    }
1892 +
1893 +    /**
1894 +     * If o implements Cloneable and has a public clone method,
1895 +     * returns a clone of o, else null.
1896 +     */
1897 +    @SuppressWarnings("unchecked")
1898 +    <T> T cloneableClone(T o) {
1899 +        if (!(o instanceof Cloneable)) return null;
1900 +        final T clone;
1901 +        try {
1902 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1903 +        } catch (NoSuchMethodException ok) {
1904 +            return null;
1905 +        } catch (ReflectiveOperationException unexpected) {
1906 +            throw new Error(unexpected);
1907 +        }
1908 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1909 +        assertSame(o.getClass(), clone.getClass());
1910 +        return clone;
1911 +    }
1912 +
1913      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1914                               Runnable... throwingActions) {
1915          for (Runnable throwingAction : throwingActions) {
# Line 1744 | Line 1938 | public class JSR166TestCase extends Test
1938          } catch (NoSuchElementException success) {}
1939          assertFalse(it.hasNext());
1940      }
1941 +
1942 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1943 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1944 +    }
1945 +
1946 +    public Runnable runnableThrowing(final RuntimeException ex) {
1947 +        return new Runnable() { public void run() { throw ex; }};
1948 +    }
1949 +
1950 +    /** A reusable thread pool to be shared by tests. */
1951 +    static final ExecutorService cachedThreadPool =
1952 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1953 +                               1000L, MILLISECONDS,
1954 +                               new SynchronousQueue<Runnable>());
1955 +
1956 +    static <T> void shuffle(T[] array) {
1957 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1958 +    }
1959   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines