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.156 by jsr166, Sat Oct 3 21:09:42 2015 UTC vs.
Revision 1.173 by jsr166, Fri Oct 9 16:24:12 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 188 | 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 +            final int timeoutMinutes = Math.max(runsPerTest / 10, 1);
201              for (TestCase lastTestCase = currentTestCase;;) {
202 <                try { MINUTES.sleep(10); }
202 >                try { MINUTES.sleep(timeoutMinutes); }
203                  catch (InterruptedException unexpected) { break; }
204                  if (lastTestCase == currentTestCase) {
205 <                    System.err.println
206 <                        ("Looks like we're stuck running test: "
207 <                         + lastTestCase);
205 >                    System.err.printf(
206 >                        "Looks like we're stuck running test: %s%n",
207 >                        lastTestCase);
208 > //                     System.err.printf(
209 > //                         "Looks like we're stuck running test: %s (%d/%d)%n",
210 > //                         lastTestCase, currentRun, runsPerTest);
211 >                    System.err.println("availableProcessors=" +
212 >                        Runtime.getRuntime().availableProcessors());
213 >                    System.err.printf("cpu model = %s%n", cpuModel());
214                      dumpTestThreads();
215 +                    // one stack dump is probably enough; more would be spam
216 +                    break;
217                  }
218                  lastTestCase = currentTestCase;
219              }}};
# Line 207 | Line 222 | public class JSR166TestCase extends Test
222          thread.start();
223      }
224  
225 +    public static String cpuModel() {
226 +        try {
227 +            Matcher matcher = Pattern.compile("model name\\s*: (.*)")
228 +                .matcher(new String(
229 +                     Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
230 +            matcher.find();
231 +            return matcher.group(1);
232 +        } catch (Exception ex) { return null; }
233 +    }
234 +
235      public void runBare() throws Throwable {
236          currentTestCase = this;
237          if (methodFilter == null
# Line 216 | Line 241 | public class JSR166TestCase extends Test
241  
242      protected void runTest() throws Throwable {
243          for (int i = 0; i < runsPerTest; i++) {
244 +            // currentRun = i;
245              if (profileTests)
246                  runTestProfiled();
247              else
# Line 539 | Line 565 | public class JSR166TestCase extends Test
565       * the same test have no effect.
566       */
567      public void threadRecordFailure(Throwable t) {
568 +        System.err.println(t);
569          dumpTestThreads();
570          threadFailure.compareAndSet(null, t);
571      }
# Line 587 | Line 614 | public class JSR166TestCase extends Test
614      }
615  
616      /**
617 <     * Finds missing try { ... } finally { joinPool(e); }
617 >     * Finds missing PoolCleaners
618       */
619      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
620          Thread[] survivors = new Thread[7];
# Line 746 | Line 773 | public class JSR166TestCase extends Test
773      /**
774       * Delays, via Thread.sleep, for the given millisecond delay, but
775       * if the sleep is shorter than specified, may re-sleep or yield
776 <     * until time elapses.
776 >     * until time elapses.  Ensures that the given time, as measured
777 >     * by System.nanoTime(), has elapsed.
778       */
779      static void delay(long millis) throws InterruptedException {
780 <        long startTime = System.nanoTime();
781 <        long ns = millis * 1000 * 1000;
782 <        for (;;) {
780 >        long nanos = millis * (1000 * 1000);
781 >        final long wakeupTime = System.nanoTime() + nanos;
782 >        do {
783              if (millis > 0L)
784                  Thread.sleep(millis);
785              else // too short to sleep
786                  Thread.yield();
787 <            long d = ns - (System.nanoTime() - startTime);
788 <            if (d > 0L)
789 <                millis = d / (1000 * 1000);
762 <            else
763 <                break;
764 <        }
787 >            nanos = wakeupTime - System.nanoTime();
788 >            millis = nanos / (1000 * 1000);
789 >        } while (nanos >= 0L);
790      }
791  
792      /**
793       * Allows use of try-with-resources with per-test thread pools.
794       */
795 <    static class PoolCloser<T extends ExecutorService>
796 <            implements AutoCloseable {
797 <        public final T pool;
773 <        public PoolCloser(T pool) { this.pool = pool; }
795 >    class PoolCleaner implements AutoCloseable {
796 >        private final ExecutorService pool;
797 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
798          public void close() { joinPool(pool); }
799      }
800  
801      /**
802 +     * An extension of PoolCleaner that has an action to release the pool.
803 +     */
804 +    class PoolCleanerWithReleaser extends PoolCleaner {
805 +        private final Runnable releaser;
806 +        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
807 +            super(pool);
808 +            this.releaser = releaser;
809 +        }
810 +        public void close() {
811 +            try {
812 +                releaser.run();
813 +            } finally {
814 +                super.close();
815 +            }
816 +        }
817 +    }
818 +
819 +    PoolCleaner cleaner(ExecutorService pool) {
820 +        return new PoolCleaner(pool);
821 +    }
822 +
823 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
824 +        return new PoolCleanerWithReleaser(pool, releaser);
825 +    }
826 +
827 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
828 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
829 +    }
830 +
831 +    Runnable releaser(final CountDownLatch latch) {
832 +        return new Runnable() { public void run() {
833 +            do { latch.countDown(); }
834 +            while (latch.getCount() > 0);
835 +        }};
836 +    }
837 +
838 +    /**
839       * Waits out termination of a thread pool or fails doing so.
840       */
841 <    static void joinPool(ExecutorService pool) {
841 >    void joinPool(ExecutorService pool) {
842          try {
843              pool.shutdown();
844 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
845 <                fail("ExecutorService " + pool +
846 <                     " did not terminate in a timely manner");
844 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
845 >                try {
846 >                    threadFail("ExecutorService " + pool +
847 >                               " did not terminate in a timely manner");
848 >                } finally {
849 >                    // last resort, for the benefit of subsequent tests
850 >                    pool.shutdownNow();
851 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
852 >                }
853 >            }
854          } catch (SecurityException ok) {
855              // Allowed in case test doesn't have privs
856          } catch (InterruptedException fail) {
857 <            fail("Unexpected InterruptedException");
857 >            threadFail("Unexpected InterruptedException");
858          }
859      }
860  
# Line 799 | Line 867 | public class JSR166TestCase extends Test
867       * necessarily individually slow because they must block.
868       */
869      void testInParallel(Action ... actions) {
870 <        try (PoolCloser<ExecutorService> poolCloser
871 <             = new PoolCloser<>(Executors.newCachedThreadPool())) {
804 <            ExecutorService pool = poolCloser.pool;
870 >        ExecutorService pool = Executors.newCachedThreadPool();
871 >        try (PoolCleaner cleaner = cleaner(pool)) {
872              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
873              for (final Action action : actions)
874                  futures.add(pool.submit(new CheckedRunnable() {
# Line 858 | Line 925 | public class JSR166TestCase extends Test
925              delay(millis);
926              assertTrue(thread.isAlive());
927          } catch (InterruptedException fail) {
928 <            fail("Unexpected InterruptedException");
928 >            threadFail("Unexpected InterruptedException");
929          }
930      }
931  
# Line 880 | Line 947 | public class JSR166TestCase extends Test
947              for (Thread thread : threads)
948                  assertTrue(thread.isAlive());
949          } catch (InterruptedException fail) {
950 <            fail("Unexpected InterruptedException");
950 >            threadFail("Unexpected InterruptedException");
951          }
952      }
953  
# Line 1158 | Line 1225 | public class JSR166TestCase extends Test
1225          } finally {
1226              if (t.getState() != Thread.State.TERMINATED) {
1227                  t.interrupt();
1228 <                fail("Test timed out");
1228 >                threadFail("Test timed out");
1229              }
1230          }
1231      }
# Line 1306 | Line 1373 | public class JSR166TestCase extends Test
1373              }};
1374      }
1375  
1376 <    public Runnable awaiter(final CountDownLatch latch) {
1377 <        return new CheckedRunnable() {
1378 <            public void realRun() throws InterruptedException {
1379 <                await(latch);
1380 <            }};
1376 >    class LatchAwaiter extends CheckedRunnable {
1377 >        static final int NEW = 0;
1378 >        static final int RUNNING = 1;
1379 >        static final int DONE = 2;
1380 >        final CountDownLatch latch;
1381 >        int state = NEW;
1382 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1383 >        public void realRun() throws InterruptedException {
1384 >            state = 1;
1385 >            await(latch);
1386 >            state = 2;
1387 >        }
1388 >    }
1389 >
1390 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1391 >        return new LatchAwaiter(latch);
1392      }
1393  
1394      public void await(CountDownLatch latch) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines