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.145 by jsr166, Fri Sep 25 05:41:29 2015 UTC vs.
Revision 1.182 by jsr166, Sun Jan 17 00:07:51 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 + /*
10 + * @test
11 + * @summary JSR-166 tck tests
12 + * @build *
13 + * @run junit/othervm/timeout=1000 JSR166TestCase
14 + */
15 +
16   import static java.util.concurrent.TimeUnit.MILLISECONDS;
17 + import static java.util.concurrent.TimeUnit.MINUTES;
18   import static java.util.concurrent.TimeUnit.NANOSECONDS;
19  
20   import java.io.ByteArrayInputStream;
# Line 15 | Line 23 | import java.io.ObjectInputStream;
23   import java.io.ObjectOutputStream;
24   import java.lang.management.ManagementFactory;
25   import java.lang.management.ThreadInfo;
26 + import java.lang.management.ThreadMXBean;
27   import java.lang.reflect.Constructor;
28   import java.lang.reflect.Method;
29   import java.lang.reflect.Modifier;
30 + import java.nio.file.Files;
31 + import java.nio.file.Paths;
32   import java.security.CodeSource;
33   import java.security.Permission;
34   import java.security.PermissionCollection;
# Line 40 | Line 51 | import java.util.concurrent.CyclicBarrie
51   import java.util.concurrent.ExecutionException;
52   import java.util.concurrent.Executors;
53   import java.util.concurrent.ExecutorService;
54 + import java.util.concurrent.ForkJoinPool;
55   import java.util.concurrent.Future;
56   import java.util.concurrent.RecursiveAction;
57   import java.util.concurrent.RecursiveTask;
# Line 49 | Line 61 | import java.util.concurrent.ThreadFactor
61   import java.util.concurrent.ThreadPoolExecutor;
62   import java.util.concurrent.TimeoutException;
63   import java.util.concurrent.atomic.AtomicReference;
64 + import java.util.regex.Matcher;
65   import java.util.regex.Pattern;
66  
67   import junit.framework.AssertionFailedError;
# Line 106 | Line 119 | import junit.framework.TestSuite;
119   * methods as there are exceptions the method can throw. Sometimes
120   * there are multiple tests per JSR166 method when the different
121   * "normal" behaviors differ significantly. And sometimes testcases
122 < * cover multiple methods when they cannot be tested in
110 < * isolation.
122 > * cover multiple methods when they cannot be tested in isolation.
123   *
124   * <li>The documentation style for testcases is to provide as javadoc
125   * a simple sentence or two describing the property that the testcase
# Line 170 | Line 182 | public class JSR166TestCase extends Test
182      private static final int suiteRuns =
183          Integer.getInteger("jsr166.suiteRuns", 1);
184  
185 +    /**
186 +     * The scaling factor to apply to standard delays used in tests.
187 +     */
188 +    private static final int delayFactor =
189 +        Integer.getInteger("jsr166.delay.factor", 1);
190 +
191      public JSR166TestCase() { super(); }
192      public JSR166TestCase(String name) { super(name); }
193  
# Line 185 | Line 203 | public class JSR166TestCase extends Test
203          return (regex == null) ? null : Pattern.compile(regex);
204      }
205  
206 <    protected void runTest() throws Throwable {
206 >    // Instrumentation to debug very rare, but very annoying hung test runs.
207 >    static volatile TestCase currentTestCase;
208 >    // static volatile int currentRun = 0;
209 >    static {
210 >        Runnable checkForWedgedTest = new Runnable() { public void run() {
211 >            // Avoid spurious reports with enormous runsPerTest.
212 >            // A single test case run should never take more than 1 second.
213 >            // But let's cap it at the high end too ...
214 >            final int timeoutMinutes =
215 >                Math.min(15, Math.max(runsPerTest / 60, 1));
216 >            for (TestCase lastTestCase = currentTestCase;;) {
217 >                try { MINUTES.sleep(timeoutMinutes); }
218 >                catch (InterruptedException unexpected) { break; }
219 >                if (lastTestCase == currentTestCase) {
220 >                    System.err.printf(
221 >                        "Looks like we're stuck running test: %s%n",
222 >                        lastTestCase);
223 > //                     System.err.printf(
224 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
225 > //                         lastTestCase, currentRun, runsPerTest);
226 > //                     System.err.println("availableProcessors=" +
227 > //                         Runtime.getRuntime().availableProcessors());
228 > //                     System.err.printf("cpu model = %s%n", cpuModel());
229 >                    dumpTestThreads();
230 >                    // one stack dump is probably enough; more would be spam
231 >                    break;
232 >                }
233 >                lastTestCase = currentTestCase;
234 >            }}};
235 >        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
236 >        thread.setDaemon(true);
237 >        thread.start();
238 >    }
239 >
240 > //     public static String cpuModel() {
241 > //         try {
242 > //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
243 > //                 .matcher(new String(
244 > //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
245 > //             matcher.find();
246 > //             return matcher.group(1);
247 > //         } catch (Exception ex) { return null; }
248 > //     }
249 >
250 >    public void runBare() throws Throwable {
251 >        currentTestCase = this;
252          if (methodFilter == null
253 <            || methodFilter.matcher(toString()).find()) {
254 <            for (int i = 0; i < runsPerTest; i++) {
255 <                if (profileTests)
256 <                    runTestProfiled();
257 <                else
258 <                    super.runTest();
259 <            }
253 >            || methodFilter.matcher(toString()).find())
254 >            super.runBare();
255 >    }
256 >
257 >    protected void runTest() throws Throwable {
258 >        for (int i = 0; i < runsPerTest; i++) {
259 >            // currentRun = i;
260 >            if (profileTests)
261 >                runTestProfiled();
262 >            else
263 >                super.runTest();
264          }
265      }
266  
# Line 218 | Line 285 | public class JSR166TestCase extends Test
285          main(suite(), args);
286      }
287  
288 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
289 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
290 +        long runTime;
291 +        public void startTest(Test test) {}
292 +        protected void printHeader(long runTime) {
293 +            this.runTime = runTime; // defer printing for later
294 +        }
295 +        protected void printFooter(TestResult result) {
296 +            if (result.wasSuccessful()) {
297 +                getWriter().println("OK (" + result.runCount() + " tests)"
298 +                    + "  Time: " + elapsedTimeAsString(runTime));
299 +            } else {
300 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
301 +                super.printFooter(result);
302 +            }
303 +        }
304 +    }
305 +
306 +    /**
307 +     * Returns a TestRunner that doesn't bother with unnecessary
308 +     * fluff, like printing a "." for each test case.
309 +     */
310 +    static junit.textui.TestRunner newPithyTestRunner() {
311 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
312 +        runner.setPrinter(new PithyResultPrinter(System.out));
313 +        return runner;
314 +    }
315 +
316      /**
317       * Runs all unit tests in the given test suite.
318       * Actual behavior influenced by jsr166.* system properties.
# Line 229 | Line 324 | public class JSR166TestCase extends Test
324              System.setSecurityManager(new SecurityManager());
325          }
326          for (int i = 0; i < suiteRuns; i++) {
327 <            TestResult result = junit.textui.TestRunner.run(suite);
327 >            TestResult result = newPithyTestRunner().doRun(suite);
328              if (!result.wasSuccessful())
329                  System.exit(1);
330              System.gc();
# Line 456 | Line 551 | public class JSR166TestCase extends Test
551          } else {
552              return new TestSuite();
553          }
459
554      }
555  
556      // Delays for timing-dependent tests, in milliseconds.
# Line 467 | Line 561 | public class JSR166TestCase extends Test
561      public static long LONG_DELAY_MS;
562  
563      /**
564 <     * Returns the shortest timed delay. This could
565 <     * be reimplemented to use for example a Property.
564 >     * Returns the shortest timed delay. This can be scaled up for
565 >     * slow machines using the jsr166.delay.factor system property.
566       */
567      protected long getShortDelay() {
568 <        return 50;
568 >        return 50 * delayFactor;
569      }
570  
571      /**
# Line 514 | Line 608 | public class JSR166TestCase extends Test
608       * the same test have no effect.
609       */
610      public void threadRecordFailure(Throwable t) {
611 +        System.err.println(t);
612 +        dumpTestThreads();
613          threadFailure.compareAndSet(null, t);
614      }
615  
# Line 521 | Line 617 | public class JSR166TestCase extends Test
617          setDelays();
618      }
619  
620 +    void tearDownFail(String format, Object... args) {
621 +        String msg = toString() + ": " + String.format(format, args);
622 +        System.err.println(msg);
623 +        dumpTestThreads();
624 +        throw new AssertionFailedError(msg);
625 +    }
626 +
627      /**
628       * Extra checks that get done for all test cases.
629       *
# Line 548 | Line 651 | public class JSR166TestCase extends Test
651          }
652  
653          if (Thread.interrupted())
654 <            throw new AssertionFailedError("interrupt status set in main thread");
654 >            tearDownFail("interrupt status set in main thread");
655  
656          checkForkJoinPoolThreadLeaks();
657      }
658  
659      /**
660 <     * Finds missing try { ... } finally { joinPool(e); }
660 >     * Finds missing PoolCleaners
661       */
662      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
663 <        Thread[] survivors = new Thread[5];
663 >        Thread[] survivors = new Thread[7];
664          int count = Thread.enumerate(survivors);
665          for (int i = 0; i < count; i++) {
666              Thread thread = survivors[i];
# Line 565 | Line 668 | public class JSR166TestCase extends Test
668              if (name.startsWith("ForkJoinPool-")) {
669                  // give thread some time to terminate
670                  thread.join(LONG_DELAY_MS);
671 <                if (!thread.isAlive()) continue;
672 <                throw new AssertionFailedError
673 <                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
571 <                                   toString(), name));
671 >                if (thread.isAlive())
672 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
673 >                                 thread);
674              }
675          }
676 +
677 +        if (!ForkJoinPool.commonPool()
678 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
679 +            tearDownFail("ForkJoin common pool thread stuck");
680      }
681  
682      /**
# Line 583 | Line 689 | public class JSR166TestCase extends Test
689              fail(reason);
690          } catch (AssertionFailedError t) {
691              threadRecordFailure(t);
692 <            fail(reason);
692 >            throw t;
693          }
694      }
695  
# Line 710 | Line 816 | public class JSR166TestCase extends Test
816      /**
817       * Delays, via Thread.sleep, for the given millisecond delay, but
818       * if the sleep is shorter than specified, may re-sleep or yield
819 <     * until time elapses.
819 >     * until time elapses.  Ensures that the given time, as measured
820 >     * by System.nanoTime(), has elapsed.
821       */
822      static void delay(long millis) throws InterruptedException {
823 <        long startTime = System.nanoTime();
824 <        long ns = millis * 1000 * 1000;
825 <        for (;;) {
823 >        long nanos = millis * (1000 * 1000);
824 >        final long wakeupTime = System.nanoTime() + nanos;
825 >        do {
826              if (millis > 0L)
827                  Thread.sleep(millis);
828              else // too short to sleep
829                  Thread.yield();
830 <            long d = ns - (System.nanoTime() - startTime);
831 <            if (d > 0L)
832 <                millis = d / (1000 * 1000);
833 <            else
834 <                break;
830 >            nanos = wakeupTime - System.nanoTime();
831 >            millis = nanos / (1000 * 1000);
832 >        } while (nanos >= 0L);
833 >    }
834 >
835 >    /**
836 >     * Allows use of try-with-resources with per-test thread pools.
837 >     */
838 >    class PoolCleaner implements AutoCloseable {
839 >        private final ExecutorService pool;
840 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
841 >        public void close() { joinPool(pool); }
842 >    }
843 >
844 >    /**
845 >     * An extension of PoolCleaner that has an action to release the pool.
846 >     */
847 >    class PoolCleanerWithReleaser extends PoolCleaner {
848 >        private final Runnable releaser;
849 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
850 >            super(pool);
851 >            this.releaser = releaser;
852 >        }
853 >        public void close() {
854 >            try {
855 >                releaser.run();
856 >            } finally {
857 >                super.close();
858 >            }
859          }
860      }
861  
862 +    PoolCleaner cleaner(ExecutorService pool) {
863 +        return new PoolCleaner(pool);
864 +    }
865 +
866 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
867 +        return new PoolCleanerWithReleaser(pool, releaser);
868 +    }
869 +
870 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
871 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
872 +    }
873 +
874 +    Runnable releaser(final CountDownLatch latch) {
875 +        return new Runnable() { public void run() {
876 +            do { latch.countDown(); }
877 +            while (latch.getCount() > 0);
878 +        }};
879 +    }
880 +
881      /**
882       * Waits out termination of a thread pool or fails doing so.
883       */
884      void joinPool(ExecutorService pool) {
885          try {
886              pool.shutdown();
887 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
888 <                fail("ExecutorService " + pool +
889 <                     " did not terminate in a timely manner");
887 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
888 >                try {
889 >                    threadFail("ExecutorService " + pool +
890 >                               " did not terminate in a timely manner");
891 >                } finally {
892 >                    // last resort, for the benefit of subsequent tests
893 >                    pool.shutdownNow();
894 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
895 >                }
896 >            }
897          } catch (SecurityException ok) {
898              // Allowed in case test doesn't have privs
899          } catch (InterruptedException fail) {
900 <            fail("Unexpected InterruptedException");
900 >            threadFail("Unexpected InterruptedException");
901          }
902      }
903  
# Line 754 | Line 911 | public class JSR166TestCase extends Test
911       */
912      void testInParallel(Action ... actions) {
913          ExecutorService pool = Executors.newCachedThreadPool();
914 <        try {
914 >        try (PoolCleaner cleaner = cleaner(pool)) {
915              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
916              for (final Action action : actions)
917                  futures.add(pool.submit(new CheckedRunnable() {
# Line 767 | Line 924 | public class JSR166TestCase extends Test
924                  } catch (Exception ex) {
925                      threadUnexpectedException(ex);
926                  }
770        } finally {
771            joinPool(pool);
927          }
928      }
929  
930      /**
931 <     * A debugging tool to print all stack traces, as jstack does.
931 >     * A debugging tool to print stack traces of most threads, as jstack does.
932 >     * Uninteresting threads are filtered out.
933       */
934 <    static void printAllStackTraces() {
935 <        for (ThreadInfo info :
936 <                 ManagementFactory.getThreadMXBean()
937 <                 .dumpAllThreads(true, true))
934 >    static void dumpTestThreads() {
935 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
936 >        System.err.println("------ stacktrace dump start ------");
937 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
938 >            String name = info.getThreadName();
939 >            if ("Signal Dispatcher".equals(name))
940 >                continue;
941 >            if ("Reference Handler".equals(name)
942 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
943 >                continue;
944 >            if ("Finalizer".equals(name)
945 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
946 >                continue;
947 >            if ("checkForWedgedTest".equals(name))
948 >                continue;
949              System.err.print(info);
950 +        }
951 +        System.err.println("------ stacktrace dump end ------");
952      }
953  
954      /**
# Line 799 | Line 968 | public class JSR166TestCase extends Test
968              delay(millis);
969              assertTrue(thread.isAlive());
970          } catch (InterruptedException fail) {
971 <            fail("Unexpected InterruptedException");
971 >            threadFail("Unexpected InterruptedException");
972          }
973      }
974  
# Line 821 | Line 990 | public class JSR166TestCase extends Test
990              for (Thread thread : threads)
991                  assertTrue(thread.isAlive());
992          } catch (InterruptedException fail) {
993 <            fail("Unexpected InterruptedException");
993 >            threadFail("Unexpected InterruptedException");
994          }
995      }
996  
# Line 1099 | Line 1268 | public class JSR166TestCase extends Test
1268          } finally {
1269              if (t.getState() != Thread.State.TERMINATED) {
1270                  t.interrupt();
1271 <                fail("Test timed out");
1271 >                threadFail("timed out waiting for thread to terminate");
1272              }
1273          }
1274      }
# Line 1240 | Line 1409 | public class JSR166TestCase extends Test
1409              }};
1410      }
1411  
1412 <    public Runnable awaiter(final CountDownLatch latch) {
1412 >    public Runnable countDowner(final CountDownLatch latch) {
1413          return new CheckedRunnable() {
1414              public void realRun() throws InterruptedException {
1415 <                await(latch);
1415 >                latch.countDown();
1416              }};
1417      }
1418  
1419 +    class LatchAwaiter extends CheckedRunnable {
1420 +        static final int NEW = 0;
1421 +        static final int RUNNING = 1;
1422 +        static final int DONE = 2;
1423 +        final CountDownLatch latch;
1424 +        int state = NEW;
1425 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1426 +        public void realRun() throws InterruptedException {
1427 +            state = 1;
1428 +            await(latch);
1429 +            state = 2;
1430 +        }
1431 +    }
1432 +
1433 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1434 +        return new LatchAwaiter(latch);
1435 +    }
1436 +
1437      public void await(CountDownLatch latch) {
1438          try {
1439 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1439 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1440 >                fail("timed out waiting for CountDownLatch for "
1441 >                     + (LONG_DELAY_MS/1000) + " sec");
1442          } catch (Throwable fail) {
1443              threadUnexpectedException(fail);
1444          }
# Line 1257 | Line 1446 | public class JSR166TestCase extends Test
1446  
1447      public void await(Semaphore semaphore) {
1448          try {
1449 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1449 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1450 >                fail("timed out waiting for Semaphore for "
1451 >                     + (LONG_DELAY_MS/1000) + " sec");
1452          } catch (Throwable fail) {
1453              threadUnexpectedException(fail);
1454          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines