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.151 by jsr166, Sat Oct 3 19:19:01 2015 UTC vs.
Revision 1.185 by jsr166, Mon Feb 22 19:36:59 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 + */
16 +
17   import static java.util.concurrent.TimeUnit.MILLISECONDS;
18 + import static java.util.concurrent.TimeUnit.MINUTES;
19   import static java.util.concurrent.TimeUnit.NANOSECONDS;
20  
21   import java.io.ByteArrayInputStream;
# Line 19 | Line 28 | import java.lang.management.ThreadMXBean
28   import java.lang.reflect.Constructor;
29   import java.lang.reflect.Method;
30   import java.lang.reflect.Modifier;
31 + import java.nio.file.Files;
32 + import java.nio.file.Paths;
33   import java.security.CodeSource;
34   import java.security.Permission;
35   import java.security.PermissionCollection;
# Line 50 | Line 61 | import java.util.concurrent.Semaphore;
61   import java.util.concurrent.ThreadFactory;
62   import java.util.concurrent.ThreadPoolExecutor;
63   import java.util.concurrent.TimeoutException;
64 + import java.util.concurrent.atomic.AtomicBoolean;
65   import java.util.concurrent.atomic.AtomicReference;
66 + import java.util.regex.Matcher;
67   import java.util.regex.Pattern;
68  
69   import junit.framework.AssertionFailedError;
# Line 108 | Line 121 | import junit.framework.TestSuite;
121   * methods as there are exceptions the method can throw. Sometimes
122   * there are multiple tests per JSR166 method when the different
123   * "normal" behaviors differ significantly. And sometimes testcases
124 < * cover multiple methods when they cannot be tested in
112 < * isolation.
124 > * cover multiple methods when they cannot be tested in isolation.
125   *
126   * <li>The documentation style for testcases is to provide as javadoc
127   * a simple sentence or two describing the property that the testcase
# Line 172 | Line 184 | public class JSR166TestCase extends Test
184      private static final int suiteRuns =
185          Integer.getInteger("jsr166.suiteRuns", 1);
186  
187 +    private static float systemPropertyValue(String name, float defaultValue) {
188 +        String floatString = System.getProperty(name);
189 +        if (floatString == null)
190 +            return defaultValue;
191 +        try {
192 +            return Float.parseFloat(floatString);
193 +        } catch (NumberFormatException ex) {
194 +            throw new IllegalArgumentException(
195 +                String.format("Bad float value in system property %s=%s",
196 +                              name, floatString));
197 +        }
198 +    }
199 +
200 +    /**
201 +     * The scaling factor to apply to standard delays used in tests.
202 +     */
203 +    private static final float delayFactor =
204 +        systemPropertyValue("jsr166.delay.factor", 1.0f);
205 +    
206 +    /**
207 +     * The timeout factor as used in the jtreg test harness.
208 +     * See: http://openjdk.java.net/jtreg/tag-spec.html
209 +     */
210 +    private static final float jtregTestTimeoutFactor
211 +        = systemPropertyValue("test.timeout.factor", 1.0f);
212 +
213      public JSR166TestCase() { super(); }
214      public JSR166TestCase(String name) { super(name); }
215  
# Line 187 | Line 225 | public class JSR166TestCase extends Test
225          return (regex == null) ? null : Pattern.compile(regex);
226      }
227  
228 +    // Instrumentation to debug very rare, but very annoying hung test runs.
229 +    static volatile TestCase currentTestCase;
230 +    // static volatile int currentRun = 0;
231 +    static {
232 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
233 +            // Avoid spurious reports with enormous runsPerTest.
234 +            // A single test case run should never take more than 1 second.
235 +            // But let's cap it at the high end too ...
236 +            final int timeoutMinutes =
237 +                Math.min(15, Math.max(runsPerTest / 60, 1));
238 +            for (TestCase lastTestCase = currentTestCase;;) {
239 +                try { MINUTES.sleep(timeoutMinutes); }
240 +                catch (InterruptedException unexpected) { break; }
241 +                if (lastTestCase == currentTestCase) {
242 +                    System.err.printf(
243 +                        "Looks like we're stuck running test: %s%n",
244 +                        lastTestCase);
245 + //                     System.err.printf(
246 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
247 + //                         lastTestCase, currentRun, runsPerTest);
248 + //                     System.err.println("availableProcessors=" +
249 + //                         Runtime.getRuntime().availableProcessors());
250 + //                     System.err.printf("cpu model = %s%n", cpuModel());
251 +                    dumpTestThreads();
252 +                    // one stack dump is probably enough; more would be spam
253 +                    break;
254 +                }
255 +                lastTestCase = currentTestCase;
256 +            }}};
257 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
258 +        thread.setDaemon(true);
259 +        thread.start();
260 +    }
261 +
262 + //     public static String cpuModel() {
263 + //         try {
264 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
265 + //                 .matcher(new String(
266 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
267 + //             matcher.find();
268 + //             return matcher.group(1);
269 + //         } catch (Exception ex) { return null; }
270 + //     }
271 +
272      public void runBare() throws Throwable {
273 +        currentTestCase = this;
274          if (methodFilter == null
275              || methodFilter.matcher(toString()).find())
276              super.runBare();
# Line 195 | Line 278 | public class JSR166TestCase extends Test
278  
279      protected void runTest() throws Throwable {
280          for (int i = 0; i < runsPerTest; i++) {
281 +            // currentRun = i;
282              if (profileTests)
283                  runTestProfiled();
284              else
# Line 223 | Line 307 | public class JSR166TestCase extends Test
307          main(suite(), args);
308      }
309  
310 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
311 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
312 +        long runTime;
313 +        public void startTest(Test test) {}
314 +        protected void printHeader(long runTime) {
315 +            this.runTime = runTime; // defer printing for later
316 +        }
317 +        protected void printFooter(TestResult result) {
318 +            if (result.wasSuccessful()) {
319 +                getWriter().println("OK (" + result.runCount() + " tests)"
320 +                    + "  Time: " + elapsedTimeAsString(runTime));
321 +            } else {
322 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
323 +                super.printFooter(result);
324 +            }
325 +        }
326 +    }
327 +
328 +    /**
329 +     * Returns a TestRunner that doesn't bother with unnecessary
330 +     * fluff, like printing a "." for each test case.
331 +     */
332 +    static junit.textui.TestRunner newPithyTestRunner() {
333 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
334 +        runner.setPrinter(new PithyResultPrinter(System.out));
335 +        return runner;
336 +    }
337 +
338      /**
339       * Runs all unit tests in the given test suite.
340       * Actual behavior influenced by jsr166.* system properties.
# Line 234 | Line 346 | public class JSR166TestCase extends Test
346              System.setSecurityManager(new SecurityManager());
347          }
348          for (int i = 0; i < suiteRuns; i++) {
349 <            TestResult result = junit.textui.TestRunner.run(suite);
349 >            TestResult result = newPithyTestRunner().doRun(suite);
350              if (!result.wasSuccessful())
351                  System.exit(1);
352              System.gc();
# Line 461 | Line 573 | public class JSR166TestCase extends Test
573          } else {
574              return new TestSuite();
575          }
464
576      }
577  
578      // Delays for timing-dependent tests, in milliseconds.
# Line 472 | Line 583 | public class JSR166TestCase extends Test
583      public static long LONG_DELAY_MS;
584  
585      /**
586 <     * Returns the shortest timed delay. This could
587 <     * be reimplemented to use for example a Property.
586 >     * Returns the shortest timed delay. This can be scaled up for
587 >     * slow machines using the jsr166.delay.factor system property,
588 >     * or via jtreg's -timeoutFactor:<val> flag.
589 >     * http://openjdk.java.net/jtreg/command-help.html
590       */
591      protected long getShortDelay() {
592 <        return 50;
592 >        return (long) (50 * delayFactor * jtregTestTimeoutFactor);
593      }
594  
595      /**
# Line 519 | Line 632 | public class JSR166TestCase extends Test
632       * the same test have no effect.
633       */
634      public void threadRecordFailure(Throwable t) {
635 +        System.err.println(t);
636 +        dumpTestThreads();
637          threadFailure.compareAndSet(null, t);
638      }
639  
# Line 529 | Line 644 | public class JSR166TestCase extends Test
644      void tearDownFail(String format, Object... args) {
645          String msg = toString() + ": " + String.format(format, args);
646          System.err.println(msg);
647 <        printAllStackTraces();
647 >        dumpTestThreads();
648          throw new AssertionFailedError(msg);
649      }
650  
# Line 566 | Line 681 | public class JSR166TestCase extends Test
681      }
682  
683      /**
684 <     * Finds missing try { ... } finally { joinPool(e); }
684 >     * Finds missing PoolCleaners
685       */
686      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
687          Thread[] survivors = new Thread[7];
# Line 598 | Line 713 | public class JSR166TestCase extends Test
713              fail(reason);
714          } catch (AssertionFailedError t) {
715              threadRecordFailure(t);
716 <            fail(reason);
716 >            throw t;
717          }
718      }
719  
# Line 725 | Line 840 | public class JSR166TestCase extends Test
840      /**
841       * Delays, via Thread.sleep, for the given millisecond delay, but
842       * if the sleep is shorter than specified, may re-sleep or yield
843 <     * until time elapses.
843 >     * until time elapses.  Ensures that the given time, as measured
844 >     * by System.nanoTime(), has elapsed.
845       */
846      static void delay(long millis) throws InterruptedException {
847 <        long startTime = System.nanoTime();
848 <        long ns = millis * 1000 * 1000;
849 <        for (;;) {
847 >        long nanos = millis * (1000 * 1000);
848 >        final long wakeupTime = System.nanoTime() + nanos;
849 >        do {
850              if (millis > 0L)
851                  Thread.sleep(millis);
852              else // too short to sleep
853                  Thread.yield();
854 <            long d = ns - (System.nanoTime() - startTime);
855 <            if (d > 0L)
856 <                millis = d / (1000 * 1000);
741 <            else
742 <                break;
743 <        }
854 >            nanos = wakeupTime - System.nanoTime();
855 >            millis = nanos / (1000 * 1000);
856 >        } while (nanos >= 0L);
857      }
858  
859      /**
860       * Allows use of try-with-resources with per-test thread pools.
861       */
862 <    static class PoolCloser<T extends ExecutorService>
863 <            implements AutoCloseable {
864 <        public final T pool;
752 <        public PoolCloser(T pool) { this.pool = pool; }
862 >    class PoolCleaner implements AutoCloseable {
863 >        private final ExecutorService pool;
864 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
865          public void close() { joinPool(pool); }
866      }
867  
868      /**
869 +     * An extension of PoolCleaner that has an action to release the pool.
870 +     */
871 +    class PoolCleanerWithReleaser extends PoolCleaner {
872 +        private final Runnable releaser;
873 +        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
874 +            super(pool);
875 +            this.releaser = releaser;
876 +        }
877 +        public void close() {
878 +            try {
879 +                releaser.run();
880 +            } finally {
881 +                super.close();
882 +            }
883 +        }
884 +    }
885 +
886 +    PoolCleaner cleaner(ExecutorService pool) {
887 +        return new PoolCleaner(pool);
888 +    }
889 +
890 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
891 +        return new PoolCleanerWithReleaser(pool, releaser);
892 +    }
893 +
894 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
895 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
896 +    }
897 +
898 +    Runnable releaser(final CountDownLatch latch) {
899 +        return new Runnable() { public void run() {
900 +            do { latch.countDown(); }
901 +            while (latch.getCount() > 0);
902 +        }};
903 +    }
904 +
905 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
906 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
907 +    }
908 +
909 +    Runnable releaser(final AtomicBoolean flag) {
910 +        return new Runnable() { public void run() { flag.set(true); }};
911 +    }
912 +
913 +    /**
914       * Waits out termination of a thread pool or fails doing so.
915       */
916 <    static void joinPool(ExecutorService pool) {
916 >    void joinPool(ExecutorService pool) {
917          try {
918              pool.shutdown();
919 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
920 <                fail("ExecutorService " + pool +
921 <                     " did not terminate in a timely manner");
919 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
920 >                try {
921 >                    threadFail("ExecutorService " + pool +
922 >                               " did not terminate in a timely manner");
923 >                } finally {
924 >                    // last resort, for the benefit of subsequent tests
925 >                    pool.shutdownNow();
926 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
927 >                }
928 >            }
929          } catch (SecurityException ok) {
930              // Allowed in case test doesn't have privs
931          } catch (InterruptedException fail) {
932 <            fail("Unexpected InterruptedException");
932 >            threadFail("Unexpected InterruptedException");
933          }
934      }
935  
# Line 778 | Line 942 | public class JSR166TestCase extends Test
942       * necessarily individually slow because they must block.
943       */
944      void testInParallel(Action ... actions) {
945 <        try (PoolCloser<ExecutorService> poolCloser
946 <             = new PoolCloser<>(Executors.newCachedThreadPool())) {
783 <            ExecutorService pool = poolCloser.pool;
945 >        ExecutorService pool = Executors.newCachedThreadPool();
946 >        try (PoolCleaner cleaner = cleaner(pool)) {
947              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
948              for (final Action action : actions)
949                  futures.add(pool.submit(new CheckedRunnable() {
# Line 797 | Line 960 | public class JSR166TestCase extends Test
960      }
961  
962      /**
963 <     * A debugging tool to print all stack traces, as jstack does.
963 >     * A debugging tool to print stack traces of most threads, as jstack does.
964       * Uninteresting threads are filtered out.
965       */
966 <    static void printAllStackTraces() {
966 >    static void dumpTestThreads() {
967          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
968          System.err.println("------ stacktrace dump start ------");
969          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
# Line 813 | Line 976 | public class JSR166TestCase extends Test
976              if ("Finalizer".equals(name)
977                  && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
978                  continue;
979 +            if ("checkForWedgedTest".equals(name))
980 +                continue;
981              System.err.print(info);
982          }
983          System.err.println("------ stacktrace dump end ------");
# Line 835 | Line 1000 | public class JSR166TestCase extends Test
1000              delay(millis);
1001              assertTrue(thread.isAlive());
1002          } catch (InterruptedException fail) {
1003 <            fail("Unexpected InterruptedException");
1003 >            threadFail("Unexpected InterruptedException");
1004          }
1005      }
1006  
# Line 857 | Line 1022 | public class JSR166TestCase extends Test
1022              for (Thread thread : threads)
1023                  assertTrue(thread.isAlive());
1024          } catch (InterruptedException fail) {
1025 <            fail("Unexpected InterruptedException");
1025 >            threadFail("Unexpected InterruptedException");
1026          }
1027      }
1028  
# Line 1135 | Line 1300 | public class JSR166TestCase extends Test
1300          } finally {
1301              if (t.getState() != Thread.State.TERMINATED) {
1302                  t.interrupt();
1303 <                fail("Test timed out");
1303 >                threadFail("timed out waiting for thread to terminate");
1304              }
1305          }
1306      }
# Line 1283 | Line 1448 | public class JSR166TestCase extends Test
1448              }};
1449      }
1450  
1451 <    public Runnable awaiter(final CountDownLatch latch) {
1452 <        return new CheckedRunnable() {
1453 <            public void realRun() throws InterruptedException {
1454 <                await(latch);
1455 <            }};
1451 >    class LatchAwaiter extends CheckedRunnable {
1452 >        static final int NEW = 0;
1453 >        static final int RUNNING = 1;
1454 >        static final int DONE = 2;
1455 >        final CountDownLatch latch;
1456 >        int state = NEW;
1457 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1458 >        public void realRun() throws InterruptedException {
1459 >            state = 1;
1460 >            await(latch);
1461 >            state = 2;
1462 >        }
1463 >    }
1464 >
1465 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1466 >        return new LatchAwaiter(latch);
1467      }
1468  
1469      public void await(CountDownLatch latch) {
1470          try {
1471 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1471 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1472 >                fail("timed out waiting for CountDownLatch for "
1473 >                     + (LONG_DELAY_MS/1000) + " sec");
1474          } catch (Throwable fail) {
1475              threadUnexpectedException(fail);
1476          }
# Line 1300 | Line 1478 | public class JSR166TestCase extends Test
1478  
1479      public void await(Semaphore semaphore) {
1480          try {
1481 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1481 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1482 >                fail("timed out waiting for Semaphore for "
1483 >                     + (LONG_DELAY_MS/1000) + " sec");
1484          } catch (Throwable fail) {
1485              threadUnexpectedException(fail);
1486          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines