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.212 by jsr166, Fri Dec 9 04:24:07 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 + /*
10 + * @test
11 + * @summary JSR-166 tck tests
12 + * @modules java.base/java.util.concurrent:open
13 + *          java.management
14 + * @build *
15 + * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
16 + * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
17 + * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=1 -Djava.util.secureRandomSeed=true JSR166TestCase
18 + */
19 +
20   import static java.util.concurrent.TimeUnit.MILLISECONDS;
21   import static java.util.concurrent.TimeUnit.MINUTES;
22   import static java.util.concurrent.TimeUnit.NANOSECONDS;
# Line 31 | Line 42 | import java.security.ProtectionDomain;
42   import java.security.SecurityPermission;
43   import java.util.ArrayList;
44   import java.util.Arrays;
45 + import java.util.Collection;
46 + import java.util.Collections;
47   import java.util.Date;
48   import java.util.Enumeration;
49   import java.util.Iterator;
# Line 50 | Line 63 | import java.util.concurrent.RecursiveAct
63   import java.util.concurrent.RecursiveTask;
64   import java.util.concurrent.RejectedExecutionHandler;
65   import java.util.concurrent.Semaphore;
66 + import java.util.concurrent.SynchronousQueue;
67   import java.util.concurrent.ThreadFactory;
68 + import java.util.concurrent.ThreadLocalRandom;
69   import java.util.concurrent.ThreadPoolExecutor;
70   import java.util.concurrent.TimeoutException;
71 + import java.util.concurrent.atomic.AtomicBoolean;
72   import java.util.concurrent.atomic.AtomicReference;
73   import java.util.regex.Matcher;
74   import java.util.regex.Pattern;
# Line 112 | Line 128 | import junit.framework.TestSuite;
128   * methods as there are exceptions the method can throw. Sometimes
129   * there are multiple tests per JSR166 method when the different
130   * "normal" behaviors differ significantly. And sometimes testcases
131 < * cover multiple methods when they cannot be tested in
116 < * isolation.
131 > * cover multiple methods when they cannot be tested in isolation.
132   *
133   * <li>The documentation style for testcases is to provide as javadoc
134   * a simple sentence or two describing the property that the testcase
# Line 176 | Line 191 | public class JSR166TestCase extends Test
191      private static final int suiteRuns =
192          Integer.getInteger("jsr166.suiteRuns", 1);
193  
194 +    /**
195 +     * Returns the value of the system property, or NaN if not defined.
196 +     */
197 +    private static float systemPropertyValue(String name) {
198 +        String floatString = System.getProperty(name);
199 +        if (floatString == null)
200 +            return Float.NaN;
201 +        try {
202 +            return Float.parseFloat(floatString);
203 +        } catch (NumberFormatException ex) {
204 +            throw new IllegalArgumentException(
205 +                String.format("Bad float value in system property %s=%s",
206 +                              name, floatString));
207 +        }
208 +    }
209 +
210 +    /**
211 +     * The scaling factor to apply to standard delays used in tests.
212 +     * May be initialized from any of:
213 +     * - the "jsr166.delay.factor" system property
214 +     * - the "test.timeout.factor" system property (as used by jtreg)
215 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
216 +     * - hard-coded fuzz factor when using a known slowpoke VM
217 +     */
218 +    private static final float delayFactor = delayFactor();
219 +
220 +    private static float delayFactor() {
221 +        float x;
222 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
223 +            return x;
224 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
225 +            return x;
226 +        String prop = System.getProperty("java.vm.version");
227 +        if (prop != null && prop.matches(".*debug.*"))
228 +            return 4.0f; // How much slower is fastdebug than product?!
229 +        return 1.0f;
230 +    }
231 +
232      public JSR166TestCase() { super(); }
233      public JSR166TestCase(String name) { super(name); }
234  
# Line 273 | Line 326 | public class JSR166TestCase extends Test
326          main(suite(), args);
327      }
328  
329 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
330 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
331 +        long runTime;
332 +        public void startTest(Test test) {}
333 +        protected void printHeader(long runTime) {
334 +            this.runTime = runTime; // defer printing for later
335 +        }
336 +        protected void printFooter(TestResult result) {
337 +            if (result.wasSuccessful()) {
338 +                getWriter().println("OK (" + result.runCount() + " tests)"
339 +                    + "  Time: " + elapsedTimeAsString(runTime));
340 +            } else {
341 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
342 +                super.printFooter(result);
343 +            }
344 +        }
345 +    }
346 +
347 +    /**
348 +     * Returns a TestRunner that doesn't bother with unnecessary
349 +     * fluff, like printing a "." for each test case.
350 +     */
351 +    static junit.textui.TestRunner newPithyTestRunner() {
352 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
353 +        runner.setPrinter(new PithyResultPrinter(System.out));
354 +        return runner;
355 +    }
356 +
357      /**
358       * Runs all unit tests in the given test suite.
359       * Actual behavior influenced by jsr166.* system properties.
# Line 284 | Line 365 | public class JSR166TestCase extends Test
365              System.setSecurityManager(new SecurityManager());
366          }
367          for (int i = 0; i < suiteRuns; i++) {
368 <            TestResult result = junit.textui.TestRunner.run(suite);
368 >            TestResult result = newPithyTestRunner().doRun(suite);
369              if (!result.wasSuccessful())
370                  System.exit(1);
371              System.gc();
# Line 368 | Line 449 | public class JSR166TestCase extends Test
449              AbstractQueuedLongSynchronizerTest.suite(),
450              ArrayBlockingQueueTest.suite(),
451              ArrayDequeTest.suite(),
452 +            ArrayListTest.suite(),
453              AtomicBooleanTest.suite(),
454              AtomicIntegerArrayTest.suite(),
455              AtomicIntegerFieldUpdaterTest.suite(),
# Line 390 | Line 472 | public class JSR166TestCase extends Test
472              CopyOnWriteArrayListTest.suite(),
473              CopyOnWriteArraySetTest.suite(),
474              CountDownLatchTest.suite(),
475 +            CountedCompleterTest.suite(),
476              CyclicBarrierTest.suite(),
477              DelayQueueTest.suite(),
478              EntryTest.suite(),
# Line 418 | Line 501 | public class JSR166TestCase extends Test
501              TreeMapTest.suite(),
502              TreeSetTest.suite(),
503              TreeSubMapTest.suite(),
504 <            TreeSubSetTest.suite());
504 >            TreeSubSetTest.suite(),
505 >            VectorTest.suite());
506  
507          // Java8+ test classes
508          if (atLeastJava8()) {
509              String[] java8TestClassNames = {
510 +                "ArrayDeque8Test",
511                  "Atomic8Test",
512                  "CompletableFutureTest",
513                  "ConcurrentHashMap8Test",
514 <                "CountedCompleterTest",
514 >                "CountedCompleter8Test",
515                  "DoubleAccumulatorTest",
516                  "DoubleAdderTest",
517                  "ForkJoinPool8Test",
# Line 437 | Line 522 | public class JSR166TestCase extends Test
522                  "StampedLockTest",
523                  "SubmissionPublisherTest",
524                  "ThreadLocalRandom8Test",
525 +                "TimeUnit8Test",
526              };
527              addNamedTestClasses(suite, java8TestClassNames);
528          }
# Line 444 | Line 530 | public class JSR166TestCase extends Test
530          // Java9+ test classes
531          if (atLeastJava9()) {
532              String[] java9TestClassNames = {
533 <                // Currently empty, but expecting varhandle tests
533 >                "AtomicBoolean9Test",
534 >                "AtomicInteger9Test",
535 >                "AtomicIntegerArray9Test",
536 >                "AtomicLong9Test",
537 >                "AtomicLongArray9Test",
538 >                "AtomicReference9Test",
539 >                "AtomicReferenceArray9Test",
540 >                "ExecutorCompletionService9Test",
541              };
542              addNamedTestClasses(suite, java9TestClassNames);
543          }
# Line 521 | Line 614 | public class JSR166TestCase extends Test
614      public static long LONG_DELAY_MS;
615  
616      /**
617 <     * Returns the shortest timed delay. This could
618 <     * be reimplemented to use for example a Property.
617 >     * Returns the shortest timed delay. This can be scaled up for
618 >     * slow machines using the jsr166.delay.factor system property,
619 >     * or via jtreg's -timeoutFactor: flag.
620 >     * http://openjdk.java.net/jtreg/command-help.html
621       */
622      protected long getShortDelay() {
623 <        return 50;
623 >        return (long) (50 * delayFactor);
624      }
625  
626      /**
# Line 838 | Line 933 | public class JSR166TestCase extends Test
933          }};
934      }
935  
936 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
937 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
938 +    }
939 +
940 +    Runnable releaser(final AtomicBoolean flag) {
941 +        return new Runnable() { public void run() { flag.set(true); }};
942 +    }
943 +
944      /**
945       * Waits out termination of a thread pool or fails doing so.
946       */
# Line 861 | Line 964 | public class JSR166TestCase extends Test
964          }
965      }
966  
967 <    /** Like Runnable, but with the freedom to throw anything */
967 >    /**
968 >     * Like Runnable, but with the freedom to throw anything.
969 >     * junit folks had the same idea:
970 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
971 >     */
972      interface Action { public void run() throws Throwable; }
973  
974      /**
# Line 892 | Line 999 | public class JSR166TestCase extends Test
999       * Uninteresting threads are filtered out.
1000       */
1001      static void dumpTestThreads() {
1002 +        SecurityManager sm = System.getSecurityManager();
1003 +        if (sm != null) {
1004 +            try {
1005 +                System.setSecurityManager(null);
1006 +            } catch (SecurityException giveUp) {
1007 +                return;
1008 +            }
1009 +        }
1010 +
1011          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1012          System.err.println("------ stacktrace dump start ------");
1013          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
1014 <            String name = info.getThreadName();
1014 >            final String name = info.getThreadName();
1015 >            String lockName;
1016              if ("Signal Dispatcher".equals(name))
1017                  continue;
1018              if ("Reference Handler".equals(name)
1019 <                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
1019 >                && (lockName = info.getLockName()) != null
1020 >                && lockName.startsWith("java.lang.ref.Reference$Lock"))
1021                  continue;
1022              if ("Finalizer".equals(name)
1023 <                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1023 >                && (lockName = info.getLockName()) != null
1024 >                && lockName.startsWith("java.lang.ref.ReferenceQueue$Lock"))
1025                  continue;
1026              if ("checkForWedgedTest".equals(name))
1027                  continue;
1028              System.err.print(info);
1029          }
1030          System.err.println("------ stacktrace dump end ------");
1031 +
1032 +        if (sm != null) System.setSecurityManager(sm);
1033      }
1034  
1035      /**
# Line 1125 | Line 1246 | public class JSR166TestCase extends Test
1246       * Sleeps until the given time has elapsed.
1247       * Throws AssertionFailedError if interrupted.
1248       */
1249 <    void sleep(long millis) {
1249 >    static void sleep(long millis) {
1250          try {
1251              delay(millis);
1252          } catch (InterruptedException fail) {
# Line 1141 | Line 1262 | public class JSR166TestCase extends Test
1262       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1263       */
1264      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1265 <        long startTime = System.nanoTime();
1265 >        long startTime = 0L;
1266          for (;;) {
1267              Thread.State s = thread.getState();
1268              if (s == Thread.State.BLOCKED ||
# Line 1150 | Line 1271 | public class JSR166TestCase extends Test
1271                  return;
1272              else if (s == Thread.State.TERMINATED)
1273                  fail("Unexpected thread termination");
1274 +            else if (startTime == 0L)
1275 +                startTime = System.nanoTime();
1276              else if (millisElapsedSince(startTime) > timeoutMillis) {
1277                  threadAssertTrue(thread.isAlive());
1278                  return;
# Line 1228 | Line 1351 | public class JSR166TestCase extends Test
1351          } finally {
1352              if (t.getState() != Thread.State.TERMINATED) {
1353                  t.interrupt();
1354 <                threadFail("Test timed out");
1354 >                threadFail("timed out waiting for thread to terminate");
1355              }
1356          }
1357      }
# Line 1394 | Line 1517 | public class JSR166TestCase extends Test
1517          return new LatchAwaiter(latch);
1518      }
1519  
1520 <    public void await(CountDownLatch latch) {
1520 >    public void await(CountDownLatch latch, long timeoutMillis) {
1521          try {
1522 <            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1522 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1523                  fail("timed out waiting for CountDownLatch for "
1524 <                     + (LONG_DELAY_MS/1000) + " sec");
1524 >                     + (timeoutMillis/1000) + " sec");
1525          } catch (Throwable fail) {
1526              threadUnexpectedException(fail);
1527          }
1528      }
1529  
1530 +    public void await(CountDownLatch latch) {
1531 +        await(latch, LONG_DELAY_MS);
1532 +    }
1533 +
1534      public void await(Semaphore semaphore) {
1535          try {
1536              if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
# Line 1638 | Line 1765 | public class JSR166TestCase extends Test
1765       * A CyclicBarrier that uses timed await and fails with
1766       * AssertionFailedErrors instead of throwing checked exceptions.
1767       */
1768 <    public class CheckedBarrier extends CyclicBarrier {
1768 >    public static class CheckedBarrier extends CyclicBarrier {
1769          public CheckedBarrier(int parties) { super(parties); }
1770  
1771          public int await() {
# Line 1702 | Line 1829 | public class JSR166TestCase extends Test
1829          }
1830      }
1831  
1832 +    void assertImmutable(final Object o) {
1833 +        if (o instanceof Collection) {
1834 +            assertThrows(
1835 +                UnsupportedOperationException.class,
1836 +                new Runnable() { public void run() {
1837 +                        ((Collection) o).add(null);}});
1838 +        }
1839 +    }
1840 +
1841      @SuppressWarnings("unchecked")
1842      <T> T serialClone(T o) {
1843          try {
1844              ObjectInputStream ois = new ObjectInputStream
1845                  (new ByteArrayInputStream(serialBytes(o)));
1846              T clone = (T) ois.readObject();
1847 +            if (o == clone) assertImmutable(o);
1848              assertSame(o.getClass(), clone.getClass());
1849              return clone;
1850          } catch (Throwable fail) {
# Line 1716 | Line 1853 | public class JSR166TestCase extends Test
1853          }
1854      }
1855  
1856 +    /**
1857 +     * A version of serialClone that leaves error handling (for
1858 +     * e.g. NotSerializableException) up to the caller.
1859 +     */
1860 +    @SuppressWarnings("unchecked")
1861 +    <T> T serialClonePossiblyFailing(T o)
1862 +        throws ReflectiveOperationException, java.io.IOException {
1863 +        ByteArrayOutputStream bos = new ByteArrayOutputStream();
1864 +        ObjectOutputStream oos = new ObjectOutputStream(bos);
1865 +        oos.writeObject(o);
1866 +        oos.flush();
1867 +        oos.close();
1868 +        ObjectInputStream ois = new ObjectInputStream
1869 +            (new ByteArrayInputStream(bos.toByteArray()));
1870 +        T clone = (T) ois.readObject();
1871 +        if (o == clone) assertImmutable(o);
1872 +        assertSame(o.getClass(), clone.getClass());
1873 +        return clone;
1874 +    }
1875 +
1876 +    /**
1877 +     * If o implements Cloneable and has a public clone method,
1878 +     * returns a clone of o, else null.
1879 +     */
1880 +    @SuppressWarnings("unchecked")
1881 +    <T> T cloneableClone(T o) {
1882 +        if (!(o instanceof Cloneable)) return null;
1883 +        final T clone;
1884 +        try {
1885 +            clone = (T) o.getClass().getMethod("clone").invoke(o);
1886 +        } catch (NoSuchMethodException ok) {
1887 +            return null;
1888 +        } catch (ReflectiveOperationException unexpected) {
1889 +            throw new Error(unexpected);
1890 +        }
1891 +        assertNotSame(o, clone); // not 100% guaranteed by spec
1892 +        assertSame(o.getClass(), clone.getClass());
1893 +        return clone;
1894 +    }
1895 +
1896      public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1897                               Runnable... throwingActions) {
1898          for (Runnable throwingAction : throwingActions) {
# Line 1744 | Line 1921 | public class JSR166TestCase extends Test
1921          } catch (NoSuchElementException success) {}
1922          assertFalse(it.hasNext());
1923      }
1924 +
1925 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1926 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1927 +    }
1928 +
1929 +    public Runnable runnableThrowing(final RuntimeException ex) {
1930 +        return new Runnable() { public void run() { throw ex; }};
1931 +    }
1932 +
1933 +    /** A reusable thread pool to be shared by tests. */
1934 +    static final ExecutorService cachedThreadPool =
1935 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1936 +                               1000L, MILLISECONDS,
1937 +                               new SynchronousQueue<Runnable>());
1938 +
1939 +    static <T> void shuffle(T[] array) {
1940 +        Collections.shuffle(Arrays.asList(array), ThreadLocalRandom.current());
1941 +    }
1942   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines