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.174 by jsr166, Fri Oct 9 19:09:59 2015 UTC vs.
Revision 1.197 by jsr166, Wed Jun 22 14:40:36 2016 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 + /*
10 + * @test
11 + * @summary JSR-166 tck tests
12 + * @modules java.management
13 + * @build *
14 + * @run junit/othervm/timeout=1000 -Djsr166.testImplementationDetails=true JSR166TestCase
15 + * @run junit/othervm/timeout=1000 -Djava.util.concurrent.ForkJoinPool.common.parallelism=0 -Djsr166.testImplementationDetails=true JSR166TestCase
16 + */
17 +
18   import static java.util.concurrent.TimeUnit.MILLISECONDS;
19   import static java.util.concurrent.TimeUnit.MINUTES;
20   import static java.util.concurrent.TimeUnit.NANOSECONDS;
# Line 50 | Line 59 | import java.util.concurrent.RecursiveAct
59   import java.util.concurrent.RecursiveTask;
60   import java.util.concurrent.RejectedExecutionHandler;
61   import java.util.concurrent.Semaphore;
62 + import java.util.concurrent.SynchronousQueue;
63   import java.util.concurrent.ThreadFactory;
64   import java.util.concurrent.ThreadPoolExecutor;
65   import java.util.concurrent.TimeoutException;
66 + import java.util.concurrent.atomic.AtomicBoolean;
67   import java.util.concurrent.atomic.AtomicReference;
68   import java.util.regex.Matcher;
69   import java.util.regex.Pattern;
# Line 112 | Line 123 | import junit.framework.TestSuite;
123   * methods as there are exceptions the method can throw. Sometimes
124   * there are multiple tests per JSR166 method when the different
125   * "normal" behaviors differ significantly. And sometimes testcases
126 < * cover multiple methods when they cannot be tested in
116 < * isolation.
126 > * cover multiple methods when they cannot be tested in isolation.
127   *
128   * <li>The documentation style for testcases is to provide as javadoc
129   * a simple sentence or two describing the property that the testcase
# Line 176 | Line 186 | public class JSR166TestCase extends Test
186      private static final int suiteRuns =
187          Integer.getInteger("jsr166.suiteRuns", 1);
188  
189 +    /**
190 +     * Returns the value of the system property, or NaN if not defined.
191 +     */
192 +    private static float systemPropertyValue(String name) {
193 +        String floatString = System.getProperty(name);
194 +        if (floatString == null)
195 +            return Float.NaN;
196 +        try {
197 +            return Float.parseFloat(floatString);
198 +        } catch (NumberFormatException ex) {
199 +            throw new IllegalArgumentException(
200 +                String.format("Bad float value in system property %s=%s",
201 +                              name, floatString));
202 +        }
203 +    }
204 +
205 +    /**
206 +     * The scaling factor to apply to standard delays used in tests.
207 +     * May be initialized from any of:
208 +     * - the "jsr166.delay.factor" system property
209 +     * - the "test.timeout.factor" system property (as used by jtreg)
210 +     *   See: http://openjdk.java.net/jtreg/tag-spec.html
211 +     * - hard-coded fuzz factor when using a known slowpoke VM
212 +     */
213 +    private static final float delayFactor = delayFactor();
214 +
215 +    private static float delayFactor() {
216 +        float x;
217 +        if (!Float.isNaN(x = systemPropertyValue("jsr166.delay.factor")))
218 +            return x;
219 +        if (!Float.isNaN(x = systemPropertyValue("test.timeout.factor")))
220 +            return x;
221 +        String prop = System.getProperty("java.vm.version");
222 +        if (prop != null && prop.matches(".*debug.*"))
223 +            return 4.0f; // How much slower is fastdebug than product?!
224 +        return 1.0f;
225 +    }
226 +
227      public JSR166TestCase() { super(); }
228      public JSR166TestCase(String name) { super(name); }
229  
# Line 211 | Line 259 | public class JSR166TestCase extends Test
259   //                     System.err.printf(
260   //                         "Looks like we're stuck running test: %s (%d/%d)%n",
261   //                         lastTestCase, currentRun, runsPerTest);
262 <                    System.err.println("availableProcessors=" +
263 <                        Runtime.getRuntime().availableProcessors());
264 <                    System.err.printf("cpu model = %s%n", cpuModel());
262 > //                     System.err.println("availableProcessors=" +
263 > //                         Runtime.getRuntime().availableProcessors());
264 > //                     System.err.printf("cpu model = %s%n", cpuModel());
265                      dumpTestThreads();
266                      // one stack dump is probably enough; more would be spam
267                      break;
# Line 225 | Line 273 | public class JSR166TestCase extends Test
273          thread.start();
274      }
275  
276 <    public static String cpuModel() {
277 <        try {
278 <            Matcher matcher = Pattern.compile("model name\\s*: (.*)")
279 <                .matcher(new String(
280 <                     Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
281 <            matcher.find();
282 <            return matcher.group(1);
283 <        } catch (Exception ex) { return null; }
284 <    }
276 > //     public static String cpuModel() {
277 > //         try {
278 > //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
279 > //                 .matcher(new String(
280 > //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
281 > //             matcher.find();
282 > //             return matcher.group(1);
283 > //         } catch (Exception ex) { return null; }
284 > //     }
285  
286      public void runBare() throws Throwable {
287          currentTestCase = this;
# Line 273 | Line 321 | public class JSR166TestCase extends Test
321          main(suite(), args);
322      }
323  
324 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
325 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
326 +        long runTime;
327 +        public void startTest(Test test) {}
328 +        protected void printHeader(long runTime) {
329 +            this.runTime = runTime; // defer printing for later
330 +        }
331 +        protected void printFooter(TestResult result) {
332 +            if (result.wasSuccessful()) {
333 +                getWriter().println("OK (" + result.runCount() + " tests)"
334 +                    + "  Time: " + elapsedTimeAsString(runTime));
335 +            } else {
336 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
337 +                super.printFooter(result);
338 +            }
339 +        }
340 +    }
341 +
342 +    /**
343 +     * Returns a TestRunner that doesn't bother with unnecessary
344 +     * fluff, like printing a "." for each test case.
345 +     */
346 +    static junit.textui.TestRunner newPithyTestRunner() {
347 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
348 +        runner.setPrinter(new PithyResultPrinter(System.out));
349 +        return runner;
350 +    }
351 +
352      /**
353       * Runs all unit tests in the given test suite.
354       * Actual behavior influenced by jsr166.* system properties.
# Line 284 | Line 360 | public class JSR166TestCase extends Test
360              System.setSecurityManager(new SecurityManager());
361          }
362          for (int i = 0; i < suiteRuns; i++) {
363 <            TestResult result = junit.textui.TestRunner.run(suite);
363 >            TestResult result = newPithyTestRunner().doRun(suite);
364              if (!result.wasSuccessful())
365                  System.exit(1);
366              System.gc();
# Line 437 | Line 513 | public class JSR166TestCase extends Test
513                  "StampedLockTest",
514                  "SubmissionPublisherTest",
515                  "ThreadLocalRandom8Test",
516 +                "TimeUnit8Test",
517              };
518              addNamedTestClasses(suite, java8TestClassNames);
519          }
# Line 444 | Line 521 | public class JSR166TestCase extends Test
521          // Java9+ test classes
522          if (atLeastJava9()) {
523              String[] java9TestClassNames = {
524 <                // Currently empty, but expecting varhandle tests
524 >                "AtomicBoolean9Test",
525 >                "AtomicInteger9Test",
526 >                "AtomicIntegerArray9Test",
527 >                "AtomicLong9Test",
528 >                "AtomicLongArray9Test",
529 >                "AtomicReference9Test",
530 >                "AtomicReferenceArray9Test",
531 >                "ExecutorCompletionService9Test",
532              };
533              addNamedTestClasses(suite, java9TestClassNames);
534          }
# Line 521 | Line 605 | public class JSR166TestCase extends Test
605      public static long LONG_DELAY_MS;
606  
607      /**
608 <     * Returns the shortest timed delay. This could
609 <     * be reimplemented to use for example a Property.
608 >     * Returns the shortest timed delay. This can be scaled up for
609 >     * slow machines using the jsr166.delay.factor system property,
610 >     * or via jtreg's -timeoutFactor: flag.
611 >     * http://openjdk.java.net/jtreg/command-help.html
612       */
613      protected long getShortDelay() {
614 <        return 50;
614 >        return (long) (50 * delayFactor);
615      }
616  
617      /**
# Line 838 | Line 924 | public class JSR166TestCase extends Test
924          }};
925      }
926  
927 +    PoolCleaner cleaner(ExecutorService pool, AtomicBoolean flag) {
928 +        return new PoolCleanerWithReleaser(pool, releaser(flag));
929 +    }
930 +
931 +    Runnable releaser(final AtomicBoolean flag) {
932 +        return new Runnable() { public void run() { flag.set(true); }};
933 +    }
934 +
935      /**
936       * Waits out termination of a thread pool or fails doing so.
937       */
# Line 861 | Line 955 | public class JSR166TestCase extends Test
955          }
956      }
957  
958 <    /** Like Runnable, but with the freedom to throw anything */
958 >    /**
959 >     * Like Runnable, but with the freedom to throw anything.
960 >     * junit folks had the same idea:
961 >     * http://junit.org/junit5/docs/snapshot/api/org/junit/gen5/api/Executable.html
962 >     */
963      interface Action { public void run() throws Throwable; }
964  
965      /**
# Line 892 | Line 990 | public class JSR166TestCase extends Test
990       * Uninteresting threads are filtered out.
991       */
992      static void dumpTestThreads() {
993 +        SecurityManager sm = System.getSecurityManager();
994 +        if (sm != null) {
995 +            try {
996 +                System.setSecurityManager(null);
997 +            } catch (SecurityException giveUp) {
998 +                return;
999 +            }
1000 +        }
1001 +
1002          ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
1003          System.err.println("------ stacktrace dump start ------");
1004          for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
# Line 909 | Line 1016 | public class JSR166TestCase extends Test
1016              System.err.print(info);
1017          }
1018          System.err.println("------ stacktrace dump end ------");
1019 +
1020 +        if (sm != null) System.setSecurityManager(sm);
1021      }
1022  
1023      /**
# Line 1228 | Line 1337 | public class JSR166TestCase extends Test
1337          } finally {
1338              if (t.getState() != Thread.State.TERMINATED) {
1339                  t.interrupt();
1340 <                threadFail("Test timed out");
1340 >                threadFail("timed out waiting for thread to terminate");
1341              }
1342          }
1343      }
# Line 1394 | Line 1503 | public class JSR166TestCase extends Test
1503          return new LatchAwaiter(latch);
1504      }
1505  
1506 <    public void await(CountDownLatch latch) {
1506 >    public void await(CountDownLatch latch, long timeoutMillis) {
1507          try {
1508 <            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1508 >            if (!latch.await(timeoutMillis, MILLISECONDS))
1509 >                fail("timed out waiting for CountDownLatch for "
1510 >                     + (timeoutMillis/1000) + " sec");
1511          } catch (Throwable fail) {
1512              threadUnexpectedException(fail);
1513          }
1514      }
1515  
1516 +    public void await(CountDownLatch latch) {
1517 +        await(latch, LONG_DELAY_MS);
1518 +    }
1519 +
1520      public void await(Semaphore semaphore) {
1521          try {
1522 <            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1522 >            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1523 >                fail("timed out waiting for Semaphore for "
1524 >                     + (LONG_DELAY_MS/1000) + " sec");
1525          } catch (Throwable fail) {
1526              threadUnexpectedException(fail);
1527          }
# Line 1740 | Line 1857 | public class JSR166TestCase extends Test
1857          } catch (NoSuchElementException success) {}
1858          assertFalse(it.hasNext());
1859      }
1860 +
1861 +    public <T> Callable<T> callableThrowing(final Exception ex) {
1862 +        return new Callable<T>() { public T call() throws Exception { throw ex; }};
1863 +    }
1864 +
1865 +    public Runnable runnableThrowing(final RuntimeException ex) {
1866 +        return new Runnable() { public void run() { throw ex; }};
1867 +    }
1868 +
1869 +    /** A reusable thread pool to be shared by tests. */
1870 +    static final ExecutorService cachedThreadPool =
1871 +        new ThreadPoolExecutor(0, Integer.MAX_VALUE,
1872 +                               1000L, MILLISECONDS,
1873 +                               new SynchronousQueue<Runnable>());
1874 +
1875   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines