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.80 by jsr166, Fri May 13 21:48:58 2011 UTC vs.
Revision 1.136 by jsr166, Fri Sep 4 18:16:28 2015 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 < import junit.framework.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 >
12   import java.io.ByteArrayInputStream;
13   import java.io.ByteArrayOutputStream;
14   import java.io.ObjectInputStream;
15   import java.io.ObjectOutputStream;
16 < import java.util.Arrays;
17 < import java.util.NoSuchElementException;
18 < import java.util.PropertyPermission;
19 < import java.util.concurrent.*;
20 < import java.util.concurrent.atomic.AtomicReference;
19 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
20 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
16 > import java.lang.management.ManagementFactory;
17 > import java.lang.management.ThreadInfo;
18 > import java.lang.reflect.Constructor;
19 > import java.lang.reflect.Method;
20 > import java.lang.reflect.Modifier;
21   import java.security.CodeSource;
22   import java.security.Permission;
23   import java.security.PermissionCollection;
# Line 25 | Line 25 | import java.security.Permissions;
25   import java.security.Policy;
26   import java.security.ProtectionDomain;
27   import java.security.SecurityPermission;
28 + import java.util.ArrayList;
29 + import java.util.Arrays;
30 + import java.util.Date;
31 + import java.util.Enumeration;
32 + import java.util.Iterator;
33 + import java.util.List;
34 + import java.util.NoSuchElementException;
35 + import java.util.PropertyPermission;
36 + import java.util.concurrent.BlockingQueue;
37 + import java.util.concurrent.Callable;
38 + import java.util.concurrent.CountDownLatch;
39 + import java.util.concurrent.CyclicBarrier;
40 + import java.util.concurrent.ExecutorService;
41 + import java.util.concurrent.Future;
42 + import java.util.concurrent.RecursiveAction;
43 + import java.util.concurrent.RecursiveTask;
44 + import java.util.concurrent.RejectedExecutionHandler;
45 + import java.util.concurrent.Semaphore;
46 + import java.util.concurrent.ThreadFactory;
47 + import java.util.concurrent.ThreadPoolExecutor;
48 + import java.util.concurrent.TimeoutException;
49 + import java.util.concurrent.atomic.AtomicReference;
50 + import java.util.regex.Pattern;
51 +
52 + import junit.framework.AssertionFailedError;
53 + import junit.framework.Test;
54 + import junit.framework.TestCase;
55 + import junit.framework.TestResult;
56 + import junit.framework.TestSuite;
57  
58   /**
59   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 67 | Line 96 | import java.security.SecurityPermission;
96   *
97   * </ol>
98   *
99 < * <p> <b>Other notes</b>
99 > * <p><b>Other notes</b>
100   * <ul>
101   *
102   * <li> Usually, there is one testcase method per JSR166 method
# Line 107 | Line 136 | public class JSR166TestCase extends Test
136          Boolean.getBoolean("jsr166.expensiveTests");
137  
138      /**
139 +     * If true, also run tests that are not part of the official tck
140 +     * because they test unspecified implementation details.
141 +     */
142 +    protected static final boolean testImplementationDetails =
143 +        Boolean.getBoolean("jsr166.testImplementationDetails");
144 +
145 +    /**
146       * If true, report on stdout all "slow" tests, that is, ones that
147       * take more than profileThreshold milliseconds to execute.
148       */
# Line 120 | Line 156 | public class JSR166TestCase extends Test
156      private static final long profileThreshold =
157          Long.getLong("jsr166.profileThreshold", 100);
158  
159 +    /**
160 +     * The number of repetitions per test (for tickling rare bugs).
161 +     */
162 +    private static final int runsPerTest =
163 +        Integer.getInteger("jsr166.runsPerTest", 1);
164 +
165 +    /**
166 +     * The number of repetitions of the test suite (for finding leaks?).
167 +     */
168 +    private static final int suiteRuns =
169 +        Integer.getInteger("jsr166.suiteRuns", 1);
170 +
171 +    public JSR166TestCase() { super(); }
172 +    public JSR166TestCase(String name) { super(name); }
173 +
174 +    /**
175 +     * A filter for tests to run, matching strings of the form
176 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
177 +     * Usefully combined with jsr166.runsPerTest.
178 +     */
179 +    private static final Pattern methodFilter = methodFilter();
180 +
181 +    private static Pattern methodFilter() {
182 +        String regex = System.getProperty("jsr166.methodFilter");
183 +        return (regex == null) ? null : Pattern.compile(regex);
184 +    }
185 +
186      protected void runTest() throws Throwable {
187 <        if (profileTests)
188 <            runTestProfiled();
189 <        else
190 <            super.runTest();
187 >        if (methodFilter == null
188 >            || methodFilter.matcher(toString()).find()) {
189 >            for (int i = 0; i < runsPerTest; i++) {
190 >                if (profileTests)
191 >                    runTestProfiled();
192 >                else
193 >                    super.runTest();
194 >            }
195 >        }
196      }
197  
198      protected void runTestProfiled() throws Throwable {
199 +        // Warmup run, notably to trigger all needed classloading.
200 +        super.runTest();
201          long t0 = System.nanoTime();
202          try {
203              super.runTest();
204          } finally {
205 <            long elapsedMillis =
136 <                (System.nanoTime() - t0) / (1000L * 1000L);
205 >            long elapsedMillis = millisElapsedSince(t0);
206              if (elapsedMillis >= profileThreshold)
207                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
208          }
209      }
210  
211      /**
212 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
212 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
213       */
214      public static void main(String[] args) {
215 +        main(suite(), args);
216 +    }
217 +
218 +    /**
219 +     * Runs all unit tests in the given test suite.
220 +     * Actual behavior influenced by jsr166.* system properties.
221 +     */
222 +    static void main(Test suite, String[] args) {
223          if (useSecurityManager) {
224              System.err.println("Setting a permissive security manager");
225              Policy.setPolicy(permissivePolicy());
226              System.setSecurityManager(new SecurityManager());
227          }
228 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
229 <
230 <        Test s = suite();
231 <        for (int i = 0; i < iters; ++i) {
155 <            junit.textui.TestRunner.run(s);
228 >        for (int i = 0; i < suiteRuns; i++) {
229 >            TestResult result = junit.textui.TestRunner.run(suite);
230 >            if (!result.wasSuccessful())
231 >                System.exit(1);
232              System.gc();
233              System.runFinalization();
234          }
159        System.exit(0);
235      }
236  
237      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 172 | Line 247 | public class JSR166TestCase extends Test
247          return suite;
248      }
249  
250 +    public static void addNamedTestClasses(TestSuite suite,
251 +                                           String... testClassNames) {
252 +        for (String testClassName : testClassNames) {
253 +            try {
254 +                Class<?> testClass = Class.forName(testClassName);
255 +                Method m = testClass.getDeclaredMethod("suite",
256 +                                                       new Class<?>[0]);
257 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
258 +            } catch (Exception e) {
259 +                throw new Error("Missing test class", e);
260 +            }
261 +        }
262 +    }
263 +
264 +    public static final double JAVA_CLASS_VERSION;
265 +    public static final String JAVA_SPECIFICATION_VERSION;
266 +    static {
267 +        try {
268 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
269 +                new java.security.PrivilegedAction<Double>() {
270 +                public Double run() {
271 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
272 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
273 +                new java.security.PrivilegedAction<String>() {
274 +                public String run() {
275 +                    return System.getProperty("java.specification.version");}});
276 +        } catch (Throwable t) {
277 +            throw new Error(t);
278 +        }
279 +    }
280 +
281 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
282 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
283 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
284 +    public static boolean atLeastJava9() {
285 +        // As of 2015-09, java9 still uses 52.0 class file version
286 +        return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
287 +    }
288 +    // public static boolean atLeastJava9() { return JAVA_CLASS_VERSION >= 53.0; }
289 +    public static boolean atLeastJava10() {
290 +        return JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
291 +    }
292 +
293      /**
294       * Collects all JSR166 unit tests as one suite.
295       */
296      public static Test suite() {
297 <        return newTestSuite(
297 >        // Java7+ test classes
298 >        TestSuite suite = newTestSuite(
299              ForkJoinPoolTest.suite(),
300              ForkJoinTaskTest.suite(),
301              RecursiveActionTest.suite(),
# Line 241 | Line 360 | public class JSR166TestCase extends Test
360              TreeSetTest.suite(),
361              TreeSubMapTest.suite(),
362              TreeSubSetTest.suite());
363 +
364 +        // Java8+ test classes
365 +        if (atLeastJava8()) {
366 +            String[] java8TestClassNames = {
367 +                "Atomic8Test",
368 +                "CompletableFutureTest",
369 +                "ConcurrentHashMap8Test",
370 +                "CountedCompleterTest",
371 +                "DoubleAccumulatorTest",
372 +                "DoubleAdderTest",
373 +                "ForkJoinPool8Test",
374 +                "ForkJoinTask8Test",
375 +                "LongAccumulatorTest",
376 +                "LongAdderTest",
377 +                "SplittableRandomTest",
378 +                "StampedLockTest",
379 +                "ThreadLocalRandom8Test",
380 +            };
381 +            addNamedTestClasses(suite, java8TestClassNames);
382 +        }
383 +
384 +        // Java9+ test classes
385 +        if (atLeastJava9()) {
386 +            String[] java9TestClassNames = {
387 +                "ThreadPoolExecutor9Test",
388 +            };
389 +            addNamedTestClasses(suite, java9TestClassNames);
390 +        }
391 +
392 +        return suite;
393 +    }
394 +
395 +    /** Returns list of junit-style test method names in given class. */
396 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
397 +        Method[] methods = testClass.getDeclaredMethods();
398 +        ArrayList<String> names = new ArrayList<String>(methods.length);
399 +        for (Method method : methods) {
400 +            if (method.getName().startsWith("test")
401 +                && Modifier.isPublic(method.getModifiers())
402 +                // method.getParameterCount() requires jdk8+
403 +                && method.getParameterTypes().length == 0) {
404 +                names.add(method.getName());
405 +            }
406 +        }
407 +        return names;
408 +    }
409 +
410 +    /**
411 +     * Returns junit-style testSuite for the given test class, but
412 +     * parameterized by passing extra data to each test.
413 +     */
414 +    public static <ExtraData> Test parameterizedTestSuite
415 +        (Class<? extends JSR166TestCase> testClass,
416 +         Class<ExtraData> dataClass,
417 +         ExtraData data) {
418 +        try {
419 +            TestSuite suite = new TestSuite();
420 +            Constructor c =
421 +                testClass.getDeclaredConstructor(dataClass, String.class);
422 +            for (String methodName : testMethodNames(testClass))
423 +                suite.addTest((Test) c.newInstance(data, methodName));
424 +            return suite;
425 +        } catch (Exception e) {
426 +            throw new Error(e);
427 +        }
428 +    }
429 +
430 +    /**
431 +     * Returns junit-style testSuite for the jdk8 extension of the
432 +     * given test class, but parameterized by passing extra data to
433 +     * each test.  Uses reflection to allow compilation in jdk7.
434 +     */
435 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
436 +        (Class<? extends JSR166TestCase> testClass,
437 +         Class<ExtraData> dataClass,
438 +         ExtraData data) {
439 +        if (atLeastJava8()) {
440 +            String name = testClass.getName();
441 +            String name8 = name.replaceAll("Test$", "8Test");
442 +            if (name.equals(name8)) throw new Error(name);
443 +            try {
444 +                return (Test)
445 +                    Class.forName(name8)
446 +                    .getMethod("testSuite", new Class[] { dataClass })
447 +                    .invoke(null, data);
448 +            } catch (Exception e) {
449 +                throw new Error(e);
450 +            }
451 +        } else {
452 +            return new TestSuite();
453 +        }
454 +
455      }
456  
457 +    // Delays for timing-dependent tests, in milliseconds.
458  
459      public static long SHORT_DELAY_MS;
460      public static long SMALL_DELAY_MS;
461      public static long MEDIUM_DELAY_MS;
462      public static long LONG_DELAY_MS;
463  
252
464      /**
465       * Returns the shortest timed delay. This could
466       * be reimplemented to use for example a Property.
# Line 258 | Line 469 | public class JSR166TestCase extends Test
469          return 50;
470      }
471  
261
472      /**
473       * Sets delays as multiples of SHORT_DELAY.
474       */
# Line 270 | Line 480 | public class JSR166TestCase extends Test
480      }
481  
482      /**
483 +     * Returns a timeout in milliseconds to be used in tests that
484 +     * verify that operations block or time out.
485 +     */
486 +    long timeoutMillis() {
487 +        return SHORT_DELAY_MS / 4;
488 +    }
489 +
490 +    /**
491 +     * Returns a new Date instance representing a time at least
492 +     * delayMillis milliseconds in the future.
493 +     */
494 +    Date delayedDate(long delayMillis) {
495 +        // Add 1 because currentTimeMillis is known to round into the past.
496 +        return new Date(System.currentTimeMillis() + delayMillis + 1);
497 +    }
498 +
499 +    /**
500       * The first exception encountered if any threadAssertXXX method fails.
501       */
502      private final AtomicReference<Throwable> threadFailure
# Line 290 | Line 517 | public class JSR166TestCase extends Test
517      }
518  
519      /**
520 +     * Extra checks that get done for all test cases.
521 +     *
522       * Triggers test case failure if any thread assertions have failed,
523       * by rethrowing, in the test harness thread, any exception recorded
524       * earlier by threadRecordFailure.
525 +     *
526 +     * Triggers test case failure if interrupt status is set in the main thread.
527       */
528      public void tearDown() throws Exception {
529          Throwable t = threadFailure.getAndSet(null);
# Line 310 | Line 541 | public class JSR166TestCase extends Test
541                  throw afe;
542              }
543          }
544 +
545 +        if (Thread.interrupted())
546 +            throw new AssertionFailedError("interrupt status set in main thread");
547 +
548 +        checkForkJoinPoolThreadLeaks();
549 +    }
550 +
551 +    /**
552 +     * Finds missing try { ... } finally { joinPool(e); }
553 +     */
554 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
555 +        Thread[] survivors = new Thread[5];
556 +        int count = Thread.enumerate(survivors);
557 +        for (int i = 0; i < count; i++) {
558 +            Thread thread = survivors[i];
559 +            String name = thread.getName();
560 +            if (name.startsWith("ForkJoinPool-")) {
561 +                // give thread some time to terminate
562 +                thread.join(LONG_DELAY_MS);
563 +                if (!thread.isAlive()) continue;
564 +                throw new AssertionFailedError
565 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
566 +                                   toString(), name));
567 +            }
568 +        }
569      }
570  
571      /**
# Line 390 | Line 646 | public class JSR166TestCase extends Test
646      public void threadAssertEquals(Object x, Object y) {
647          try {
648              assertEquals(x, y);
649 <        } catch (AssertionFailedError t) {
650 <            threadRecordFailure(t);
651 <            throw t;
652 <        } catch (Throwable t) {
653 <            threadUnexpectedException(t);
649 >        } catch (AssertionFailedError fail) {
650 >            threadRecordFailure(fail);
651 >            throw fail;
652 >        } catch (Throwable fail) {
653 >            threadUnexpectedException(fail);
654          }
655      }
656  
# Line 406 | Line 662 | public class JSR166TestCase extends Test
662      public void threadAssertSame(Object x, Object y) {
663          try {
664              assertSame(x, y);
665 <        } catch (AssertionFailedError t) {
666 <            threadRecordFailure(t);
667 <            throw t;
665 >        } catch (AssertionFailedError fail) {
666 >            threadRecordFailure(fail);
667 >            throw fail;
668          }
669      }
670  
# Line 441 | Line 697 | public class JSR166TestCase extends Test
697          else {
698              AssertionFailedError afe =
699                  new AssertionFailedError("unexpected exception: " + t);
700 <            t.initCause(t);
700 >            afe.initCause(t);
701              throw afe;
702          }
703      }
704  
705      /**
706 <     * Delays, via Thread.sleep for the given millisecond delay, but
706 >     * Delays, via Thread.sleep, for the given millisecond delay, but
707       * if the sleep is shorter than specified, may re-sleep or yield
708       * until time elapses.
709       */
710 <    public static void delay(long millis) throws InterruptedException {
710 >    static void delay(long millis) throws InterruptedException {
711          long startTime = System.nanoTime();
712          long ns = millis * 1000 * 1000;
713          for (;;) {
# Line 470 | Line 726 | public class JSR166TestCase extends Test
726      /**
727       * Waits out termination of a thread pool or fails doing so.
728       */
729 <    public void joinPool(ExecutorService exec) {
729 >    void joinPool(ExecutorService exec) {
730          try {
731              exec.shutdown();
732 <            assertTrue("ExecutorService did not terminate in a timely manner",
733 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
732 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
733 >                fail("ExecutorService " + exec +
734 >                     " did not terminate in a timely manner");
735          } catch (SecurityException ok) {
736              // Allowed in case test doesn't have privs
737 <        } catch (InterruptedException ie) {
737 >        } catch (InterruptedException fail) {
738              fail("Unexpected InterruptedException");
739          }
740      }
741  
742      /**
743 +     * A debugging tool to print all stack traces, as jstack does.
744 +     */
745 +    static void printAllStackTraces() {
746 +        for (ThreadInfo info :
747 +                 ManagementFactory.getThreadMXBean()
748 +                 .dumpAllThreads(true, true))
749 +            System.err.print(info);
750 +    }
751 +
752 +    /**
753 +     * Checks that thread does not terminate within the default
754 +     * millisecond delay of {@code timeoutMillis()}.
755 +     */
756 +    void assertThreadStaysAlive(Thread thread) {
757 +        assertThreadStaysAlive(thread, timeoutMillis());
758 +    }
759 +
760 +    /**
761       * Checks that thread does not terminate within the given millisecond delay.
762       */
763 <    public void assertThreadStaysAlive(Thread thread, long millis) {
763 >    void assertThreadStaysAlive(Thread thread, long millis) {
764          try {
765              // No need to optimize the failing case via Thread.join.
766              delay(millis);
767              assertTrue(thread.isAlive());
768 <        } catch (InterruptedException ie) {
768 >        } catch (InterruptedException fail) {
769 >            fail("Unexpected InterruptedException");
770 >        }
771 >    }
772 >
773 >    /**
774 >     * Checks that the threads do not terminate within the default
775 >     * millisecond delay of {@code timeoutMillis()}.
776 >     */
777 >    void assertThreadsStayAlive(Thread... threads) {
778 >        assertThreadsStayAlive(timeoutMillis(), threads);
779 >    }
780 >
781 >    /**
782 >     * Checks that the threads do not terminate within the given millisecond delay.
783 >     */
784 >    void assertThreadsStayAlive(long millis, Thread... threads) {
785 >        try {
786 >            // No need to optimize the failing case via Thread.join.
787 >            delay(millis);
788 >            for (Thread thread : threads)
789 >                assertTrue(thread.isAlive());
790 >        } catch (InterruptedException fail) {
791              fail("Unexpected InterruptedException");
792          }
793      }
794  
795      /**
796 +     * Checks that future.get times out, with the default timeout of
797 +     * {@code timeoutMillis()}.
798 +     */
799 +    void assertFutureTimesOut(Future future) {
800 +        assertFutureTimesOut(future, timeoutMillis());
801 +    }
802 +
803 +    /**
804 +     * Checks that future.get times out, with the given millisecond timeout.
805 +     */
806 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
807 +        long startTime = System.nanoTime();
808 +        try {
809 +            future.get(timeoutMillis, MILLISECONDS);
810 +            shouldThrow();
811 +        } catch (TimeoutException success) {
812 +        } catch (Exception fail) {
813 +            threadUnexpectedException(fail);
814 +        } finally { future.cancel(true); }
815 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
816 +    }
817 +
818 +    /**
819       * Fails with message "should throw exception".
820       */
821      public void shouldThrow() {
# Line 534 | Line 854 | public class JSR166TestCase extends Test
854      public static final Integer m6  = new Integer(-6);
855      public static final Integer m10 = new Integer(-10);
856  
537
857      /**
858       * Runs Runnable r with a security policy that permits precisely
859       * the specified permissions.  If there is no current security
# Line 546 | Line 865 | public class JSR166TestCase extends Test
865          SecurityManager sm = System.getSecurityManager();
866          if (sm == null) {
867              r.run();
868 +        }
869 +        runWithSecurityManagerWithPermissions(r, permissions);
870 +    }
871 +
872 +    /**
873 +     * Runs Runnable r with a security policy that permits precisely
874 +     * the specified permissions.  If there is no current security
875 +     * manager, a temporary one is set for the duration of the
876 +     * Runnable.  We require that any security manager permit
877 +     * getPolicy/setPolicy.
878 +     */
879 +    public void runWithSecurityManagerWithPermissions(Runnable r,
880 +                                                      Permission... permissions) {
881 +        SecurityManager sm = System.getSecurityManager();
882 +        if (sm == null) {
883              Policy savedPolicy = Policy.getPolicy();
884              try {
885                  Policy.setPolicy(permissivePolicy());
886                  System.setSecurityManager(new SecurityManager());
887 <                runWithPermissions(r, permissions);
887 >                runWithSecurityManagerWithPermissions(r, permissions);
888              } finally {
889                  System.setSecurityManager(null);
890                  Policy.setPolicy(savedPolicy);
# Line 598 | Line 932 | public class JSR166TestCase extends Test
932              return perms.implies(p);
933          }
934          public void refresh() {}
935 +        public String toString() {
936 +            List<Permission> ps = new ArrayList<Permission>();
937 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
938 +                ps.add(e.nextElement());
939 +            return "AdjustablePolicy with permissions " + ps;
940 +        }
941      }
942  
943      /**
# Line 626 | Line 966 | public class JSR166TestCase extends Test
966      void sleep(long millis) {
967          try {
968              delay(millis);
969 <        } catch (InterruptedException ie) {
969 >        } catch (InterruptedException fail) {
970              AssertionFailedError afe =
971                  new AssertionFailedError("Unexpected InterruptedException");
972 <            afe.initCause(ie);
972 >            afe.initCause(fail);
973              throw afe;
974          }
975      }
976  
977      /**
978 <     * Sleeps until the timeout has elapsed, or interrupted.
639 <     * Does <em>NOT</em> throw InterruptedException.
640 <     */
641 <    void sleepTillInterrupted(long timeoutMillis) {
642 <        try {
643 <            Thread.sleep(timeoutMillis);
644 <        } catch (InterruptedException wakeup) {}
645 <    }
646 <
647 <    /**
648 <     * Waits up to the specified number of milliseconds for the given
978 >     * Spin-waits up to the specified number of milliseconds for the given
979       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
980       */
981      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
982 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
653 <        long t0 = System.nanoTime();
982 >        long startTime = System.nanoTime();
983          for (;;) {
984              Thread.State s = thread.getState();
985              if (s == Thread.State.BLOCKED ||
# Line 659 | Line 988 | public class JSR166TestCase extends Test
988                  return;
989              else if (s == Thread.State.TERMINATED)
990                  fail("Unexpected thread termination");
991 <            else if (System.nanoTime() - t0 > timeoutNanos) {
991 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
992                  threadAssertTrue(thread.isAlive());
993                  return;
994              }
# Line 678 | Line 1007 | public class JSR166TestCase extends Test
1007      /**
1008       * Returns the number of milliseconds since time given by
1009       * startNanoTime, which must have been previously returned from a
1010 <     * call to {@link System.nanoTime()}.
1010 >     * call to {@link System#nanoTime()}.
1011       */
1012 <    long millisElapsedSince(long startNanoTime) {
1012 >    static long millisElapsedSince(long startNanoTime) {
1013          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1014      }
1015  
1016 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1017 + //         long startTime = System.nanoTime();
1018 + //         try {
1019 + //             r.run();
1020 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1021 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1022 + //             throw new AssertionFailedError("did not return promptly");
1023 + //     }
1024 +
1025 + //     void assertTerminatesPromptly(Runnable r) {
1026 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1027 + //     }
1028 +
1029 +    /**
1030 +     * Checks that timed f.get() returns the expected value, and does not
1031 +     * wait for the timeout to elapse before returning.
1032 +     */
1033 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1034 +        long startTime = System.nanoTime();
1035 +        try {
1036 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1037 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1038 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1039 +            throw new AssertionFailedError("timed get did not return promptly");
1040 +    }
1041 +
1042 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1043 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1044 +    }
1045 +
1046      /**
1047       * Returns a new started daemon Thread running the given runnable.
1048       */
# Line 702 | Line 1061 | public class JSR166TestCase extends Test
1061      void awaitTermination(Thread t, long timeoutMillis) {
1062          try {
1063              t.join(timeoutMillis);
1064 <        } catch (InterruptedException ie) {
1065 <            threadUnexpectedException(ie);
1064 >        } catch (InterruptedException fail) {
1065 >            threadUnexpectedException(fail);
1066          } finally {
1067 <            if (t.isAlive()) {
1067 >            if (t.getState() != Thread.State.TERMINATED) {
1068                  t.interrupt();
1069                  fail("Test timed out");
1070              }
# Line 729 | Line 1088 | public class JSR166TestCase extends Test
1088          public final void run() {
1089              try {
1090                  realRun();
1091 <            } catch (Throwable t) {
1092 <                threadUnexpectedException(t);
1091 >            } catch (Throwable fail) {
1092 >                threadUnexpectedException(fail);
1093              }
1094          }
1095      }
# Line 783 | Line 1142 | public class JSR166TestCase extends Test
1142                  realRun();
1143                  threadShouldThrow("InterruptedException");
1144              } catch (InterruptedException success) {
1145 <            } catch (Throwable t) {
1146 <                threadUnexpectedException(t);
1145 >                threadAssertFalse(Thread.interrupted());
1146 >            } catch (Throwable fail) {
1147 >                threadUnexpectedException(fail);
1148              }
1149          }
1150      }
# Line 795 | Line 1155 | public class JSR166TestCase extends Test
1155          public final T call() {
1156              try {
1157                  return realCall();
1158 <            } catch (Throwable t) {
1159 <                threadUnexpectedException(t);
1158 >            } catch (Throwable fail) {
1159 >                threadUnexpectedException(fail);
1160                  return null;
1161              }
1162          }
# Line 812 | Line 1172 | public class JSR166TestCase extends Test
1172                  threadShouldThrow("InterruptedException");
1173                  return result;
1174              } catch (InterruptedException success) {
1175 <            } catch (Throwable t) {
1176 <                threadUnexpectedException(t);
1175 >                threadAssertFalse(Thread.interrupted());
1176 >            } catch (Throwable fail) {
1177 >                threadUnexpectedException(fail);
1178              }
1179              return null;
1180          }
# Line 853 | Line 1214 | public class JSR166TestCase extends Test
1214      public void await(CountDownLatch latch) {
1215          try {
1216              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1217 <        } catch (Throwable t) {
1218 <            threadUnexpectedException(t);
1217 >        } catch (Throwable fail) {
1218 >            threadUnexpectedException(fail);
1219 >        }
1220 >    }
1221 >
1222 >    public void await(Semaphore semaphore) {
1223 >        try {
1224 >            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1225 >        } catch (Throwable fail) {
1226 >            threadUnexpectedException(fail);
1227          }
1228      }
1229  
1230 + //     /**
1231 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1232 + //      */
1233 + //     public void await(AtomicBoolean flag) {
1234 + //         await(flag, LONG_DELAY_MS);
1235 + //     }
1236 +
1237 + //     /**
1238 + //      * Spin-waits up to the specified timeout until flag becomes true.
1239 + //      */
1240 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1241 + //         long startTime = System.nanoTime();
1242 + //         while (!flag.get()) {
1243 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1244 + //                 throw new AssertionFailedError("timed out");
1245 + //             Thread.yield();
1246 + //         }
1247 + //     }
1248 +
1249      public static class NPETask implements Callable<String> {
1250          public String call() { throw new NullPointerException(); }
1251      }
# Line 1026 | Line 1414 | public class JSR166TestCase extends Test
1414      public abstract class CheckedRecursiveAction extends RecursiveAction {
1415          protected abstract void realCompute() throws Throwable;
1416  
1417 <        public final void compute() {
1417 >        @Override protected final void compute() {
1418              try {
1419                  realCompute();
1420 <            } catch (Throwable t) {
1421 <                threadUnexpectedException(t);
1420 >            } catch (Throwable fail) {
1421 >                threadUnexpectedException(fail);
1422              }
1423          }
1424      }
# Line 1041 | Line 1429 | public class JSR166TestCase extends Test
1429      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1430          protected abstract T realCompute() throws Throwable;
1431  
1432 <        public final T compute() {
1432 >        @Override protected final T compute() {
1433              try {
1434                  return realCompute();
1435 <            } catch (Throwable t) {
1436 <                threadUnexpectedException(t);
1435 >            } catch (Throwable fail) {
1436 >                threadUnexpectedException(fail);
1437                  return null;
1438              }
1439          }
# Line 1060 | Line 1448 | public class JSR166TestCase extends Test
1448      }
1449  
1450      /**
1451 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1452 <     * of throwing checked exceptions.
1451 >     * A CyclicBarrier that uses timed await and fails with
1452 >     * AssertionFailedErrors instead of throwing checked exceptions.
1453       */
1454      public class CheckedBarrier extends CyclicBarrier {
1455          public CheckedBarrier(int parties) { super(parties); }
1456  
1457          public int await() {
1458              try {
1459 <                return super.await();
1460 <            } catch (Exception e) {
1459 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1460 >            } catch (TimeoutException timedOut) {
1461 >                throw new AssertionFailedError("timed out");
1462 >            } catch (Exception fail) {
1463                  AssertionFailedError afe =
1464 <                    new AssertionFailedError("Unexpected exception: " + e);
1465 <                afe.initCause(e);
1464 >                    new AssertionFailedError("Unexpected exception: " + fail);
1465 >                afe.initCause(fail);
1466                  throw afe;
1467              }
1468          }
1469      }
1470  
1471 <    public void checkEmpty(BlockingQueue q) {
1471 >    void checkEmpty(BlockingQueue q) {
1472          try {
1473              assertTrue(q.isEmpty());
1474              assertEquals(0, q.size());
# Line 1100 | Line 1490 | public class JSR166TestCase extends Test
1490                  q.remove();
1491                  shouldThrow();
1492              } catch (NoSuchElementException success) {}
1493 <        } catch (InterruptedException ie) {
1104 <            threadUnexpectedException(ie);
1105 <        }
1493 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1494      }
1495  
1496 <    @SuppressWarnings("unchecked")
1497 <    public <T> T serialClone(T o) {
1496 >    void assertSerialEquals(Object x, Object y) {
1497 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1498 >    }
1499 >
1500 >    void assertNotSerialEquals(Object x, Object y) {
1501 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1502 >    }
1503 >
1504 >    byte[] serialBytes(Object o) {
1505          try {
1506              ByteArrayOutputStream bos = new ByteArrayOutputStream();
1507              ObjectOutputStream oos = new ObjectOutputStream(bos);
1508              oos.writeObject(o);
1509              oos.flush();
1510              oos.close();
1511 <            ByteArrayInputStream bin =
1512 <                new ByteArrayInputStream(bos.toByteArray());
1513 <            ObjectInputStream ois = new ObjectInputStream(bin);
1514 <            return (T) ois.readObject();
1515 <        } catch (Throwable t) {
1516 <            threadUnexpectedException(t);
1511 >            return bos.toByteArray();
1512 >        } catch (Throwable fail) {
1513 >            threadUnexpectedException(fail);
1514 >            return new byte[0];
1515 >        }
1516 >    }
1517 >
1518 >    @SuppressWarnings("unchecked")
1519 >    <T> T serialClone(T o) {
1520 >        try {
1521 >            ObjectInputStream ois = new ObjectInputStream
1522 >                (new ByteArrayInputStream(serialBytes(o)));
1523 >            T clone = (T) ois.readObject();
1524 >            assertSame(o.getClass(), clone.getClass());
1525 >            return clone;
1526 >        } catch (Throwable fail) {
1527 >            threadUnexpectedException(fail);
1528              return null;
1529          }
1530      }
1531 +
1532 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1533 +                             Runnable... throwingActions) {
1534 +        for (Runnable throwingAction : throwingActions) {
1535 +            boolean threw = false;
1536 +            try { throwingAction.run(); }
1537 +            catch (Throwable t) {
1538 +                threw = true;
1539 +                if (!expectedExceptionClass.isInstance(t)) {
1540 +                    AssertionFailedError afe =
1541 +                        new AssertionFailedError
1542 +                        ("Expected " + expectedExceptionClass.getName() +
1543 +                         ", got " + t.getClass().getName());
1544 +                    afe.initCause(t);
1545 +                    threadUnexpectedException(afe);
1546 +                }
1547 +            }
1548 +            if (!threw)
1549 +                shouldThrow(expectedExceptionClass.getName());
1550 +        }
1551 +    }
1552 +
1553 +    public void assertIteratorExhausted(Iterator<?> it) {
1554 +        try {
1555 +            it.next();
1556 +            shouldThrow();
1557 +        } catch (NoSuchElementException success) {}
1558 +        assertFalse(it.hasNext());
1559 +    }
1560   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines