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.157 by jsr166, Sat Oct 3 22:20:05 2015 UTC vs.
Revision 1.172 by jsr166, Fri Oct 9 01:26:36 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
# Line 197 | Line 202 | public class JSR166TestCase extends Test
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 (%d/%d)%n",
207 >                        lastTestCase, currentRun, runsPerTest);
208 >                    System.err.println("availableProcessors=" +
209 >                        Runtime.getRuntime().availableProcessors());
210 >                    System.err.printf("cpu model = %s%n", cpuModel());
211                      dumpTestThreads();
212 +                    // one stack dump is probably enough; more would be spam
213 +                    break;
214                  }
215                  lastTestCase = currentTestCase;
216              }}};
# Line 209 | Line 219 | public class JSR166TestCase extends Test
219          thread.start();
220      }
221  
222 +    public static String cpuModel() {
223 +        try {
224 +            Matcher matcher = Pattern.compile("model name\\s*: (.*)")
225 +                .matcher(new String(
226 +                     Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
227 +            matcher.find();
228 +            return matcher.group(1);
229 +        } catch (Exception ex) { return null; }
230 +    }
231 +
232      public void runBare() throws Throwable {
233          currentTestCase = this;
234          if (methodFilter == null
# Line 218 | Line 238 | public class JSR166TestCase extends Test
238  
239      protected void runTest() throws Throwable {
240          for (int i = 0; i < runsPerTest; i++) {
241 +            currentRun = i;
242              if (profileTests)
243                  runTestProfiled();
244              else
# Line 541 | Line 562 | public class JSR166TestCase extends Test
562       * the same test have no effect.
563       */
564      public void threadRecordFailure(Throwable t) {
565 +        System.err.println(t);
566          dumpTestThreads();
567          threadFailure.compareAndSet(null, t);
568      }
# Line 589 | Line 611 | public class JSR166TestCase extends Test
611      }
612  
613      /**
614 <     * Finds missing try { ... } finally { joinPool(e); }
614 >     * Finds missing PoolCleaners
615       */
616      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
617          Thread[] survivors = new Thread[7];
# Line 748 | Line 770 | public class JSR166TestCase extends Test
770      /**
771       * Delays, via Thread.sleep, for the given millisecond delay, but
772       * if the sleep is shorter than specified, may re-sleep or yield
773 <     * until time elapses.
773 >     * until time elapses.  Ensures that the given time, as measured
774 >     * by System.nanoTime(), has elapsed.
775       */
776      static void delay(long millis) throws InterruptedException {
777 <        long startTime = System.nanoTime();
778 <        long ns = millis * 1000 * 1000;
779 <        for (;;) {
777 >        long nanos = millis * (1000 * 1000);
778 >        final long wakeupTime = System.nanoTime() + nanos;
779 >        do {
780              if (millis > 0L)
781                  Thread.sleep(millis);
782              else // too short to sleep
783                  Thread.yield();
784 <            long d = ns - (System.nanoTime() - startTime);
785 <            if (d > 0L)
786 <                millis = d / (1000 * 1000);
764 <            else
765 <                break;
766 <        }
784 >            nanos = wakeupTime - System.nanoTime();
785 >            millis = nanos / (1000 * 1000);
786 >        } while (nanos >= 0L);
787      }
788  
789      /**
790       * Allows use of try-with-resources with per-test thread pools.
791       */
792 <    static class PoolCloser<T extends ExecutorService>
793 <            implements AutoCloseable {
794 <        public final T pool;
775 <        public PoolCloser(T pool) { this.pool = pool; }
792 >    class PoolCleaner implements AutoCloseable {
793 >        private final ExecutorService pool;
794 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
795          public void close() { joinPool(pool); }
796      }
797  
798      /**
799 +     * An extension of PoolCleaner that has an action to release the pool.
800 +     */
801 +    class PoolCleanerWithReleaser extends PoolCleaner {
802 +        private final Runnable releaser;
803 +        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
804 +            super(pool);
805 +            this.releaser = releaser;
806 +        }
807 +        public void close() {
808 +            try {
809 +                releaser.run();
810 +            } finally {
811 +                super.close();
812 +            }
813 +        }
814 +    }
815 +
816 +    PoolCleaner cleaner(ExecutorService pool) {
817 +        return new PoolCleaner(pool);
818 +    }
819 +
820 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
821 +        return new PoolCleanerWithReleaser(pool, releaser);
822 +    }
823 +
824 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
825 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
826 +    }
827 +
828 +    Runnable releaser(final CountDownLatch latch) {
829 +        return new Runnable() { public void run() {
830 +            do { latch.countDown(); }
831 +            while (latch.getCount() > 0);
832 +        }};
833 +    }
834 +
835 +    /**
836       * Waits out termination of a thread pool or fails doing so.
837       */
838 <    static void joinPool(ExecutorService pool) {
838 >    void joinPool(ExecutorService pool) {
839          try {
840              pool.shutdown();
841 <            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
842 <                fail("ExecutorService " + pool +
843 <                     " did not terminate in a timely manner");
841 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
842 >                try {
843 >                    threadFail("ExecutorService " + pool +
844 >                               " did not terminate in a timely manner");
845 >                } finally {
846 >                    // last resort, for the benefit of subsequent tests
847 >                    pool.shutdownNow();
848 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
849 >                }
850 >            }
851          } catch (SecurityException ok) {
852              // Allowed in case test doesn't have privs
853          } catch (InterruptedException fail) {
854 <            fail("Unexpected InterruptedException");
854 >            threadFail("Unexpected InterruptedException");
855          }
856      }
857  
# Line 801 | Line 864 | public class JSR166TestCase extends Test
864       * necessarily individually slow because they must block.
865       */
866      void testInParallel(Action ... actions) {
867 <        try (PoolCloser<ExecutorService> poolCloser
868 <             = new PoolCloser<>(Executors.newCachedThreadPool())) {
806 <            ExecutorService pool = poolCloser.pool;
867 >        ExecutorService pool = Executors.newCachedThreadPool();
868 >        try (PoolCleaner cleaner = cleaner(pool)) {
869              ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
870              for (final Action action : actions)
871                  futures.add(pool.submit(new CheckedRunnable() {
# Line 860 | Line 922 | public class JSR166TestCase extends Test
922              delay(millis);
923              assertTrue(thread.isAlive());
924          } catch (InterruptedException fail) {
925 <            fail("Unexpected InterruptedException");
925 >            threadFail("Unexpected InterruptedException");
926          }
927      }
928  
# Line 882 | Line 944 | public class JSR166TestCase extends Test
944              for (Thread thread : threads)
945                  assertTrue(thread.isAlive());
946          } catch (InterruptedException fail) {
947 <            fail("Unexpected InterruptedException");
947 >            threadFail("Unexpected InterruptedException");
948          }
949      }
950  
# Line 1160 | Line 1222 | public class JSR166TestCase extends Test
1222          } finally {
1223              if (t.getState() != Thread.State.TERMINATED) {
1224                  t.interrupt();
1225 <                fail("Test timed out");
1225 >                threadFail("Test timed out");
1226              }
1227          }
1228      }
# Line 1308 | Line 1370 | public class JSR166TestCase extends Test
1370              }};
1371      }
1372  
1373 <    public Runnable awaiter(final CountDownLatch latch) {
1374 <        return new CheckedRunnable() {
1375 <            public void realRun() throws InterruptedException {
1376 <                await(latch);
1377 <            }};
1373 >    class LatchAwaiter extends CheckedRunnable {
1374 >        static final int NEW = 0;
1375 >        static final int RUNNING = 1;
1376 >        static final int DONE = 2;
1377 >        final CountDownLatch latch;
1378 >        int state = NEW;
1379 >        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1380 >        public void realRun() throws InterruptedException {
1381 >            state = 1;
1382 >            await(latch);
1383 >            state = 2;
1384 >        }
1385 >    }
1386 >
1387 >    public LatchAwaiter awaiter(CountDownLatch latch) {
1388 >        return new LatchAwaiter(latch);
1389      }
1390  
1391      public void await(CountDownLatch latch) {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines