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.83 by jsr166, Fri May 27 19:29:59 2011 UTC vs.
Revision 1.109 by jsr166, Sun Jul 14 16:55:01 2013 UTC

# Line 11 | Line 11 | import java.io.ByteArrayInputStream;
11   import java.io.ByteArrayOutputStream;
12   import java.io.ObjectInputStream;
13   import java.io.ObjectOutputStream;
14 + import java.lang.management.ManagementFactory;
15 + import java.lang.management.ThreadInfo;
16 + import java.lang.reflect.Method;
17 + import java.util.ArrayList;
18   import java.util.Arrays;
19   import java.util.Date;
20 + import java.util.Enumeration;
21 + import java.util.List;
22   import java.util.NoSuchElementException;
23   import java.util.PropertyPermission;
24   import java.util.concurrent.*;
# Line 69 | Line 75 | import java.security.SecurityPermission;
75   *
76   * </ol>
77   *
78 < * <p> <b>Other notes</b>
78 > * <p><b>Other notes</b>
79   * <ul>
80   *
81   * <li> Usually, there is one testcase method per JSR166 method
# Line 122 | Line 128 | public class JSR166TestCase extends Test
128      private static final long profileThreshold =
129          Long.getLong("jsr166.profileThreshold", 100);
130  
131 +    /**
132 +     * The number of repetitions per test (for tickling rare bugs).
133 +     */
134 +    private static final int runsPerTest =
135 +        Integer.getInteger("jsr166.runsPerTest", 1);
136 +
137      protected void runTest() throws Throwable {
138 <        if (profileTests)
139 <            runTestProfiled();
140 <        else
141 <            super.runTest();
138 >        for (int i = 0; i < runsPerTest; i++) {
139 >            if (profileTests)
140 >                runTestProfiled();
141 >            else
142 >                super.runTest();
143 >        }
144      }
145  
146      protected void runTestProfiled() throws Throwable {
# Line 142 | Line 156 | public class JSR166TestCase extends Test
156      }
157  
158      /**
159 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
159 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
160 >     * Optional command line arg provides the number of iterations to
161 >     * repeat running the tests.
162       */
163      public static void main(String[] args) {
164          if (useSecurityManager) {
# Line 174 | Line 190 | public class JSR166TestCase extends Test
190          return suite;
191      }
192  
193 +    public static void addNamedTestClasses(TestSuite suite,
194 +                                           String... testClassNames) {
195 +        for (String testClassName : testClassNames) {
196 +            try {
197 +                Class<?> testClass = Class.forName(testClassName);
198 +                Method m = testClass.getDeclaredMethod("suite",
199 +                                                       new Class<?>[0]);
200 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
201 +            } catch (Exception e) {
202 +                throw new Error("Missing test class", e);
203 +            }
204 +        }
205 +    }
206 +
207 +    public static final double JAVA_CLASS_VERSION;
208 +    static {
209 +        try {
210 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
211 +                new java.security.PrivilegedAction<Double>() {
212 +                public Double run() {
213 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
214 +        } catch (Throwable t) {
215 +            throw new Error(t);
216 +        }
217 +    }
218 +
219 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
220 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
221 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
222 +
223      /**
224       * Collects all JSR166 unit tests as one suite.
225       */
226      public static Test suite() {
227 <        return newTestSuite(
227 >        // Java7+ test classes
228 >        TestSuite suite = newTestSuite(
229              ForkJoinPoolTest.suite(),
230              ForkJoinTaskTest.suite(),
231              RecursiveActionTest.suite(),
232              RecursiveTaskTest.suite(),
233              LinkedTransferQueueTest.suite(),
234              PhaserTest.suite(),
235 +            SplittableRandomTest.suite(),
236              ThreadLocalRandomTest.suite(),
237              AbstractExecutorServiceTest.suite(),
238              AbstractQueueTest.suite(),
# Line 243 | Line 291 | public class JSR166TestCase extends Test
291              TreeSetTest.suite(),
292              TreeSubMapTest.suite(),
293              TreeSubSetTest.suite());
294 +
295 +        // Java8+ test classes
296 +        if (atLeastJava8()) {
297 +            String[] java8TestClassNames = {
298 +                "CompletableFutureTest",
299 +                "ConcurrentHashMap8Test",
300 +                "CountedCompleterTest",
301 +                "DoubleAccumulatorTest",
302 +                "DoubleAdderTest",
303 +                "ForkJoinPool8Test",
304 +                "LongAccumulatorTest",
305 +                "LongAdderTest",
306 +                "StampedLockTest",
307 +            };
308 +            addNamedTestClasses(suite, java8TestClassNames);
309 +        }
310 +
311 +        return suite;
312      }
313  
314 +    // Delays for timing-dependent tests, in milliseconds.
315  
316      public static long SHORT_DELAY_MS;
317      public static long SMALL_DELAY_MS;
318      public static long MEDIUM_DELAY_MS;
319      public static long LONG_DELAY_MS;
320  
254
321      /**
322       * Returns the shortest timed delay. This could
323       * be reimplemented to use for example a Property.
# Line 283 | Line 349 | public class JSR166TestCase extends Test
349       * milliseconds in the future.
350       */
351      Date delayedDate(long delayMillis) {
352 <        return new Date(new Date().getTime() + delayMillis);
352 >        return new Date(System.currentTimeMillis() + delayMillis);
353      }
354  
355      /**
# Line 307 | Line 373 | public class JSR166TestCase extends Test
373      }
374  
375      /**
376 +     * Extra checks that get done for all test cases.
377 +     *
378       * Triggers test case failure if any thread assertions have failed,
379       * by rethrowing, in the test harness thread, any exception recorded
380       * earlier by threadRecordFailure.
381 +     *
382 +     * Triggers test case failure if interrupt status is set in the main thread.
383       */
384      public void tearDown() throws Exception {
385          Throwable t = threadFailure.getAndSet(null);
# Line 327 | Line 397 | public class JSR166TestCase extends Test
397                  throw afe;
398              }
399          }
400 +
401 +        if (Thread.interrupted())
402 +            throw new AssertionFailedError("interrupt status set in main thread");
403 +
404 +        checkForkJoinPoolThreadLeaks();
405 +    }
406 +
407 +    /**
408 +     * Find missing try { ... } finally { joinPool(e); }
409 +     */
410 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
411 +        Thread[] survivors = new Thread[5];
412 +        int count = Thread.enumerate(survivors);
413 +        for (int i = 0; i < count; i++) {
414 +            Thread thread = survivors[i];
415 +            String name = thread.getName();
416 +            if (name.startsWith("ForkJoinPool-")) {
417 +                // give thread some time to terminate
418 +                thread.join(LONG_DELAY_MS);
419 +                if (!thread.isAlive()) continue;
420 +                thread.stop();
421 +                throw new AssertionFailedError
422 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
423 +                                   toString(), name));
424 +            }
425 +        }
426      }
427  
428      /**
# Line 500 | Line 596 | public class JSR166TestCase extends Test
596      }
597  
598      /**
599 +     * A debugging tool to print all stack traces, as jstack does.
600 +     */
601 +    static void printAllStackTraces() {
602 +        for (ThreadInfo info :
603 +                 ManagementFactory.getThreadMXBean()
604 +                 .dumpAllThreads(true, true))
605 +            System.err.print(info);
606 +    }
607 +
608 +    /**
609       * Checks that thread does not terminate within the default
610       * millisecond delay of {@code timeoutMillis()}.
611       */
# Line 521 | Line 627 | public class JSR166TestCase extends Test
627      }
628  
629      /**
630 +     * Checks that the threads do not terminate within the default
631 +     * millisecond delay of {@code timeoutMillis()}.
632 +     */
633 +    void assertThreadsStayAlive(Thread... threads) {
634 +        assertThreadsStayAlive(timeoutMillis(), threads);
635 +    }
636 +
637 +    /**
638 +     * Checks that the threads do not terminate within the given millisecond delay.
639 +     */
640 +    void assertThreadsStayAlive(long millis, Thread... threads) {
641 +        try {
642 +            // No need to optimize the failing case via Thread.join.
643 +            delay(millis);
644 +            for (Thread thread : threads)
645 +                assertTrue(thread.isAlive());
646 +        } catch (InterruptedException ie) {
647 +            fail("Unexpected InterruptedException");
648 +        }
649 +    }
650 +
651 +    /**
652       * Checks that future.get times out, with the default timeout of
653       * {@code timeoutMillis()}.
654       */
# Line 582 | Line 710 | public class JSR166TestCase extends Test
710      public static final Integer m6  = new Integer(-6);
711      public static final Integer m10 = new Integer(-10);
712  
585
713      /**
714       * Runs Runnable r with a security policy that permits precisely
715       * the specified permissions.  If there is no current security
# Line 594 | Line 721 | public class JSR166TestCase extends Test
721          SecurityManager sm = System.getSecurityManager();
722          if (sm == null) {
723              r.run();
724 +        }
725 +        runWithSecurityManagerWithPermissions(r, permissions);
726 +    }
727 +
728 +    /**
729 +     * Runs Runnable r with a security policy that permits precisely
730 +     * the specified permissions.  If there is no current security
731 +     * manager, a temporary one is set for the duration of the
732 +     * Runnable.  We require that any security manager permit
733 +     * getPolicy/setPolicy.
734 +     */
735 +    public void runWithSecurityManagerWithPermissions(Runnable r,
736 +                                                      Permission... permissions) {
737 +        SecurityManager sm = System.getSecurityManager();
738 +        if (sm == null) {
739              Policy savedPolicy = Policy.getPolicy();
740              try {
741                  Policy.setPolicy(permissivePolicy());
742                  System.setSecurityManager(new SecurityManager());
743 <                runWithPermissions(r, permissions);
743 >                runWithSecurityManagerWithPermissions(r, permissions);
744              } finally {
745                  System.setSecurityManager(null);
746                  Policy.setPolicy(savedPolicy);
# Line 646 | Line 788 | public class JSR166TestCase extends Test
788              return perms.implies(p);
789          }
790          public void refresh() {}
791 +        public String toString() {
792 +            List<Permission> ps = new ArrayList<Permission>();
793 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
794 +                ps.add(e.nextElement());
795 +            return "AdjustablePolicy with permissions " + ps;
796 +        }
797      }
798  
799      /**
# Line 683 | Line 831 | public class JSR166TestCase extends Test
831      }
832  
833      /**
834 <     * Waits up to the specified number of milliseconds for the given
834 >     * Spin-waits up to the specified number of milliseconds for the given
835       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
836       */
837      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
838 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
691 <        long t0 = System.nanoTime();
838 >        long startTime = System.nanoTime();
839          for (;;) {
840              Thread.State s = thread.getState();
841              if (s == Thread.State.BLOCKED ||
# Line 697 | Line 844 | public class JSR166TestCase extends Test
844                  return;
845              else if (s == Thread.State.TERMINATED)
846                  fail("Unexpected thread termination");
847 <            else if (System.nanoTime() - t0 > timeoutNanos) {
847 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
848                  threadAssertTrue(thread.isAlive());
849                  return;
850              }
# Line 898 | Line 1045 | public class JSR166TestCase extends Test
1045          }
1046      }
1047  
1048 +    public void await(Semaphore semaphore) {
1049 +        try {
1050 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1051 +        } catch (Throwable t) {
1052 +            threadUnexpectedException(t);
1053 +        }
1054 +    }
1055 +
1056   //     /**
1057   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1058   //      */
# Line 1085 | Line 1240 | public class JSR166TestCase extends Test
1240      public abstract class CheckedRecursiveAction extends RecursiveAction {
1241          protected abstract void realCompute() throws Throwable;
1242  
1243 <        public final void compute() {
1243 >        @Override protected final void compute() {
1244              try {
1245                  realCompute();
1246              } catch (Throwable t) {
# Line 1100 | Line 1255 | public class JSR166TestCase extends Test
1255      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1256          protected abstract T realCompute() throws Throwable;
1257  
1258 <        public final T compute() {
1258 >        @Override protected final T compute() {
1259              try {
1260                  return realCompute();
1261              } catch (Throwable t) {
# Line 1119 | Line 1274 | public class JSR166TestCase extends Test
1274      }
1275  
1276      /**
1277 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1278 <     * of throwing checked exceptions.
1277 >     * A CyclicBarrier that uses timed await and fails with
1278 >     * AssertionFailedErrors instead of throwing checked exceptions.
1279       */
1280      public class CheckedBarrier extends CyclicBarrier {
1281          public CheckedBarrier(int parties) { super(parties); }
1282  
1283          public int await() {
1284              try {
1285 <                return super.await();
1285 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1286 >            } catch (TimeoutException e) {
1287 >                throw new AssertionFailedError("timed out");
1288              } catch (Exception e) {
1289                  AssertionFailedError afe =
1290                      new AssertionFailedError("Unexpected exception: " + e);
# Line 1164 | Line 1321 | public class JSR166TestCase extends Test
1321          }
1322      }
1323  
1324 <    @SuppressWarnings("unchecked")
1325 <    <T> T serialClone(T o) {
1324 >    void assertSerialEquals(Object x, Object y) {
1325 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1326 >    }
1327 >
1328 >    void assertNotSerialEquals(Object x, Object y) {
1329 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1330 >    }
1331 >
1332 >    byte[] serialBytes(Object o) {
1333          try {
1334              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1335              ObjectOutputStream oos = new ObjectOutputStream(bos);
1336              oos.writeObject(o);
1337              oos.flush();
1338              oos.close();
1339 <            ByteArrayInputStream bin =
1340 <                new ByteArrayInputStream(bos.toByteArray());
1341 <            ObjectInputStream ois = new ObjectInputStream(bin);
1342 <            return (T) ois.readObject();
1339 >            return bos.toByteArray();
1340 >        } catch (Throwable t) {
1341 >            threadUnexpectedException(t);
1342 >            return new byte[0];
1343 >        }
1344 >    }
1345 >
1346 >    @SuppressWarnings("unchecked")
1347 >    <T> T serialClone(T o) {
1348 >        try {
1349 >            ObjectInputStream ois = new ObjectInputStream
1350 >                (new ByteArrayInputStream(serialBytes(o)));
1351 >            T clone = (T) ois.readObject();
1352 >            assertSame(o.getClass(), clone.getClass());
1353 >            return clone;
1354          } catch (Throwable t) {
1355              threadUnexpectedException(t);
1356              return null;
1357          }
1358      }
1359 +
1360 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1361 +                             Runnable... throwingActions) {
1362 +        for (Runnable throwingAction : throwingActions) {
1363 +            boolean threw = false;
1364 +            try { throwingAction.run(); }
1365 +            catch (Throwable t) {
1366 +                threw = true;
1367 +                if (!expectedExceptionClass.isInstance(t)) {
1368 +                    AssertionFailedError afe =
1369 +                        new AssertionFailedError
1370 +                        ("Expected " + expectedExceptionClass.getName() +
1371 +                         ", got " + t.getClass().getName());
1372 +                    afe.initCause(t);
1373 +                    threadUnexpectedException(afe);
1374 +                }
1375 +            }
1376 +            if (!threw)
1377 +                shouldThrow(expectedExceptionClass.getName());
1378 +        }
1379 +    }
1380   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines