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.148 by jsr166, Mon Sep 28 08:23:49 2015 UTC vs.
Revision 1.176 by jsr166, Mon Oct 12 07:16:39 2015 UTC

# Line 7 | Line 7
7   */
8  
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 + import static java.util.concurrent.TimeUnit.MINUTES;
11   import static java.util.concurrent.TimeUnit.NANOSECONDS;
12  
13   import java.io.ByteArrayInputStream;
# Line 15 | Line 16 | import java.io.ObjectInputStream;
16   import java.io.ObjectOutputStream;
17   import java.lang.management.ManagementFactory;
18   import java.lang.management.ThreadInfo;
19 + 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 50 | 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 186 | Line 191 | public class JSR166TestCase extends Test
191          return (regex == null) ? null : Pattern.compile(regex);
192      }
193  
194 +    // Instrumentation to debug very rare, but very annoying hung test runs.
195 +    static volatile TestCase currentTestCase;
196 +    // static volatile int currentRun = 0;
197 +    static {
198 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
199 +            // Avoid spurious reports with enormous runsPerTest.
200 +            // A single test case run should never take more than 1 second.
201 +            // But let's cap it at the high end too ...
202 +            final int timeoutMinutes =
203 +                Math.min(15, Math.max(runsPerTest / 60, 1));
204 +            for (TestCase lastTestCase = currentTestCase;;) {
205 +                try { MINUTES.sleep(timeoutMinutes); }
206 +                catch (InterruptedException unexpected) { break; }
207 +                if (lastTestCase == currentTestCase) {
208 +                    System.err.printf(
209 +                        "Looks like we're stuck running test: %s%n",
210 +                        lastTestCase);
211 + //                     System.err.printf(
212 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
213 + //                         lastTestCase, currentRun, runsPerTest);
214 + //                     System.err.println("availableProcessors=" +
215 + //                         Runtime.getRuntime().availableProcessors());
216 + //                     System.err.printf("cpu model = %s%n", cpuModel());
217 +                    dumpTestThreads();
218 +                    // one stack dump is probably enough; more would be spam
219 +                    break;
220 +                }
221 +                lastTestCase = currentTestCase;
222 +            }}};
223 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
224 +        thread.setDaemon(true);
225 +        thread.start();
226 +    }
227 +
228 + //     public static String cpuModel() {
229 + //         try {
230 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
231 + //                 .matcher(new String(
232 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
233 + //             matcher.find();
234 + //             return matcher.group(1);
235 + //         } catch (Exception ex) { return null; }
236 + //     }
237 +
238      public void runBare() throws Throwable {
239 +        currentTestCase = this;
240          if (methodFilter == null
241              || methodFilter.matcher(toString()).find())
242              super.runBare();
# Line 194 | Line 244 | public class JSR166TestCase extends Test
244  
245      protected void runTest() throws Throwable {
246          for (int i = 0; i < runsPerTest; i++) {
247 +            // currentRun = i;
248              if (profileTests)
249                  runTestProfiled();
250              else
# Line 460 | Line 511 | public class JSR166TestCase extends Test
511          } else {
512              return new TestSuite();
513          }
463
514      }
515  
516      // Delays for timing-dependent tests, in milliseconds.
# Line 518 | Line 568 | public class JSR166TestCase extends Test
568       * the same test have no effect.
569       */
570      public void threadRecordFailure(Throwable t) {
571 +        System.err.println(t);
572 +        dumpTestThreads();
573          threadFailure.compareAndSet(null, t);
574      }
575  
# Line 528 | Line 580 | public class JSR166TestCase extends Test
580      void tearDownFail(String format, Object... args) {
581          String msg = toString() + ": " + String.format(format, args);
582          System.err.println(msg);
583 <        printAllStackTraces();
583 >        dumpTestThreads();
584          throw new AssertionFailedError(msg);
585      }
586  
# Line 565 | Line 617 | public class JSR166TestCase extends Test
617      }
618  
619      /**
620 <     * Finds missing try { ... } finally { joinPool(e); }
620 >     * Finds missing PoolCleaners
621       */
622      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
623          Thread[] survivors = new Thread[7];
# Line 597 | Line 649 | public class JSR166TestCase extends Test
649              fail(reason);
650          } catch (AssertionFailedError t) {
651              threadRecordFailure(t);
652 <            fail(reason);
652 >            throw t;
653          }
654      }
655  
# Line 724 | Line 776 | public class JSR166TestCase extends Test
776      /**
777       * Delays, via Thread.sleep, for the given millisecond delay, but
778       * if the sleep is shorter than specified, may re-sleep or yield
779 <     * until time elapses.
779 >     * until time elapses.  Ensures that the given time, as measured
780 >     * by System.nanoTime(), has elapsed.
781       */
782      static void delay(long millis) throws InterruptedException {
783 <        long startTime = System.nanoTime();
784 <        long ns = millis * 1000 * 1000;
785 <        for (;;) {
783 >        long nanos = millis * (1000 * 1000);
784 >        final long wakeupTime = System.nanoTime() + nanos;
785 >        do {
786              if (millis > 0L)
787                  Thread.sleep(millis);
788              else // too short to sleep
789                  Thread.yield();
790 <            long d = ns - (System.nanoTime() - startTime);
791 <            if (d > 0L)
792 <                millis = d / (1000 * 1000);
793 <            else
794 <                break;
790 >            nanos = wakeupTime - System.nanoTime();
791 >            millis = nanos / (1000 * 1000);
792 >        } while (nanos >= 0L);
793 >    }
794 >
795 >    /**
796 >     * Allows use of try-with-resources with per-test thread pools.
797 >     */
798 >    class PoolCleaner implements AutoCloseable {
799 >        private final ExecutorService pool;
800 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
801 >        public void close() { joinPool(pool); }
802 >    }
803 >
804 >    /**
805 >     * An extension of PoolCleaner that has an action to release the pool.
806 >     */
807 >    class PoolCleanerWithReleaser extends PoolCleaner {
808 >        private final Runnable releaser;
809 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
810 >            super(pool);
811 >            this.releaser = releaser;
812 >        }
813 >        public void close() {
814 >            try {
815 >                releaser.run();
816 >            } finally {
817 >                super.close();
818 >            }
819          }
820      }
821  
822 +    PoolCleaner cleaner(ExecutorService pool) {
823 +        return new PoolCleaner(pool);
824 +    }
825 +
826 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
827 +        return new PoolCleanerWithReleaser(pool, releaser);
828 +    }
829 +
830 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
831 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
832 +    }
833 +
834 +    Runnable releaser(final CountDownLatch latch) {
835 +        return new Runnable() { public void run() {
836 +            do { latch.countDown(); }
837 +            while (latch.getCount() > 0);
838 +        }};
839 +    }
840 +
841      /**
842       * Waits out termination of a thread pool or fails doing so.
843       */
844      void joinPool(ExecutorService pool) {
845          try {
846              pool.shutdown();
847 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
848 <                fail("ExecutorService " + pool +
849 <                     " did not terminate in a timely manner");
847 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
848 >                try {
849 >                    threadFail("ExecutorService " + pool +
850 >                               " did not terminate in a timely manner");
851 >                } finally {
852 >                    // last resort, for the benefit of subsequent tests
853 >                    pool.shutdownNow();
854 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
855 >                }
856 >            }
857          } catch (SecurityException ok) {
858              // Allowed in case test doesn't have privs
859          } catch (InterruptedException fail) {
860 <            fail("Unexpected InterruptedException");
860 >            threadFail("Unexpected InterruptedException");
861          }
862      }
863  
# Line 768 | Line 871 | public class JSR166TestCase extends Test
871       */
872      void testInParallel(Action ... actions) {
873          ExecutorService pool = Executors.newCachedThreadPool();
874 <        try {
874 >        try (PoolCleaner cleaner = cleaner(pool)) {
875              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
876              for (final Action action : actions)
877                  futures.add(pool.submit(new CheckedRunnable() {
# Line 781 | Line 884 | public class JSR166TestCase extends Test
884                  } catch (Exception ex) {
885                      threadUnexpectedException(ex);
886                  }
784        } finally {
785            joinPool(pool);
887          }
888      }
889  
890      /**
891 <     * A debugging tool to print all stack traces, as jstack does.
891 >     * A debugging tool to print stack traces of most threads, as jstack does.
892 >     * Uninteresting threads are filtered out.
893       */
894 <    static void printAllStackTraces() {
895 <        for (ThreadInfo info :
896 <                 ManagementFactory.getThreadMXBean()
897 <                 .dumpAllThreads(true, true))
894 >    static void dumpTestThreads() {
895 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
896 >        System.err.println("------ stacktrace dump start ------");
897 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
898 >            String name = info.getThreadName();
899 >            if ("Signal Dispatcher".equals(name))
900 >                continue;
901 >            if ("Reference Handler".equals(name)
902 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
903 >                continue;
904 >            if ("Finalizer".equals(name)
905 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
906 >                continue;
907 >            if ("checkForWedgedTest".equals(name))
908 >                continue;
909              System.err.print(info);
910 +        }
911 +        System.err.println("------ stacktrace dump end ------");
912      }
913  
914      /**
# Line 813 | Line 928 | public class JSR166TestCase extends Test
928              delay(millis);
929              assertTrue(thread.isAlive());
930          } catch (InterruptedException fail) {
931 <            fail("Unexpected InterruptedException");
931 >            threadFail("Unexpected InterruptedException");
932          }
933      }
934  
# Line 835 | Line 950 | public class JSR166TestCase extends Test
950              for (Thread thread : threads)
951                  assertTrue(thread.isAlive());
952          } catch (InterruptedException fail) {
953 <            fail("Unexpected InterruptedException");
953 >            threadFail("Unexpected InterruptedException");
954          }
955      }
956  
# Line 1113 | Line 1228 | public class JSR166TestCase extends Test
1228          } finally {
1229              if (t.getState() != Thread.State.TERMINATED) {
1230                  t.interrupt();
1231 <                fail("Test timed out");
1231 >                threadFail("Test timed out");
1232              }
1233          }
1234      }
# Line 1261 | Line 1376 | public class JSR166TestCase extends Test
1376              }};
1377      }
1378  
1379 <    public Runnable awaiter(final CountDownLatch latch) {
1380 <        return new CheckedRunnable() {
1381 <            public void realRun() throws InterruptedException {
1382 <                await(latch);
1383 <            }};
1379 >    class LatchAwaiter extends CheckedRunnable {
1380 >        static final int NEW = 0;
1381 >        static final int RUNNING = 1;
1382 >        static final int DONE = 2;
1383 >        final CountDownLatch latch;
1384 >        int state = NEW;
1385 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1386 >        public void realRun() throws InterruptedException {
1387 >            state = 1;
1388 >            await(latch);
1389 >            state = 2;
1390 >        }
1391 >    }
1392 >
1393 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1394 >        return new LatchAwaiter(latch);
1395      }
1396  
1397      public void await(CountDownLatch latch) {
1398          try {
1399 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1399 >            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1400 >                fail("timed out waiting for CountDownLatch for "
1401 >                     + (LONG_DELAY_MS/1000) + " sec");
1402          } catch (Throwable fail) {
1403              threadUnexpectedException(fail);
1404          }
# Line 1278 | Line 1406 | public class JSR166TestCase extends Test
1406  
1407      public void await(Semaphore semaphore) {
1408          try {
1409 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1409 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1410 >                fail("timed out waiting for Semaphore for "
1411 >                     + (LONG_DELAY_MS/1000) + " sec");
1412          } catch (Throwable fail) {
1413              threadUnexpectedException(fail);
1414          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines