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.97 by jsr166, Fri Feb 1 19:07:36 2013 UTC vs.
Revision 1.121 by jsr166, Wed Jul 9 16:51:40 2014 UTC

# Line 26 | Line 26 | import java.util.concurrent.atomic.Atomi
26   import java.util.concurrent.atomic.AtomicReference;
27   import static java.util.concurrent.TimeUnit.MILLISECONDS;
28   import static java.util.concurrent.TimeUnit.NANOSECONDS;
29 + import java.util.regex.Pattern;
30   import java.security.CodeSource;
31   import java.security.Permission;
32   import java.security.PermissionCollection;
# Line 115 | Line 116 | public class JSR166TestCase extends Test
116          Boolean.getBoolean("jsr166.expensiveTests");
117  
118      /**
119 +     * If true, also run tests that are not part of the official tck
120 +     * because they test unspecified implementation details.
121 +     */
122 +    protected static final boolean testImplementationDetails =
123 +        Boolean.getBoolean("jsr166.testImplementationDetails");
124 +
125 +    /**
126       * If true, report on stdout all "slow" tests, that is, ones that
127       * take more than profileThreshold milliseconds to execute.
128       */
# Line 128 | Line 136 | public class JSR166TestCase extends Test
136      private static final long profileThreshold =
137          Long.getLong("jsr166.profileThreshold", 100);
138  
139 +    /**
140 +     * The number of repetitions per test (for tickling rare bugs).
141 +     */
142 +    private static final int runsPerTest =
143 +        Integer.getInteger("jsr166.runsPerTest", 1);
144 +
145 +    /**
146 +     * A filter for tests to run, matching strings of the form
147 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
148 +     * Usefully combined with jsr166.runsPerTest.
149 +     */
150 +    private static final Pattern methodFilter = methodFilter();
151 +
152 +    private static Pattern methodFilter() {
153 +        String regex = System.getProperty("jsr166.methodFilter");
154 +        return (regex == null) ? null : Pattern.compile(regex);
155 +    }
156 +
157      protected void runTest() throws Throwable {
158 <        if (profileTests)
159 <            runTestProfiled();
160 <        else
161 <            super.runTest();
158 >        if (methodFilter == null
159 >            || methodFilter.matcher(toString()).find()) {
160 >            for (int i = 0; i < runsPerTest; i++) {
161 >                if (profileTests)
162 >                    runTestProfiled();
163 >                else
164 >                    super.runTest();
165 >            }
166 >        }
167      }
168  
169      protected void runTestProfiled() throws Throwable {
170 +        // Warmup run, notably to trigger all needed classloading.
171 +        super.runTest();
172          long t0 = System.nanoTime();
173          try {
174              super.runTest();
175          } finally {
176 <            long elapsedMillis =
144 <                (System.nanoTime() - t0) / (1000L * 1000L);
176 >            long elapsedMillis = millisElapsedSince(t0);
177              if (elapsedMillis >= profileThreshold)
178                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
179          }
# Line 182 | Line 214 | public class JSR166TestCase extends Test
214          return suite;
215      }
216  
217 <    static void addTestReflectively(TestSuite suite, String testClassName) {
218 <        try {
219 <            Class klazz = Class.forName(testClassName);
220 <            Method m = klazz.getDeclaredMethod("suite", new Class<?>[0]);
221 <            suite.addTest(newTestSuite((Test)m.invoke(null)));
222 <        } catch (Exception e) {
223 <            throw new Error(e);
217 >    public static void addNamedTestClasses(TestSuite suite,
218 >                                           String... testClassNames) {
219 >        for (String testClassName : testClassNames) {
220 >            try {
221 >                Class<?> testClass = Class.forName(testClassName);
222 >                Method m = testClass.getDeclaredMethod("suite",
223 >                                                       new Class<?>[0]);
224 >                suite.addTest(newTestSuite((Test)m.invoke(null)));
225 >            } catch (Exception e) {
226 >                throw new Error("Missing test class", e);
227 >            }
228          }
229      }
230  
231      public static final double JAVA_CLASS_VERSION;
232 +    public static final String JAVA_SPECIFICATION_VERSION;
233      static {
234          try {
235              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
236                  new java.security.PrivilegedAction<Double>() {
237                  public Double run() {
238                      return Double.valueOf(System.getProperty("java.class.version"));}});
239 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
240 +                new java.security.PrivilegedAction<String>() {
241 +                public String run() {
242 +                    return System.getProperty("java.specification.version");}});
243          } catch (Throwable t) {
244              throw new Error(t);
245          }
246      }
247  
248 <    public static boolean isAtLeastJdk6() { return JAVA_CLASS_VERSION >= 50.0; }
249 <    public static boolean isAtLeastJdk7() { return JAVA_CLASS_VERSION >= 51.0; }
250 <    public static boolean isAtLeastJdk8() { return JAVA_CLASS_VERSION >= 52.0; }
248 >    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
249 >    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
250 >    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
251 >    public static boolean atLeastJava9() {
252 >        // As of 2014-05, java9 still uses 52.0 class file version
253 >        return JAVA_SPECIFICATION_VERSION.startsWith("1.9");
254 >    }
255  
256      /**
257       * Collects all JSR166 unit tests as one suite.
258       */
259      public static Test suite() {
260 +        // Java7+ test classes
261          TestSuite suite = newTestSuite(
262              ForkJoinPoolTest.suite(),
263              ForkJoinTaskTest.suite(),
# Line 277 | Line 323 | public class JSR166TestCase extends Test
323              TreeSetTest.suite(),
324              TreeSubMapTest.suite(),
325              TreeSubSetTest.suite());
326 <        if (isAtLeastJdk8()) {
327 <            addTestReflectively(suite, "StampedLockTest");
326 >
327 >        // Java8+ test classes
328 >        if (atLeastJava8()) {
329 >            String[] java8TestClassNames = {
330 >                "Atomic8Test",
331 >                "CompletableFutureTest",
332 >                "ConcurrentHashMap8Test",
333 >                "CountedCompleterTest",
334 >                "DoubleAccumulatorTest",
335 >                "DoubleAdderTest",
336 >                "ForkJoinPool8Test",
337 >                "ForkJoinTask8Test",
338 >                "LongAccumulatorTest",
339 >                "LongAdderTest",
340 >                "SplittableRandomTest",
341 >                "StampedLockTest",
342 >                "ThreadLocalRandom8Test",
343 >            };
344 >            addNamedTestClasses(suite, java8TestClassNames);
345 >        }
346 >
347 >        // Java9+ test classes
348 >        if (atLeastJava9()) {
349 >            String[] java9TestClassNames = {
350 >                "ThreadPoolExecutor9Test",
351 >            };
352 >            addNamedTestClasses(suite, java9TestClassNames);
353          }
354 +
355          return suite;
356      }
357  
358 +    // Delays for timing-dependent tests, in milliseconds.
359  
360      public static long SHORT_DELAY_MS;
361      public static long SMALL_DELAY_MS;
362      public static long MEDIUM_DELAY_MS;
363      public static long LONG_DELAY_MS;
364  
292
365      /**
366       * Returns the shortest timed delay. This could
367       * be reimplemented to use for example a Property.
# Line 372 | Line 444 | public class JSR166TestCase extends Test
444  
445          if (Thread.interrupted())
446              throw new AssertionFailedError("interrupt status set in main thread");
447 +
448 +        checkForkJoinPoolThreadLeaks();
449 +    }
450 +
451 +    /**
452 +     * Find missing try { ... } finally { joinPool(e); }
453 +     */
454 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
455 +        Thread[] survivors = new Thread[5];
456 +        int count = Thread.enumerate(survivors);
457 +        for (int i = 0; i < count; i++) {
458 +            Thread thread = survivors[i];
459 +            String name = thread.getName();
460 +            if (name.startsWith("ForkJoinPool-")) {
461 +                // give thread some time to terminate
462 +                thread.join(LONG_DELAY_MS);
463 +                if (!thread.isAlive()) continue;
464 +                thread.stop();
465 +                throw new AssertionFailedError
466 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
467 +                                   toString(), name));
468 +            }
469 +        }
470      }
471  
472      /**
# Line 535 | Line 630 | public class JSR166TestCase extends Test
630      void joinPool(ExecutorService exec) {
631          try {
632              exec.shutdown();
633 <            assertTrue("ExecutorService did not terminate in a timely manner",
634 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
633 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
634 >                fail("ExecutorService " + exec +
635 >                     " did not terminate in a timely manner");
636          } catch (SecurityException ok) {
637              // Allowed in case test doesn't have privs
638          } catch (InterruptedException ie) {
# Line 659 | Line 755 | public class JSR166TestCase extends Test
755      public static final Integer m6  = new Integer(-6);
756      public static final Integer m10 = new Integer(-10);
757  
662
758      /**
759       * Runs Runnable r with a security policy that permits precisely
760       * the specified permissions.  If there is no current security
# Line 815 | Line 910 | public class JSR166TestCase extends Test
910       * startNanoTime, which must have been previously returned from a
911       * call to {@link System.nanoTime()}.
912       */
913 <    long millisElapsedSince(long startNanoTime) {
913 >    static long millisElapsedSince(long startNanoTime) {
914          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
915      }
916  
917 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
918 + //         long startTime = System.nanoTime();
919 + //         try {
920 + //             r.run();
921 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
922 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
923 + //             throw new AssertionFailedError("did not return promptly");
924 + //     }
925 +
926 + //     void assertTerminatesPromptly(Runnable r) {
927 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
928 + //     }
929 +
930 +    /**
931 +     * Checks that timed f.get() returns the expected value, and does not
932 +     * wait for the timeout to elapse before returning.
933 +     */
934 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
935 +        long startTime = System.nanoTime();
936 +        try {
937 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
938 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
939 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
940 +            throw new AssertionFailedError("timed get did not return promptly");
941 +    }
942 +
943 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
944 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
945 +    }
946 +
947      /**
948       * Returns a new started daemon Thread running the given runnable.
949       */
# Line 1190 | Line 1315 | public class JSR166TestCase extends Test
1315      public abstract class CheckedRecursiveAction extends RecursiveAction {
1316          protected abstract void realCompute() throws Throwable;
1317  
1318 <        public final void compute() {
1318 >        @Override protected final void compute() {
1319              try {
1320                  realCompute();
1321              } catch (Throwable t) {
# Line 1205 | Line 1330 | public class JSR166TestCase extends Test
1330      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1331          protected abstract T realCompute() throws Throwable;
1332  
1333 <        public final T compute() {
1333 >        @Override protected final T compute() {
1334              try {
1335                  return realCompute();
1336              } catch (Throwable t) {
# Line 1306 | Line 1431 | public class JSR166TestCase extends Test
1431              return null;
1432          }
1433      }
1434 +
1435 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1436 +                             Runnable... throwingActions) {
1437 +        for (Runnable throwingAction : throwingActions) {
1438 +            boolean threw = false;
1439 +            try { throwingAction.run(); }
1440 +            catch (Throwable t) {
1441 +                threw = true;
1442 +                if (!expectedExceptionClass.isInstance(t)) {
1443 +                    AssertionFailedError afe =
1444 +                        new AssertionFailedError
1445 +                        ("Expected " + expectedExceptionClass.getName() +
1446 +                         ", got " + t.getClass().getName());
1447 +                    afe.initCause(t);
1448 +                    threadUnexpectedException(afe);
1449 +                }
1450 +            }
1451 +            if (!threw)
1452 +                shouldThrow(expectedExceptionClass.getName());
1453 +        }
1454 +    }
1455   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines