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.86 by jsr166, Mon May 30 22:42:22 2011 UTC vs.
Revision 1.104 by dl, Thu Mar 21 00:26:43 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 142 | Line 148 | public class JSR166TestCase extends Test
148      }
149  
150      /**
151 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
151 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
152 >     * Optional command line arg provides the number of iterations to
153 >     * repeat running the tests.
154       */
155      public static void main(String[] args) {
156          if (useSecurityManager) {
# Line 174 | Line 182 | public class JSR166TestCase extends Test
182          return suite;
183      }
184  
185 +    public static void addNamedTestClasses(TestSuite suite,
186 +                                           String... testClassNames) {
187 +        for (String testClassName : testClassNames) {
188 +            try {
189 +                Class<?> testClass = Class.forName(testClassName);
190 +                Method m = testClass.getDeclaredMethod("suite",
191 +                                                       new Class<?>[0]);
192 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
193 +            } catch (Exception e) {
194 +                throw new Error("Missing test class", e);
195 +            }
196 +        }
197 +    }
198 +
199 +    public static final double JAVA_CLASS_VERSION;
200 +    static {
201 +        try {
202 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
203 +                new java.security.PrivilegedAction<Double>() {
204 +                public Double run() {
205 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
206 +        } catch (Throwable t) {
207 +            throw new Error(t);
208 +        }
209 +    }
210 +
211 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
212 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
213 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
214 +
215      /**
216       * Collects all JSR166 unit tests as one suite.
217       */
218      public static Test suite() {
219 <        return newTestSuite(
219 >        // Java7+ test classes
220 >        TestSuite suite = newTestSuite(
221              ForkJoinPoolTest.suite(),
222              ForkJoinTaskTest.suite(),
223              RecursiveActionTest.suite(),
# Line 243 | Line 282 | public class JSR166TestCase extends Test
282              TreeSetTest.suite(),
283              TreeSubMapTest.suite(),
284              TreeSubSetTest.suite());
285 +
286 +        // Java8+ test classes
287 +        if (atLeastJava8()) {
288 +            String[] java8TestClassNames = {
289 +                "CompletableFutureTest",
290 +                "CountedCompleterTest",
291 +                "DoubleAccumulatorTest",
292 +                "DoubleAdderTest",
293 +                "ForkJoinPool8Test",
294 +                "LongAccumulatorTest",
295 +                "LongAdderTest",
296 +                "StampedLockTest",
297 +            };
298 +            addNamedTestClasses(suite, java8TestClassNames);
299 +        }
300 +
301 +        return suite;
302      }
303  
304  
# Line 334 | Line 390 | public class JSR166TestCase extends Test
390  
391          if (Thread.interrupted())
392              throw new AssertionFailedError("interrupt status set in main thread");
393 +
394 +        checkForkJoinPoolThreadLeaks();
395 +    }
396 +
397 +    /**
398 +     * Find missing try { ... } finally { joinPool(e); }
399 +     */
400 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
401 +        Thread[] survivors = new Thread[5];
402 +        int count = Thread.enumerate(survivors);
403 +        for (int i = 0; i < count; i++) {
404 +            Thread thread = survivors[i];
405 +            String name = thread.getName();
406 +            if (name.startsWith("ForkJoinPool-")) {
407 +                // give thread some time to terminate
408 +                thread.join(LONG_DELAY_MS);
409 +                if (!thread.isAlive()) continue;
410 +                thread.stop();
411 +                throw new AssertionFailedError
412 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
413 +                                   toString(), name));
414 +            }
415 +        }
416      }
417  
418      /**
# Line 507 | Line 586 | public class JSR166TestCase extends Test
586      }
587  
588      /**
589 +     * A debugging tool to print all stack traces, as jstack does.
590 +     */
591 +    static void printAllStackTraces() {
592 +        for (ThreadInfo info :
593 +                 ManagementFactory.getThreadMXBean()
594 +                 .dumpAllThreads(true, true))
595 +            System.err.print(info);
596 +    }
597 +
598 +    /**
599       * Checks that thread does not terminate within the default
600       * millisecond delay of {@code timeoutMillis()}.
601       */
# Line 528 | Line 617 | public class JSR166TestCase extends Test
617      }
618  
619      /**
620 +     * Checks that the threads do not terminate within the default
621 +     * millisecond delay of {@code timeoutMillis()}.
622 +     */
623 +    void assertThreadsStayAlive(Thread... threads) {
624 +        assertThreadsStayAlive(timeoutMillis(), threads);
625 +    }
626 +
627 +    /**
628 +     * Checks that the threads do not terminate within the given millisecond delay.
629 +     */
630 +    void assertThreadsStayAlive(long millis, Thread... threads) {
631 +        try {
632 +            // No need to optimize the failing case via Thread.join.
633 +            delay(millis);
634 +            for (Thread thread : threads)
635 +                assertTrue(thread.isAlive());
636 +        } catch (InterruptedException ie) {
637 +            fail("Unexpected InterruptedException");
638 +        }
639 +    }
640 +
641 +    /**
642       * Checks that future.get times out, with the default timeout of
643       * {@code timeoutMillis()}.
644       */
# Line 601 | Line 712 | public class JSR166TestCase extends Test
712          SecurityManager sm = System.getSecurityManager();
713          if (sm == null) {
714              r.run();
715 +        }
716 +        runWithSecurityManagerWithPermissions(r, permissions);
717 +    }
718 +
719 +    /**
720 +     * Runs Runnable r with a security policy that permits precisely
721 +     * the specified permissions.  If there is no current security
722 +     * manager, a temporary one is set for the duration of the
723 +     * Runnable.  We require that any security manager permit
724 +     * getPolicy/setPolicy.
725 +     */
726 +    public void runWithSecurityManagerWithPermissions(Runnable r,
727 +                                                      Permission... permissions) {
728 +        SecurityManager sm = System.getSecurityManager();
729 +        if (sm == null) {
730              Policy savedPolicy = Policy.getPolicy();
731              try {
732                  Policy.setPolicy(permissivePolicy());
733                  System.setSecurityManager(new SecurityManager());
734 <                runWithPermissions(r, permissions);
734 >                runWithSecurityManagerWithPermissions(r, permissions);
735              } finally {
736                  System.setSecurityManager(null);
737                  Policy.setPolicy(savedPolicy);
# Line 653 | Line 779 | public class JSR166TestCase extends Test
779              return perms.implies(p);
780          }
781          public void refresh() {}
782 +        public String toString() {
783 +            List<Permission> ps = new ArrayList<Permission>();
784 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
785 +                ps.add(e.nextElement());
786 +            return "AdjustablePolicy with permissions " + ps;
787 +        }
788      }
789  
790      /**
# Line 690 | Line 822 | public class JSR166TestCase extends Test
822      }
823  
824      /**
825 <     * Waits up to the specified number of milliseconds for the given
825 >     * Spin-waits up to the specified number of milliseconds for the given
826       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
827       */
828      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
829 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
698 <        long t0 = System.nanoTime();
829 >        long startTime = System.nanoTime();
830          for (;;) {
831              Thread.State s = thread.getState();
832              if (s == Thread.State.BLOCKED ||
# Line 704 | Line 835 | public class JSR166TestCase extends Test
835                  return;
836              else if (s == Thread.State.TERMINATED)
837                  fail("Unexpected thread termination");
838 <            else if (System.nanoTime() - t0 > timeoutNanos) {
838 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
839                  threadAssertTrue(thread.isAlive());
840                  return;
841              }
# Line 905 | Line 1036 | public class JSR166TestCase extends Test
1036          }
1037      }
1038  
1039 +    public void await(Semaphore semaphore) {
1040 +        try {
1041 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1042 +        } catch (Throwable t) {
1043 +            threadUnexpectedException(t);
1044 +        }
1045 +    }
1046 +
1047   //     /**
1048   //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1049   //      */
# Line 1173 | Line 1312 | public class JSR166TestCase extends Test
1312          }
1313      }
1314  
1315 <    @SuppressWarnings("unchecked")
1316 <    <T> T serialClone(T o) {
1315 >    void assertSerialEquals(Object x, Object y) {
1316 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1317 >    }
1318 >
1319 >    void assertNotSerialEquals(Object x, Object y) {
1320 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1321 >    }
1322 >
1323 >    byte[] serialBytes(Object o) {
1324          try {
1325              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1326              ObjectOutputStream oos = new ObjectOutputStream(bos);
1327              oos.writeObject(o);
1328              oos.flush();
1329              oos.close();
1330 <            ByteArrayInputStream bin =
1331 <                new ByteArrayInputStream(bos.toByteArray());
1332 <            ObjectInputStream ois = new ObjectInputStream(bin);
1333 <            return (T) ois.readObject();
1330 >            return bos.toByteArray();
1331 >        } catch (Throwable t) {
1332 >            threadUnexpectedException(t);
1333 >            return new byte[0];
1334 >        }
1335 >    }
1336 >
1337 >    @SuppressWarnings("unchecked")
1338 >    <T> T serialClone(T o) {
1339 >        try {
1340 >            ObjectInputStream ois = new ObjectInputStream
1341 >                (new ByteArrayInputStream(serialBytes(o)));
1342 >            T clone = (T) ois.readObject();
1343 >            assertSame(o.getClass(), clone.getClass());
1344 >            return clone;
1345          } catch (Throwable t) {
1346              threadUnexpectedException(t);
1347              return null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines