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.159 by jsr166, Sun Oct 4 00:30:50 2015 UTC vs.
Revision 1.181 by jsr166, Mon Nov 9 06:06:54 2015 UTC

# Line 20 | Line 20 | import java.lang.management.ThreadMXBean
20   import java.lang.reflect.Constructor;
21   import java.lang.reflect.Method;
22   import java.lang.reflect.Modifier;
23 + import java.nio.file.Files;
24 + import java.nio.file.Paths;
25   import java.security.CodeSource;
26   import java.security.Permission;
27   import java.security.PermissionCollection;
# Line 52 | Line 54 | import java.util.concurrent.ThreadFactor
54   import java.util.concurrent.ThreadPoolExecutor;
55   import java.util.concurrent.TimeoutException;
56   import java.util.concurrent.atomic.AtomicReference;
57 + import java.util.regex.Matcher;
58   import java.util.regex.Pattern;
59  
60   import junit.framework.AssertionFailedError;
# Line 109 | Line 112 | import junit.framework.TestSuite;
112   * methods as there are exceptions the method can throw. Sometimes
113   * there are multiple tests per JSR166 method when the different
114   * "normal" behaviors differ significantly. And sometimes testcases
115 < * cover multiple methods when they cannot be tested in
113 < * isolation.
115 > * cover multiple methods when they cannot be tested in isolation.
116   *
117   * <li>The documentation style for testcases is to provide as javadoc
118   * a simple sentence or two describing the property that the testcase
# Line 173 | Line 175 | public class JSR166TestCase extends Test
175      private static final int suiteRuns =
176          Integer.getInteger("jsr166.suiteRuns", 1);
177  
178 +    /**
179 +     * The scaling factor to apply to standard delays used in tests.
180 +     */
181 +    private static final int delayFactor =
182 +        Integer.getInteger("jsr166.delay.factor", 1);
183 +
184      public JSR166TestCase() { super(); }
185      public JSR166TestCase(String name) { super(name); }
186  
# Line 188 | Line 196 | public class JSR166TestCase extends Test
196          return (regex == null) ? null : Pattern.compile(regex);
197      }
198  
199 +    // Instrumentation to debug very rare, but very annoying hung test runs.
200      static volatile TestCase currentTestCase;
201 +    // static volatile int currentRun = 0;
202      static {
203          Runnable checkForWedgedTest = new Runnable() { public void run() {
204 <            // avoid spurious reports with enormous runsPerTest
205 <            final int timeoutMinutes = Math.max(runsPerTest / 10, 1);
204 >            // Avoid spurious reports with enormous runsPerTest.
205 >            // A single test case run should never take more than 1 second.
206 >            // But let's cap it at the high end too ...
207 >            final int timeoutMinutes =
208 >                Math.min(15, Math.max(runsPerTest / 60, 1));
209              for (TestCase lastTestCase = currentTestCase;;) {
210                  try { MINUTES.sleep(timeoutMinutes); }
211                  catch (InterruptedException unexpected) { break; }
212                  if (lastTestCase == currentTestCase) {
213 <                    System.err.println
214 <                        ("Looks like we're stuck running test: "
215 <                         + lastTestCase);
213 >                    System.err.printf(
214 >                        "Looks like we're stuck running test: %s%n",
215 >                        lastTestCase);
216 > //                     System.err.printf(
217 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
218 > //                         lastTestCase, currentRun, runsPerTest);
219 > //                     System.err.println("availableProcessors=" +
220 > //                         Runtime.getRuntime().availableProcessors());
221 > //                     System.err.printf("cpu model = %s%n", cpuModel());
222                      dumpTestThreads();
223 +                    // one stack dump is probably enough; more would be spam
224 +                    break;
225                  }
226                  lastTestCase = currentTestCase;
227              }}};
# Line 209 | Line 230 | public class JSR166TestCase extends Test
230          thread.start();
231      }
232  
233 + //     public static String cpuModel() {
234 + //         try {
235 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
236 + //                 .matcher(new String(
237 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
238 + //             matcher.find();
239 + //             return matcher.group(1);
240 + //         } catch (Exception ex) { return null; }
241 + //     }
242 +
243      public void runBare() throws Throwable {
244          currentTestCase = this;
245          if (methodFilter == null
# Line 218 | Line 249 | public class JSR166TestCase extends Test
249  
250      protected void runTest() throws Throwable {
251          for (int i = 0; i < runsPerTest; i++) {
252 +            // currentRun = i;
253              if (profileTests)
254                  runTestProfiled();
255              else
# Line 246 | Line 278 | public class JSR166TestCase extends Test
278          main(suite(), args);
279      }
280  
281 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
282 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
283 +        long runTime;
284 +        public void startTest(Test test) {}
285 +        protected void printHeader(long runTime) {
286 +            this.runTime = runTime; // defer printing for later
287 +        }
288 +        protected void printFooter(TestResult result) {
289 +            if (result.wasSuccessful()) {
290 +                getWriter().println("OK (" + result.runCount() + " tests)"
291 +                    + "  Time: " + elapsedTimeAsString(runTime));
292 +            } else {
293 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
294 +                super.printFooter(result);
295 +            }
296 +        }
297 +    }
298 +
299 +    /**
300 +     * Returns a TestRunner that doesn't bother with unnecessary
301 +     * fluff, like printing a "." for each test case.
302 +     */
303 +    static junit.textui.TestRunner newPithyTestRunner() {
304 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
305 +        runner.setPrinter(new PithyResultPrinter(System.out));
306 +        return runner;
307 +    }
308 +
309      /**
310       * Runs all unit tests in the given test suite.
311       * Actual behavior influenced by jsr166.* system properties.
# Line 257 | Line 317 | public class JSR166TestCase extends Test
317              System.setSecurityManager(new SecurityManager());
318          }
319          for (int i = 0; i < suiteRuns; i++) {
320 <            TestResult result = junit.textui.TestRunner.run(suite);
320 >            TestResult result = newPithyTestRunner().doRun(suite);
321              if (!result.wasSuccessful())
322                  System.exit(1);
323              System.gc();
# Line 494 | Line 554 | public class JSR166TestCase extends Test
554      public static long LONG_DELAY_MS;
555  
556      /**
557 <     * Returns the shortest timed delay. This could
558 <     * be reimplemented to use for example a Property.
557 >     * Returns the shortest timed delay. This can be scaled up for
558 >     * slow machines using the jsr166.delay.factor system property.
559       */
560      protected long getShortDelay() {
561 <        return 50;
561 >        return 50 * delayFactor;
562      }
563  
564      /**
# Line 590 | Line 650 | public class JSR166TestCase extends Test
650      }
651  
652      /**
653 <     * Finds missing try { ... } finally { joinPool(e); }
653 >     * Finds missing PoolCleaners
654       */
655      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
656          Thread[] survivors = new Thread[7];
# Line 749 | Line 809 | public class JSR166TestCase extends Test
809      /**
810       * Delays, via Thread.sleep, for the given millisecond delay, but
811       * if the sleep is shorter than specified, may re-sleep or yield
812 <     * until time elapses.
812 >     * until time elapses.  Ensures that the given time, as measured
813 >     * by System.nanoTime(), has elapsed.
814       */
815      static void delay(long millis) throws InterruptedException {
816 <        long startTime = System.nanoTime();
817 <        long ns = millis * 1000 * 1000;
818 <        for (;;) {
816 >        long nanos = millis * (1000 * 1000);
817 >        final long wakeupTime = System.nanoTime() + nanos;
818 >        do {
819              if (millis > 0L)
820                  Thread.sleep(millis);
821              else // too short to sleep
822                  Thread.yield();
823 <            long d = ns - (System.nanoTime() - startTime);
824 <            if (d > 0L)
825 <                millis = d / (1000 * 1000);
765 <            else
766 <                break;
767 <        }
823 >            nanos = wakeupTime - System.nanoTime();
824 >            millis = nanos / (1000 * 1000);
825 >        } while (nanos >= 0L);
826      }
827  
828      /**
829       * Allows use of try-with-resources with per-test thread pools.
830       */
831 <    class PoolCleaner<T extends ExecutorService>
832 <            implements AutoCloseable {
833 <        public final T pool;
776 <        public PoolCleaner(T pool) { this.pool = pool; }
831 >    class PoolCleaner implements AutoCloseable {
832 >        private final ExecutorService pool;
833 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
834          public void close() { joinPool(pool); }
835      }
836  
837 <    <T extends ExecutorService> PoolCleaner<T> cleaner(T pool) {
838 <        return new PoolCleaner<T>(pool);
837 >    /**
838 >     * An extension of PoolCleaner that has an action to release the pool.
839 >     */
840 >    class PoolCleanerWithReleaser extends PoolCleaner {
841 >        private final Runnable releaser;
842 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
843 >            super(pool);
844 >            this.releaser = releaser;
845 >        }
846 >        public void close() {
847 >            try {
848 >                releaser.run();
849 >            } finally {
850 >                super.close();
851 >            }
852 >        }
853 >    }
854 >
855 >    PoolCleaner cleaner(ExecutorService pool) {
856 >        return new PoolCleaner(pool);
857 >    }
858 >
859 >    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
860 >        return new PoolCleanerWithReleaser(pool, releaser);
861 >    }
862 >
863 >    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
864 >        return new PoolCleanerWithReleaser(pool, releaser(latch));
865 >    }
866 >
867 >    Runnable releaser(final CountDownLatch latch) {
868 >        return new Runnable() { public void run() {
869 >            do { latch.countDown(); }
870 >            while (latch.getCount() > 0);
871 >        }};
872      }
873  
874      /**
# Line 794 | Line 884 | public class JSR166TestCase extends Test
884                  } finally {
885                      // last resort, for the benefit of subsequent tests
886                      pool.shutdownNow();
887 <                    pool.awaitTermination(SMALL_DELAY_MS, MILLISECONDS);
887 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
888                  }
889              }
890          } catch (SecurityException ok) {
# Line 813 | Line 903 | public class JSR166TestCase extends Test
903       * necessarily individually slow because they must block.
904       */
905      void testInParallel(Action ... actions) {
906 <        try (PoolCleaner<ExecutorService> cleaner
907 <             = cleaner(Executors.newCachedThreadPool())) {
818 <            ExecutorService pool = cleaner.pool;
906 >        ExecutorService pool = Executors.newCachedThreadPool();
907 >        try (PoolCleaner cleaner = cleaner(pool)) {
908              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
909              for (final Action action : actions)
910                  futures.add(pool.submit(new CheckedRunnable() {
# Line 1172 | Line 1261 | public class JSR166TestCase extends Test
1261          } finally {
1262              if (t.getState() != Thread.State.TERMINATED) {
1263                  t.interrupt();
1264 <                fail("Test timed out");
1264 >                threadFail("timed out waiting for thread to terminate");
1265              }
1266          }
1267      }
# Line 1320 | Line 1409 | public class JSR166TestCase extends Test
1409              }};
1410      }
1411  
1412 <    public Runnable awaiter(final CountDownLatch latch) {
1413 <        return new CheckedRunnable() {
1414 <            public void realRun() throws InterruptedException {
1415 <                await(latch);
1416 <            }};
1412 >    class LatchAwaiter extends CheckedRunnable {
1413 >        static final int NEW = 0;
1414 >        static final int RUNNING = 1;
1415 >        static final int DONE = 2;
1416 >        final CountDownLatch latch;
1417 >        int state = NEW;
1418 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1419 >        public void realRun() throws InterruptedException {
1420 >            state = 1;
1421 >            await(latch);
1422 >            state = 2;
1423 >        }
1424 >    }
1425 >
1426 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1427 >        return new LatchAwaiter(latch);
1428      }
1429  
1430      public void await(CountDownLatch latch) {
1431          try {
1432 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1432 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1433 >                fail("timed out waiting for CountDownLatch for "
1434 >                     + (LONG_DELAY_MS/1000) + " sec");
1435          } catch (Throwable fail) {
1436              threadUnexpectedException(fail);
1437          }
# Line 1337 | Line 1439 | public class JSR166TestCase extends Test
1439  
1440      public void await(Semaphore semaphore) {
1441          try {
1442 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1442 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1443 >                fail("timed out waiting for Semaphore for "
1444 >                     + (LONG_DELAY_MS/1000) + " sec");
1445          } catch (Throwable fail) {
1446              threadUnexpectedException(fail);
1447          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines