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.104 by dl, Thu Mar 21 00:26:43 2013 UTC vs.
Revision 1.144 by jsr166, Mon Sep 14 03:14:01 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.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;
24 + 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.*;
37 < import java.util.concurrent.atomic.AtomicBoolean;
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.ExecutionException;
41 > import java.util.concurrent.Executors;
42 > import java.util.concurrent.ExecutorService;
43 > import java.util.concurrent.Future;
44 > import java.util.concurrent.RecursiveAction;
45 > import java.util.concurrent.RecursiveTask;
46 > import java.util.concurrent.RejectedExecutionHandler;
47 > import java.util.concurrent.Semaphore;
48 > import java.util.concurrent.ThreadFactory;
49 > import java.util.concurrent.ThreadPoolExecutor;
50 > import java.util.concurrent.TimeoutException;
51   import java.util.concurrent.atomic.AtomicReference;
52 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
53 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
54 < import java.security.CodeSource;
55 < import java.security.Permission;
56 < import java.security.PermissionCollection;
57 < import java.security.Permissions;
58 < import java.security.Policy;
34 < import java.security.ProtectionDomain;
35 < import java.security.SecurityPermission;
52 > import java.util.regex.Pattern;
53 >
54 > import junit.framework.AssertionFailedError;
55 > import junit.framework.Test;
56 > import junit.framework.TestCase;
57 > import junit.framework.TestResult;
58 > import junit.framework.TestSuite;
59  
60   /**
61   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 44 | Line 67 | import java.security.SecurityPermission;
67   *
68   * <ol>
69   *
70 < * <li> All assertions in code running in generated threads must use
70 > * <li>All assertions in code running in generated threads must use
71   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
72   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
73   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
74   * particularly recommended) for other code to use these forms too.
75   * Only the most typically used JUnit assertion methods are defined
76 < * this way, but enough to live with.</li>
76 > * this way, but enough to live with.
77   *
78 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
78 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
79   * to invoke {@code super.setUp} and {@code super.tearDown} within
80   * them. These methods are used to clear and check for thread
81 < * assertion failures.</li>
81 > * assertion failures.
82   *
83   * <li>All delays and timeouts must use one of the constants {@code
84   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 66 | Line 89 | import java.security.SecurityPermission;
89   * is always discriminable as larger than SHORT and smaller than
90   * MEDIUM.  And so on. These constants are set to conservative values,
91   * but even so, if there is ever any doubt, they can all be increased
92 < * in one spot to rerun tests on slower platforms.</li>
92 > * in one spot to rerun tests on slower platforms.
93   *
94 < * <li> All threads generated must be joined inside each test case
94 > * <li>All threads generated must be joined inside each test case
95   * method (or {@code fail} to do so) before returning from the
96   * method. The {@code joinPool} method can be used to do this when
97 < * using Executors.</li>
97 > * using Executors.
98   *
99   * </ol>
100   *
101   * <p><b>Other notes</b>
102   * <ul>
103   *
104 < * <li> Usually, there is one testcase method per JSR166 method
104 > * <li>Usually, there is one testcase method per JSR166 method
105   * covering "normal" operation, and then as many exception-testing
106   * methods as there are exceptions the method can throw. Sometimes
107   * there are multiple tests per JSR166 method when the different
108   * "normal" behaviors differ significantly. And sometimes testcases
109   * cover multiple methods when they cannot be tested in
110 < * isolation.</li>
110 > * isolation.
111   *
112 < * <li> The documentation style for testcases is to provide as javadoc
112 > * <li>The documentation style for testcases is to provide as javadoc
113   * a simple sentence or two describing the property that the testcase
114   * method purports to test. The javadocs do not say anything about how
115 < * the property is tested. To find out, read the code.</li>
115 > * the property is tested. To find out, read the code.
116   *
117 < * <li> These tests are "conformance tests", and do not attempt to
117 > * <li>These tests are "conformance tests", and do not attempt to
118   * test throughput, latency, scalability or other performance factors
119   * (see the separate "jtreg" tests for a set intended to check these
120   * for the most central aspects of functionality.) So, most tests use
121   * the smallest sensible numbers of threads, collection sizes, etc
122 < * needed to check basic conformance.</li>
122 > * needed to check basic conformance.
123   *
124   * <li>The test classes currently do not declare inclusion in
125   * any particular package to simplify things for people integrating
126 < * them in TCK test suites.</li>
126 > * them in TCK test suites.
127   *
128 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
129 < * runs all JSR166 unit tests.</li>
128 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
129 > * runs all JSR166 unit tests.
130   *
131   * </ul>
132   */
# Line 115 | Line 138 | public class JSR166TestCase extends Test
138          Boolean.getBoolean("jsr166.expensiveTests");
139  
140      /**
141 +     * If true, also run tests that are not part of the official tck
142 +     * because they test unspecified implementation details.
143 +     */
144 +    protected static final boolean testImplementationDetails =
145 +        Boolean.getBoolean("jsr166.testImplementationDetails");
146 +
147 +    /**
148       * If true, report on stdout all "slow" tests, that is, ones that
149       * take more than profileThreshold milliseconds to execute.
150       */
# Line 128 | Line 158 | public class JSR166TestCase extends Test
158      private static final long profileThreshold =
159          Long.getLong("jsr166.profileThreshold", 100);
160  
161 +    /**
162 +     * The number of repetitions per test (for tickling rare bugs).
163 +     */
164 +    private static final int runsPerTest =
165 +        Integer.getInteger("jsr166.runsPerTest", 1);
166 +
167 +    /**
168 +     * The number of repetitions of the test suite (for finding leaks?).
169 +     */
170 +    private static final int suiteRuns =
171 +        Integer.getInteger("jsr166.suiteRuns", 1);
172 +
173 +    public JSR166TestCase() { super(); }
174 +    public JSR166TestCase(String name) { super(name); }
175 +
176 +    /**
177 +     * A filter for tests to run, matching strings of the form
178 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
179 +     * Usefully combined with jsr166.runsPerTest.
180 +     */
181 +    private static final Pattern methodFilter = methodFilter();
182 +
183 +    private static Pattern methodFilter() {
184 +        String regex = System.getProperty("jsr166.methodFilter");
185 +        return (regex == null) ? null : Pattern.compile(regex);
186 +    }
187 +
188      protected void runTest() throws Throwable {
189 <        if (profileTests)
190 <            runTestProfiled();
191 <        else
192 <            super.runTest();
189 >        if (methodFilter == null
190 >            || methodFilter.matcher(toString()).find()) {
191 >            for (int i = 0; i < runsPerTest; i++) {
192 >                if (profileTests)
193 >                    runTestProfiled();
194 >                else
195 >                    super.runTest();
196 >            }
197 >        }
198      }
199  
200      protected void runTestProfiled() throws Throwable {
201 +        // Warmup run, notably to trigger all needed classloading.
202 +        super.runTest();
203          long t0 = System.nanoTime();
204          try {
205              super.runTest();
206          } finally {
207 <            long elapsedMillis =
144 <                (System.nanoTime() - t0) / (1000L * 1000L);
207 >            long elapsedMillis = millisElapsedSince(t0);
208              if (elapsedMillis >= profileThreshold)
209                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
210          }
# Line 149 | Line 212 | public class JSR166TestCase extends Test
212  
213      /**
214       * 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.
215       */
216      public static void main(String[] args) {
217 +        main(suite(), args);
218 +    }
219 +
220 +    /**
221 +     * Runs all unit tests in the given test suite.
222 +     * Actual behavior influenced by jsr166.* system properties.
223 +     */
224 +    static void main(Test suite, String[] args) {
225          if (useSecurityManager) {
226              System.err.println("Setting a permissive security manager");
227              Policy.setPolicy(permissivePolicy());
228              System.setSecurityManager(new SecurityManager());
229          }
230 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
231 <
232 <        Test s = suite();
233 <        for (int i = 0; i < iters; ++i) {
165 <            junit.textui.TestRunner.run(s);
230 >        for (int i = 0; i < suiteRuns; i++) {
231 >            TestResult result = junit.textui.TestRunner.run(suite);
232 >            if (!result.wasSuccessful())
233 >                System.exit(1);
234              System.gc();
235              System.runFinalization();
236          }
169        System.exit(0);
237      }
238  
239      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 197 | Line 264 | public class JSR166TestCase extends Test
264      }
265  
266      public static final double JAVA_CLASS_VERSION;
267 +    public static final String JAVA_SPECIFICATION_VERSION;
268      static {
269          try {
270              JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
271                  new java.security.PrivilegedAction<Double>() {
272                  public Double run() {
273                      return Double.valueOf(System.getProperty("java.class.version"));}});
274 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
275 +                new java.security.PrivilegedAction<String>() {
276 +                public String run() {
277 +                    return System.getProperty("java.specification.version");}});
278          } catch (Throwable t) {
279              throw new Error(t);
280          }
# Line 211 | Line 283 | public class JSR166TestCase extends Test
283      public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
284      public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
285      public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
286 +    public static boolean atLeastJava9() {
287 +        return JAVA_CLASS_VERSION >= 53.0
288 +            // As of 2015-09, java9 still uses 52.0 class file version
289 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
290 +    }
291 +    public static boolean atLeastJava10() {
292 +        return JAVA_CLASS_VERSION >= 54.0
293 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
294 +    }
295  
296      /**
297       * Collects all JSR166 unit tests as one suite.
# Line 286 | Line 367 | public class JSR166TestCase extends Test
367          // Java8+ test classes
368          if (atLeastJava8()) {
369              String[] java8TestClassNames = {
370 +                "Atomic8Test",
371                  "CompletableFutureTest",
372 +                "ConcurrentHashMap8Test",
373                  "CountedCompleterTest",
374                  "DoubleAccumulatorTest",
375                  "DoubleAdderTest",
376                  "ForkJoinPool8Test",
377 +                "ForkJoinTask8Test",
378                  "LongAccumulatorTest",
379                  "LongAdderTest",
380 +                "SplittableRandomTest",
381                  "StampedLockTest",
382 +                "SubmissionPublisherTest",
383 +                "ThreadLocalRandom8Test",
384              };
385              addNamedTestClasses(suite, java8TestClassNames);
386          }
387  
388 +        // Java9+ test classes
389 +        if (atLeastJava9()) {
390 +            String[] java9TestClassNames = {
391 +                // Currently empty, but expecting varhandle tests
392 +            };
393 +            addNamedTestClasses(suite, java9TestClassNames);
394 +        }
395 +
396          return suite;
397      }
398  
399 +    /** Returns list of junit-style test method names in given class. */
400 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
401 +        Method[] methods = testClass.getDeclaredMethods();
402 +        ArrayList<String> names = new ArrayList<String>(methods.length);
403 +        for (Method method : methods) {
404 +            if (method.getName().startsWith("test")
405 +                && Modifier.isPublic(method.getModifiers())
406 +                // method.getParameterCount() requires jdk8+
407 +                && method.getParameterTypes().length == 0) {
408 +                names.add(method.getName());
409 +            }
410 +        }
411 +        return names;
412 +    }
413 +
414 +    /**
415 +     * Returns junit-style testSuite for the given test class, but
416 +     * parameterized by passing extra data to each test.
417 +     */
418 +    public static <ExtraData> Test parameterizedTestSuite
419 +        (Class<? extends JSR166TestCase> testClass,
420 +         Class<ExtraData> dataClass,
421 +         ExtraData data) {
422 +        try {
423 +            TestSuite suite = new TestSuite();
424 +            Constructor c =
425 +                testClass.getDeclaredConstructor(dataClass, String.class);
426 +            for (String methodName : testMethodNames(testClass))
427 +                suite.addTest((Test) c.newInstance(data, methodName));
428 +            return suite;
429 +        } catch (Exception e) {
430 +            throw new Error(e);
431 +        }
432 +    }
433 +
434 +    /**
435 +     * Returns junit-style testSuite for the jdk8 extension of the
436 +     * given test class, but parameterized by passing extra data to
437 +     * each test.  Uses reflection to allow compilation in jdk7.
438 +     */
439 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
440 +        (Class<? extends JSR166TestCase> testClass,
441 +         Class<ExtraData> dataClass,
442 +         ExtraData data) {
443 +        if (atLeastJava8()) {
444 +            String name = testClass.getName();
445 +            String name8 = name.replaceAll("Test$", "8Test");
446 +            if (name.equals(name8)) throw new Error(name);
447 +            try {
448 +                return (Test)
449 +                    Class.forName(name8)
450 +                    .getMethod("testSuite", new Class[] { dataClass })
451 +                    .invoke(null, data);
452 +            } catch (Exception e) {
453 +                throw new Error(e);
454 +            }
455 +        } else {
456 +            return new TestSuite();
457 +        }
458 +
459 +    }
460 +
461 +    // Delays for timing-dependent tests, in milliseconds.
462  
463      public static long SHORT_DELAY_MS;
464      public static long SMALL_DELAY_MS;
465      public static long MEDIUM_DELAY_MS;
466      public static long LONG_DELAY_MS;
467  
310
468      /**
469       * Returns the shortest timed delay. This could
470       * be reimplemented to use for example a Property.
# Line 335 | Line 492 | public class JSR166TestCase extends Test
492      }
493  
494      /**
495 <     * Returns a new Date instance representing a time delayMillis
496 <     * milliseconds in the future.
495 >     * Returns a new Date instance representing a time at least
496 >     * delayMillis milliseconds in the future.
497       */
498      Date delayedDate(long delayMillis) {
499 <        return new Date(System.currentTimeMillis() + delayMillis);
499 >        // Add 1 because currentTimeMillis is known to round into the past.
500 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
501      }
502  
503      /**
# Line 395 | Line 553 | public class JSR166TestCase extends Test
553      }
554  
555      /**
556 <     * Find missing try { ... } finally { joinPool(e); }
556 >     * Finds missing try { ... } finally { joinPool(e); }
557       */
558      void checkForkJoinPoolThreadLeaks() throws InterruptedException {
559          Thread[] survivors = new Thread[5];
# Line 407 | Line 565 | public class JSR166TestCase extends Test
565                  // give thread some time to terminate
566                  thread.join(LONG_DELAY_MS);
567                  if (!thread.isAlive()) continue;
410                thread.stop();
568                  throw new AssertionFailedError
569                      (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
570                                     toString(), name));
# Line 493 | Line 650 | public class JSR166TestCase extends Test
650      public void threadAssertEquals(Object x, Object y) {
651          try {
652              assertEquals(x, y);
653 <        } catch (AssertionFailedError t) {
654 <            threadRecordFailure(t);
655 <            throw t;
656 <        } catch (Throwable t) {
657 <            threadUnexpectedException(t);
653 >        } catch (AssertionFailedError fail) {
654 >            threadRecordFailure(fail);
655 >            throw fail;
656 >        } catch (Throwable fail) {
657 >            threadUnexpectedException(fail);
658          }
659      }
660  
# Line 509 | Line 666 | public class JSR166TestCase extends Test
666      public void threadAssertSame(Object x, Object y) {
667          try {
668              assertSame(x, y);
669 <        } catch (AssertionFailedError t) {
670 <            threadRecordFailure(t);
671 <            throw t;
669 >        } catch (AssertionFailedError fail) {
670 >            threadRecordFailure(fail);
671 >            throw fail;
672          }
673      }
674  
# Line 573 | Line 730 | public class JSR166TestCase extends Test
730      /**
731       * Waits out termination of a thread pool or fails doing so.
732       */
733 <    void joinPool(ExecutorService exec) {
733 >    void joinPool(ExecutorService pool) {
734          try {
735 <            exec.shutdown();
736 <            assertTrue("ExecutorService did not terminate in a timely manner",
737 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
735 >            pool.shutdown();
736 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
737 >                fail("ExecutorService " + pool +
738 >                     " did not terminate in a timely manner");
739          } catch (SecurityException ok) {
740              // Allowed in case test doesn't have privs
741 <        } catch (InterruptedException ie) {
741 >        } catch (InterruptedException fail) {
742              fail("Unexpected InterruptedException");
743          }
744      }
745  
746 +    /** Like Runnable, but with the freedom to throw anything */
747 +    interface Action { public void run() throws Throwable; }
748 +
749 +    /**
750 +     * Runs all the given actions in parallel, failing if any fail.
751 +     * Useful for running multiple variants of tests that are
752 +     * necessarily individually slow because they must block.
753 +     */
754 +    void testInParallel(Action ... actions) {
755 +        ExecutorService pool = Executors.newCachedThreadPool();
756 +        try {
757 +            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
758 +            for (final Action action : actions)
759 +                futures.add(pool.submit(new CheckedRunnable() {
760 +                    public void realRun() throws Throwable { action.run();}}));
761 +            for (Future<?> future : futures)
762 +                try {
763 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
764 +                } catch (ExecutionException ex) {
765 +                    threadUnexpectedException(ex.getCause());
766 +                } catch (Exception ex) {
767 +                    threadUnexpectedException(ex);
768 +                }
769 +        } finally {
770 +            joinPool(pool);
771 +        }
772 +    }
773 +
774      /**
775       * A debugging tool to print all stack traces, as jstack does.
776       */
# Line 611 | Line 797 | public class JSR166TestCase extends Test
797              // No need to optimize the failing case via Thread.join.
798              delay(millis);
799              assertTrue(thread.isAlive());
800 <        } catch (InterruptedException ie) {
800 >        } catch (InterruptedException fail) {
801              fail("Unexpected InterruptedException");
802          }
803      }
# Line 633 | Line 819 | public class JSR166TestCase extends Test
819              delay(millis);
820              for (Thread thread : threads)
821                  assertTrue(thread.isAlive());
822 <        } catch (InterruptedException ie) {
822 >        } catch (InterruptedException fail) {
823              fail("Unexpected InterruptedException");
824          }
825      }
# Line 655 | Line 841 | public class JSR166TestCase extends Test
841              future.get(timeoutMillis, MILLISECONDS);
842              shouldThrow();
843          } catch (TimeoutException success) {
844 <        } catch (Exception e) {
845 <            threadUnexpectedException(e);
844 >        } catch (Exception fail) {
845 >            threadUnexpectedException(fail);
846          } finally { future.cancel(true); }
847          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
848      }
# Line 700 | Line 886 | public class JSR166TestCase extends Test
886      public static final Integer m6  = new Integer(-6);
887      public static final Integer m10 = new Integer(-10);
888  
703
889      /**
890       * Runs Runnable r with a security policy that permits precisely
891       * the specified permissions.  If there is no current security
# Line 813 | Line 998 | public class JSR166TestCase extends Test
998      void sleep(long millis) {
999          try {
1000              delay(millis);
1001 <        } catch (InterruptedException ie) {
1001 >        } catch (InterruptedException fail) {
1002              AssertionFailedError afe =
1003                  new AssertionFailedError("Unexpected InterruptedException");
1004 <            afe.initCause(ie);
1004 >            afe.initCause(fail);
1005              throw afe;
1006          }
1007      }
# Line 854 | Line 1039 | public class JSR166TestCase extends Test
1039      /**
1040       * Returns the number of milliseconds since time given by
1041       * startNanoTime, which must have been previously returned from a
1042 <     * call to {@link System.nanoTime()}.
1042 >     * call to {@link System#nanoTime()}.
1043       */
1044 <    long millisElapsedSince(long startNanoTime) {
1044 >    static long millisElapsedSince(long startNanoTime) {
1045          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1046      }
1047  
1048 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1049 + //         long startTime = System.nanoTime();
1050 + //         try {
1051 + //             r.run();
1052 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1053 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1054 + //             throw new AssertionFailedError("did not return promptly");
1055 + //     }
1056 +
1057 + //     void assertTerminatesPromptly(Runnable r) {
1058 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1059 + //     }
1060 +
1061 +    /**
1062 +     * Checks that timed f.get() returns the expected value, and does not
1063 +     * wait for the timeout to elapse before returning.
1064 +     */
1065 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1066 +        long startTime = System.nanoTime();
1067 +        try {
1068 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1069 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1070 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1071 +            throw new AssertionFailedError("timed get did not return promptly");
1072 +    }
1073 +
1074 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1075 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1076 +    }
1077 +
1078      /**
1079       * Returns a new started daemon Thread running the given runnable.
1080       */
# Line 878 | Line 1093 | public class JSR166TestCase extends Test
1093      void awaitTermination(Thread t, long timeoutMillis) {
1094          try {
1095              t.join(timeoutMillis);
1096 <        } catch (InterruptedException ie) {
1097 <            threadUnexpectedException(ie);
1096 >        } catch (InterruptedException fail) {
1097 >            threadUnexpectedException(fail);
1098          } finally {
1099              if (t.getState() != Thread.State.TERMINATED) {
1100                  t.interrupt();
# Line 905 | Line 1120 | public class JSR166TestCase extends Test
1120          public final void run() {
1121              try {
1122                  realRun();
1123 <            } catch (Throwable t) {
1124 <                threadUnexpectedException(t);
1123 >            } catch (Throwable fail) {
1124 >                threadUnexpectedException(fail);
1125              }
1126          }
1127      }
# Line 960 | Line 1175 | public class JSR166TestCase extends Test
1175                  threadShouldThrow("InterruptedException");
1176              } catch (InterruptedException success) {
1177                  threadAssertFalse(Thread.interrupted());
1178 <            } catch (Throwable t) {
1179 <                threadUnexpectedException(t);
1178 >            } catch (Throwable fail) {
1179 >                threadUnexpectedException(fail);
1180              }
1181          }
1182      }
# Line 972 | Line 1187 | public class JSR166TestCase extends Test
1187          public final T call() {
1188              try {
1189                  return realCall();
1190 <            } catch (Throwable t) {
1191 <                threadUnexpectedException(t);
1190 >            } catch (Throwable fail) {
1191 >                threadUnexpectedException(fail);
1192                  return null;
1193              }
1194          }
# Line 990 | Line 1205 | public class JSR166TestCase extends Test
1205                  return result;
1206              } catch (InterruptedException success) {
1207                  threadAssertFalse(Thread.interrupted());
1208 <            } catch (Throwable t) {
1209 <                threadUnexpectedException(t);
1208 >            } catch (Throwable fail) {
1209 >                threadUnexpectedException(fail);
1210              }
1211              return null;
1212          }
# Line 1008 | Line 1223 | public class JSR166TestCase extends Test
1223      public static final String TEST_STRING = "a test string";
1224  
1225      public static class StringTask implements Callable<String> {
1226 <        public String call() { return TEST_STRING; }
1226 >        final String value;
1227 >        public StringTask() { this(TEST_STRING); }
1228 >        public StringTask(String value) { this.value = value; }
1229 >        public String call() { return value; }
1230      }
1231  
1232      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 1031 | Line 1249 | public class JSR166TestCase extends Test
1249      public void await(CountDownLatch latch) {
1250          try {
1251              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1252 <        } catch (Throwable t) {
1253 <            threadUnexpectedException(t);
1252 >        } catch (Throwable fail) {
1253 >            threadUnexpectedException(fail);
1254          }
1255      }
1256  
1257      public void await(Semaphore semaphore) {
1258          try {
1259              assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1260 <        } catch (Throwable t) {
1261 <            threadUnexpectedException(t);
1260 >        } catch (Throwable fail) {
1261 >            threadUnexpectedException(fail);
1262          }
1263      }
1264  
# Line 1231 | Line 1449 | public class JSR166TestCase extends Test
1449      public abstract class CheckedRecursiveAction extends RecursiveAction {
1450          protected abstract void realCompute() throws Throwable;
1451  
1452 <        public final void compute() {
1452 >        @Override protected final void compute() {
1453              try {
1454                  realCompute();
1455 <            } catch (Throwable t) {
1456 <                threadUnexpectedException(t);
1455 >            } catch (Throwable fail) {
1456 >                threadUnexpectedException(fail);
1457              }
1458          }
1459      }
# Line 1246 | Line 1464 | public class JSR166TestCase extends Test
1464      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1465          protected abstract T realCompute() throws Throwable;
1466  
1467 <        public final T compute() {
1467 >        @Override protected final T compute() {
1468              try {
1469                  return realCompute();
1470 <            } catch (Throwable t) {
1471 <                threadUnexpectedException(t);
1470 >            } catch (Throwable fail) {
1471 >                threadUnexpectedException(fail);
1472                  return null;
1473              }
1474          }
# Line 1274 | Line 1492 | public class JSR166TestCase extends Test
1492          public int await() {
1493              try {
1494                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1495 <            } catch (TimeoutException e) {
1495 >            } catch (TimeoutException timedOut) {
1496                  throw new AssertionFailedError("timed out");
1497 <            } catch (Exception e) {
1497 >            } catch (Exception fail) {
1498                  AssertionFailedError afe =
1499 <                    new AssertionFailedError("Unexpected exception: " + e);
1500 <                afe.initCause(e);
1499 >                    new AssertionFailedError("Unexpected exception: " + fail);
1500 >                afe.initCause(fail);
1501                  throw afe;
1502              }
1503          }
# Line 1307 | Line 1525 | public class JSR166TestCase extends Test
1525                  q.remove();
1526                  shouldThrow();
1527              } catch (NoSuchElementException success) {}
1528 <        } catch (InterruptedException ie) {
1311 <            threadUnexpectedException(ie);
1312 <        }
1528 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1529      }
1530  
1531      void assertSerialEquals(Object x, Object y) {
# Line 1328 | Line 1544 | public class JSR166TestCase extends Test
1544              oos.flush();
1545              oos.close();
1546              return bos.toByteArray();
1547 <        } catch (Throwable t) {
1548 <            threadUnexpectedException(t);
1547 >        } catch (Throwable fail) {
1548 >            threadUnexpectedException(fail);
1549              return new byte[0];
1550          }
1551      }
# Line 1342 | Line 1558 | public class JSR166TestCase extends Test
1558              T clone = (T) ois.readObject();
1559              assertSame(o.getClass(), clone.getClass());
1560              return clone;
1561 <        } catch (Throwable t) {
1562 <            threadUnexpectedException(t);
1561 >        } catch (Throwable fail) {
1562 >            threadUnexpectedException(fail);
1563              return null;
1564          }
1565      }
1566 +
1567 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1568 +                             Runnable... throwingActions) {
1569 +        for (Runnable throwingAction : throwingActions) {
1570 +            boolean threw = false;
1571 +            try { throwingAction.run(); }
1572 +            catch (Throwable t) {
1573 +                threw = true;
1574 +                if (!expectedExceptionClass.isInstance(t)) {
1575 +                    AssertionFailedError afe =
1576 +                        new AssertionFailedError
1577 +                        ("Expected " + expectedExceptionClass.getName() +
1578 +                         ", got " + t.getClass().getName());
1579 +                    afe.initCause(t);
1580 +                    threadUnexpectedException(afe);
1581 +                }
1582 +            }
1583 +            if (!threw)
1584 +                shouldThrow(expectedExceptionClass.getName());
1585 +        }
1586 +    }
1587 +
1588 +    public void assertIteratorExhausted(Iterator<?> it) {
1589 +        try {
1590 +            it.next();
1591 +            shouldThrow();
1592 +        } catch (NoSuchElementException success) {}
1593 +        assertFalse(it.hasNext());
1594 +    }
1595   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines