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.147 by jsr166, Sat Sep 26 19:08:26 2015 UTC vs.
Revision 1.195 by jsr166, Sat Jun 4 23:49:29 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.management
13 + * @build *
14 + * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
15 + * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
16 + */
17 +
18   import static java.util.concurrent.TimeUnit.MILLISECONDS;
19 + import static java.util.concurrent.TimeUnit.MINUTES;
20   import static java.util.concurrent.TimeUnit.NANOSECONDS;
21  
22   import java.io.ByteArrayInputStream;
# Line 15 | Line 25 | import java.io.ObjectInputStream;
25   import java.io.ObjectOutputStream;
26   import java.lang.management.ManagementFactory;
27   import java.lang.management.ThreadInfo;
28 + import java.lang.management.ThreadMXBean;
29   import java.lang.reflect.Constructor;
30   import java.lang.reflect.Method;
31   import java.lang.reflect.Modifier;
32 + import java.nio.file.Files;
33 + import java.nio.file.Paths;
34   import java.security.CodeSource;
35   import java.security.Permission;
36   import java.security.PermissionCollection;
# Line 46 | Line 59 | import java.util.concurrent.RecursiveAct
59   import java.util.concurrent.RecursiveTask;
60   import java.util.concurrent.RejectedExecutionHandler;
61   import java.util.concurrent.Semaphore;
62 + import java.util.concurrent.SynchronousQueue;
63   import java.util.concurrent.ThreadFactory;
64   import java.util.concurrent.ThreadPoolExecutor;
65   import java.util.concurrent.TimeoutException;
66 + import java.util.concurrent.atomic.AtomicBoolean;
67   import java.util.concurrent.atomic.AtomicReference;
68 + import java.util.regex.Matcher;
69   import java.util.regex.Pattern;
70  
71   import junit.framework.AssertionFailedError;
# Line 107 | Line 123 | import junit.framework.TestSuite;
123   * methods as there are exceptions the method can throw. Sometimes
124   * there are multiple tests per JSR166 method when the different
125   * "normal" behaviors differ significantly. And sometimes testcases
126 < * cover multiple methods when they cannot be tested in
111 < * isolation.
126 > * cover multiple methods when they cannot be tested in isolation.
127   *
128   * <li>The documentation style for testcases is to provide as javadoc
129   * a simple sentence or two describing the property that the testcase
# Line 171 | Line 186 | public class JSR166TestCase extends Test
186      private static final int suiteRuns =
187          Integer.getInteger("jsr166.suiteRuns", 1);
188  
189 +    /**
190 +     * Returns the value of the system property, or NaN if not defined.
191 +     */
192 +    private static float systemPropertyValue(String name) {
193 +        String floatString = System.getProperty(name);
194 +        if (floatString == null)
195 +            return Float.NaN;
196 +        try {
197 +            return Float.parseFloat(floatString);
198 +        } catch (NumberFormatException ex) {
199 +            throw new IllegalArgumentException(
200 +                String.format("Bad float value in system property %s=%s",
201 +                              name, floatString));
202 +        }
203 +    }
204 +
205 +    /**
206 +     * The scaling factor to apply to standard delays used in tests.
207 +     * May be initialized from any of:
208 +     * - the "jsr166.delay.factor" system property
209 +     * - the "test.timeout.factor" system property (as used by jtreg)
210 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
211 +     * - hard-coded fuzz factor when using a known slowpoke VM
212 +     */
213 +    private static final float delayFactor = delayFactor();
214 +
215 +    private static float delayFactor() {
216 +        float x;
217 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
218 +            return x;
219 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
220 +            return x;
221 +        String prop = System.getProperty("java.vm.version");
222 +        if (prop != null && prop.matches(".*debug.*"))
223 +            return 4.0f; // How much slower is fastdebug than product?!
224 +        return 1.0f;
225 +    }
226 +
227      public JSR166TestCase() { super(); }
228      public JSR166TestCase(String name) { super(name); }
229  
# Line 186 | Line 239 | public class JSR166TestCase extends Test
239          return (regex == null) ? null : Pattern.compile(regex);
240      }
241  
242 +    // Instrumentation to debug very rare, but very annoying hung test runs.
243 +    static volatile TestCase currentTestCase;
244 +    // static volatile int currentRun = 0;
245 +    static {
246 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
247 +            // Avoid spurious reports with enormous runsPerTest.
248 +            // A single test case run should never take more than 1 second.
249 +            // But let's cap it at the high end too ...
250 +            final int timeoutMinutes =
251 +                Math.min(15, Math.max(runsPerTest / 60, 1));
252 +            for (TestCase lastTestCase = currentTestCase;;) {
253 +                try { MINUTES.sleep(timeoutMinutes); }
254 +                catch (InterruptedException unexpected) { break; }
255 +                if (lastTestCase == currentTestCase) {
256 +                    System.err.printf(
257 +                        "Looks like we're stuck running test: %s%n",
258 +                        lastTestCase);
259 + //                     System.err.printf(
260 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
261 + //                         lastTestCase, currentRun, runsPerTest);
262 + //                     System.err.println("availableProcessors=" +
263 + //                         Runtime.getRuntime().availableProcessors());
264 + //                     System.err.printf("cpu model = %s%n", cpuModel());
265 +                    dumpTestThreads();
266 +                    // one stack dump is probably enough; more would be spam
267 +                    break;
268 +                }
269 +                lastTestCase = currentTestCase;
270 +            }}};
271 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
272 +        thread.setDaemon(true);
273 +        thread.start();
274 +    }
275 +
276 + //     public static String cpuModel() {
277 + //         try {
278 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
279 + //                 .matcher(new String(
280 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
281 + //             matcher.find();
282 + //             return matcher.group(1);
283 + //         } catch (Exception ex) { return null; }
284 + //     }
285 +
286      public void runBare() throws Throwable {
287 +        currentTestCase = this;
288          if (methodFilter == null
289              || methodFilter.matcher(toString()).find())
290              super.runBare();
# Line 194 | Line 292 | public class JSR166TestCase extends Test
292  
293      protected void runTest() throws Throwable {
294          for (int i = 0; i < runsPerTest; i++) {
295 +            // currentRun = i;
296              if (profileTests)
297                  runTestProfiled();
298              else
# Line 222 | Line 321 | public class JSR166TestCase extends Test
321          main(suite(), args);
322      }
323  
324 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
325 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
326 +        long runTime;
327 +        public void startTest(Test test) {}
328 +        protected void printHeader(long runTime) {
329 +            this.runTime = runTime; // defer printing for later
330 +        }
331 +        protected void printFooter(TestResult result) {
332 +            if (result.wasSuccessful()) {
333 +                getWriter().println("OK (" + result.runCount() + " tests)"
334 +                    + "  Time: " + elapsedTimeAsString(runTime));
335 +            } else {
336 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
337 +                super.printFooter(result);
338 +            }
339 +        }
340 +    }
341 +
342 +    /**
343 +     * Returns a TestRunner that doesn't bother with unnecessary
344 +     * fluff, like printing a "." for each test case.
345 +     */
346 +    static junit.textui.TestRunner newPithyTestRunner() {
347 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
348 +        runner.setPrinter(new PithyResultPrinter(System.out));
349 +        return runner;
350 +    }
351 +
352      /**
353       * Runs all unit tests in the given test suite.
354       * Actual behavior influenced by jsr166.* system properties.
# Line 233 | Line 360 | public class JSR166TestCase extends Test
360              System.setSecurityManager(new SecurityManager());
361          }
362          for (int i = 0; i < suiteRuns; i++) {
363 <            TestResult result = junit.textui.TestRunner.run(suite);
363 >            TestResult result = newPithyTestRunner().doRun(suite);
364              if (!result.wasSuccessful())
365                  System.exit(1);
366              System.gc();
# Line 386 | Line 513 | public class JSR166TestCase extends Test
513                  "StampedLockTest",
514                  "SubmissionPublisherTest",
515                  "ThreadLocalRandom8Test",
516 +                "TimeUnit8Test",
517              };
518              addNamedTestClasses(suite, java8TestClassNames);
519          }
# Line 393 | Line 521 | public class JSR166TestCase extends Test
521          // Java9+ test classes
522          if (atLeastJava9()) {
523              String[] java9TestClassNames = {
524 <                // Currently empty, but expecting varhandle tests
524 >                "ExecutorCompletionService9Test",
525              };
526              addNamedTestClasses(suite, java9TestClassNames);
527          }
# Line 460 | Line 588 | public class JSR166TestCase extends Test
588          } else {
589              return new TestSuite();
590          }
463
591      }
592  
593      // Delays for timing-dependent tests, in milliseconds.
# Line 471 | Line 598 | public class JSR166TestCase extends Test
598      public static long LONG_DELAY_MS;
599  
600      /**
601 <     * Returns the shortest timed delay. This could
602 <     * be reimplemented to use for example a Property.
601 >     * Returns the shortest timed delay. This can be scaled up for
602 >     * slow machines using the jsr166.delay.factor system property,
603 >     * or via jtreg's -timeoutFactor: flag.
604 >     * http://openjdk.java.net/jtreg/command-help.html
605       */
606      protected long getShortDelay() {
607 <        return 50;
607 >        return (long) (50 * delayFactor);
608      }
609  
610      /**
# Line 518 | Line 647 | public class JSR166TestCase extends Test
647       * the same test have no effect.
648       */
649      public void threadRecordFailure(Throwable t) {
650 +        System.err.println(t);
651 +        dumpTestThreads();
652          threadFailure.compareAndSet(null, t);
653      }
654  
# Line 528 | Line 659 | public class JSR166TestCase extends Test
659      void tearDownFail(String format, Object... args) {
660          String msg = toString() + ": " + String.format(format, args);
661          System.err.println(msg);
662 <        printAllStackTraces();
662 >        dumpTestThreads();
663          throw new AssertionFailedError(msg);
664      }
665  
# Line 565 | Line 696 | public class JSR166TestCase extends Test
696      }
697  
698      /**
699 <     * Finds missing try { ... } finally { joinPool(e); }
699 >     * Finds missing PoolCleaners
700       */
701      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
702          Thread[] survivors = new Thread[7];
# Line 597 | Line 728 | public class JSR166TestCase extends Test
728              fail(reason);
729          } catch (AssertionFailedError t) {
730              threadRecordFailure(t);
731 <            fail(reason);
731 >            throw t;
732          }
733      }
734  
# Line 724 | Line 855 | public class JSR166TestCase extends Test
855      /**
856       * Delays, via Thread.sleep, for the given millisecond delay, but
857       * if the sleep is shorter than specified, may re-sleep or yield
858 <     * until time elapses.
858 >     * until time elapses.  Ensures that the given time, as measured
859 >     * by System.nanoTime(), has elapsed.
860       */
861      static void delay(long millis) throws InterruptedException {
862 <        long startTime = System.nanoTime();
863 <        long ns = millis * 1000 * 1000;
864 <        for (;;) {
862 >        long nanos = millis * (1000 * 1000);
863 >        final long wakeupTime = System.nanoTime() + nanos;
864 >        do {
865              if (millis > 0L)
866                  Thread.sleep(millis);
867              else // too short to sleep
868                  Thread.yield();
869 <            long d = ns - (System.nanoTime() - startTime);
870 <            if (d > 0L)
871 <                millis = d / (1000 * 1000);
872 <            else
873 <                break;
869 >            nanos = wakeupTime - System.nanoTime();
870 >            millis = nanos / (1000 * 1000);
871 >        } while (nanos >= 0L);
872 >    }
873 >
874 >    /**
875 >     * Allows use of try-with-resources with per-test thread pools.
876 >     */
877 >    class PoolCleaner implements AutoCloseable {
878 >        private final ExecutorService pool;
879 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
880 >        public void close() { joinPool(pool); }
881 >    }
882 >
883 >    /**
884 >     * An extension of PoolCleaner that has an action to release the pool.
885 >     */
886 >    class PoolCleanerWithReleaser extends PoolCleaner {
887 >        private final Runnable releaser;
888 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
889 >            super(pool);
890 >            this.releaser = releaser;
891          }
892 +        public void close() {
893 +            try {
894 +                releaser.run();
895 +            } finally {
896 +                super.close();
897 +            }
898 +        }
899 +    }
900 +
901 +    PoolCleaner cleaner(ExecutorService pool) {
902 +        return new PoolCleaner(pool);
903 +    }
904 +
905 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
906 +        return new PoolCleanerWithReleaser(pool, releaser);
907 +    }
908 +
909 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
910 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
911 +    }
912 +
913 +    Runnable releaser(final CountDownLatch latch) {
914 +        return new Runnable() { public void run() {
915 +            do { latch.countDown(); }
916 +            while (latch.getCount() > 0);
917 +        }};
918 +    }
919 +
920 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
921 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
922 +    }
923 +
924 +    Runnable releaser(final AtomicBoolean flag) {
925 +        return new Runnable() { public void run() { flag.set(true); }};
926      }
927  
928      /**
# Line 748 | Line 931 | public class JSR166TestCase extends Test
931      void joinPool(ExecutorService pool) {
932          try {
933              pool.shutdown();
934 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
935 <                fail("ExecutorService " + pool +
936 <                     " did not terminate in a timely manner");
934 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
935 >                try {
936 >                    threadFail("ExecutorService " + pool +
937 >                               " did not terminate in a timely manner");
938 >                } finally {
939 >                    // last resort, for the benefit of subsequent tests
940 >                    pool.shutdownNow();
941 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
942 >                }
943 >            }
944          } catch (SecurityException ok) {
945              // Allowed in case test doesn't have privs
946          } catch (InterruptedException fail) {
947 <            fail("Unexpected InterruptedException");
947 >            threadFail("Unexpected InterruptedException");
948          }
949      }
950  
# Line 768 | Line 958 | public class JSR166TestCase extends Test
958       */
959      void testInParallel(Action ... actions) {
960          ExecutorService pool = Executors.newCachedThreadPool();
961 <        try {
961 >        try (PoolCleaner cleaner = cleaner(pool)) {
962              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
963              for (final Action action : actions)
964                  futures.add(pool.submit(new CheckedRunnable() {
# Line 781 | Line 971 | public class JSR166TestCase extends Test
971                  } catch (Exception ex) {
972                      threadUnexpectedException(ex);
973                  }
784        } finally {
785            joinPool(pool);
974          }
975      }
976  
977      /**
978 <     * A debugging tool to print all stack traces, as jstack does.
978 >     * A debugging tool to print stack traces of most threads, as jstack does.
979 >     * Uninteresting threads are filtered out.
980       */
981 <    static void printAllStackTraces() {
982 <        for (ThreadInfo info :
983 <                 ManagementFactory.getThreadMXBean()
984 <                 .dumpAllThreads(true, true))
981 >    static void dumpTestThreads() {
982 >        SecurityManager sm = System.getSecurityManager();
983 >        if (sm != null) {
984 >            try {
985 >                System.setSecurityManager(null);
986 >            } catch (SecurityException giveUp) {
987 >                return;
988 >            }
989 >        }
990 >
991 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
992 >        System.err.println("------ stacktrace dump start ------");
993 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
994 >            String name = info.getThreadName();
995 >            if ("Signal Dispatcher".equals(name))
996 >                continue;
997 >            if ("Reference Handler".equals(name)
998 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
999 >                continue;
1000 >            if ("Finalizer".equals(name)
1001 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
1002 >                continue;
1003 >            if ("checkForWedgedTest".equals(name))
1004 >                continue;
1005              System.err.print(info);
1006 +        }
1007 +        System.err.println("------ stacktrace dump end ------");
1008 +
1009 +        if (sm != null) System.setSecurityManager(sm);
1010      }
1011  
1012      /**
# Line 813 | Line 1026 | public class JSR166TestCase extends Test
1026              delay(millis);
1027              assertTrue(thread.isAlive());
1028          } catch (InterruptedException fail) {
1029 <            fail("Unexpected InterruptedException");
1029 >            threadFail("Unexpected InterruptedException");
1030          }
1031      }
1032  
# Line 835 | Line 1048 | public class JSR166TestCase extends Test
1048              for (Thread thread : threads)
1049                  assertTrue(thread.isAlive());
1050          } catch (InterruptedException fail) {
1051 <            fail("Unexpected InterruptedException");
1051 >            threadFail("Unexpected InterruptedException");
1052          }
1053      }
1054  
# Line 1113 | Line 1326 | public class JSR166TestCase extends Test
1326          } finally {
1327              if (t.getState() != Thread.State.TERMINATED) {
1328                  t.interrupt();
1329 <                fail("Test timed out");
1329 >                threadFail("timed out waiting for thread to terminate");
1330              }
1331          }
1332      }
# Line 1254 | Line 1467 | public class JSR166TestCase extends Test
1467              }};
1468      }
1469  
1470 <    public Runnable awaiter(final CountDownLatch latch) {
1470 >    public Runnable countDowner(final CountDownLatch latch) {
1471          return new CheckedRunnable() {
1472              public void realRun() throws InterruptedException {
1473 <                await(latch);
1473 >                latch.countDown();
1474              }};
1475      }
1476  
1477 <    public void await(CountDownLatch latch) {
1477 >    class LatchAwaiter extends CheckedRunnable {
1478 >        static final int NEW = 0;
1479 >        static final int RUNNING = 1;
1480 >        static final int DONE = 2;
1481 >        final CountDownLatch latch;
1482 >        int state = NEW;
1483 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1484 >        public void realRun() throws InterruptedException {
1485 >            state = 1;
1486 >            await(latch);
1487 >            state = 2;
1488 >        }
1489 >    }
1490 >
1491 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1492 >        return new LatchAwaiter(latch);
1493 >    }
1494 >
1495 >    public void await(CountDownLatch latch, long timeoutMillis) {
1496          try {
1497 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1497 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1498 >                fail("timed out waiting for CountDownLatch for "
1499 >                     + (timeoutMillis/1000) + " sec");
1500          } catch (Throwable fail) {
1501              threadUnexpectedException(fail);
1502          }
1503      }
1504  
1505 +    public void await(CountDownLatch latch) {
1506 +        await(latch, LONG_DELAY_MS);
1507 +    }
1508 +
1509      public void await(Semaphore semaphore) {
1510          try {
1511 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1511 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1512 >                fail("timed out waiting for Semaphore for "
1513 >                     + (LONG_DELAY_MS/1000) + " sec");
1514          } catch (Throwable fail) {
1515              threadUnexpectedException(fail);
1516          }
# Line 1607 | Line 1846 | public class JSR166TestCase extends Test
1846          } catch (NoSuchElementException success) {}
1847          assertFalse(it.hasNext());
1848      }
1849 +
1850 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1851 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1852 +    }
1853 +
1854 +    public Runnable runnableThrowing(final RuntimeException ex) {
1855 +        return new Runnable() { public void run() { throw ex; }};
1856 +    }
1857 +
1858 +    /** A reusable thread pool to be shared by tests. */
1859 +    static final ExecutorService cachedThreadPool =
1860 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1861 +                               1000L, MILLISECONDS,
1862 +                               new SynchronousQueue<Runnable>());
1863 +
1864   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines