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.91 by jsr166, Thu Dec 8 18:54:46 2011 UTC vs.
Revision 1.134 by jsr166, Sun Jun 14 20:58:14 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.Date;
18 < import java.util.NoSuchElementException;
19 < import java.util.PropertyPermission;
20 < import java.util.concurrent.*;
19 < import java.util.concurrent.atomic.AtomicBoolean;
20 < import java.util.concurrent.atomic.AtomicReference;
21 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
22 < 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 27 | 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 69 | 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 109 | 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 122 | 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 =
138 <                (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) {
157 <            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          }
161        System.exit(0);
235      }
236  
237      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 174 | 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() { return JAVA_CLASS_VERSION >= 53.0; }
285 +
286      /**
287       * Collects all JSR166 unit tests as one suite.
288       */
289      public static Test suite() {
290 <        return newTestSuite(
290 >        // Java7+ test classes
291 >        TestSuite suite = newTestSuite(
292              ForkJoinPoolTest.suite(),
293              ForkJoinTaskTest.suite(),
294              RecursiveActionTest.suite(),
# Line 243 | Line 353 | public class JSR166TestCase extends Test
353              TreeSetTest.suite(),
354              TreeSubMapTest.suite(),
355              TreeSubSetTest.suite());
356 +
357 +        // Java8+ test classes
358 +        if (atLeastJava8()) {
359 +            String[] java8TestClassNames = {
360 +                "Atomic8Test",
361 +                "CompletableFutureTest",
362 +                "ConcurrentHashMap8Test",
363 +                "CountedCompleterTest",
364 +                "DoubleAccumulatorTest",
365 +                "DoubleAdderTest",
366 +                "ForkJoinPool8Test",
367 +                "ForkJoinTask8Test",
368 +                "LongAccumulatorTest",
369 +                "LongAdderTest",
370 +                "SplittableRandomTest",
371 +                "StampedLockTest",
372 +                "ThreadLocalRandom8Test",
373 +            };
374 +            addNamedTestClasses(suite, java8TestClassNames);
375 +        }
376 +
377 +        // Java9+ test classes
378 +        if (atLeastJava9()) {
379 +            String[] java9TestClassNames = {
380 +                "ThreadPoolExecutor9Test",
381 +            };
382 +            addNamedTestClasses(suite, java9TestClassNames);
383 +        }
384 +
385 +        return suite;
386      }
387  
388 +    /** Returns list of junit-style test method names in given class. */
389 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
390 +        Method[] methods = testClass.getDeclaredMethods();
391 +        ArrayList<String> names = new ArrayList<String>(methods.length);
392 +        for (Method method : methods) {
393 +            if (method.getName().startsWith("test")
394 +                && Modifier.isPublic(method.getModifiers())
395 +                // method.getParameterCount() requires jdk8+
396 +                && method.getParameterTypes().length == 0) {
397 +                names.add(method.getName());
398 +            }
399 +        }
400 +        return names;
401 +    }
402 +
403 +    /**
404 +     * Returns junit-style testSuite for the given test class, but
405 +     * parameterized by passing extra data to each test.
406 +     */
407 +    public static <ExtraData> Test parameterizedTestSuite
408 +        (Class<? extends JSR166TestCase> testClass,
409 +         Class<ExtraData> dataClass,
410 +         ExtraData data) {
411 +        try {
412 +            TestSuite suite = new TestSuite();
413 +            Constructor c =
414 +                testClass.getDeclaredConstructor(dataClass, String.class);
415 +            for (String methodName : testMethodNames(testClass))
416 +                suite.addTest((Test) c.newInstance(data, methodName));
417 +            return suite;
418 +        } catch (Exception e) {
419 +            throw new Error(e);
420 +        }
421 +    }
422 +
423 +    /**
424 +     * Returns junit-style testSuite for the jdk8 extension of the
425 +     * given test class, but parameterized by passing extra data to
426 +     * each test.  Uses reflection to allow compilation in jdk7.
427 +     */
428 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
429 +        (Class<? extends JSR166TestCase> testClass,
430 +         Class<ExtraData> dataClass,
431 +         ExtraData data) {
432 +        if (atLeastJava8()) {
433 +            String name = testClass.getName();
434 +            String name8 = name.replaceAll("Test$", "8Test");
435 +            if (name.equals(name8)) throw new Error(name);
436 +            try {
437 +                return (Test)
438 +                    Class.forName(name8)
439 +                    .getMethod("testSuite", new Class[] { dataClass })
440 +                    .invoke(null, data);
441 +            } catch (Exception e) {
442 +                throw new Error(e);
443 +            }
444 +        } else {
445 +            return new TestSuite();
446 +        }
447 +
448 +    }
449 +
450 +    // Delays for timing-dependent tests, in milliseconds.
451  
452      public static long SHORT_DELAY_MS;
453      public static long SMALL_DELAY_MS;
454      public static long MEDIUM_DELAY_MS;
455      public static long LONG_DELAY_MS;
456  
254
457      /**
458       * Returns the shortest timed delay. This could
459       * be reimplemented to use for example a Property.
# Line 334 | Line 536 | public class JSR166TestCase extends Test
536  
537          if (Thread.interrupted())
538              throw new AssertionFailedError("interrupt status set in main thread");
539 +
540 +        checkForkJoinPoolThreadLeaks();
541 +    }
542 +
543 +    /**
544 +     * Finds missing try { ... } finally { joinPool(e); }
545 +     */
546 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
547 +        Thread[] survivors = new Thread[5];
548 +        int count = Thread.enumerate(survivors);
549 +        for (int i = 0; i < count; i++) {
550 +            Thread thread = survivors[i];
551 +            String name = thread.getName();
552 +            if (name.startsWith("ForkJoinPool-")) {
553 +                // give thread some time to terminate
554 +                thread.join(LONG_DELAY_MS);
555 +                if (!thread.isAlive()) continue;
556 +                throw new AssertionFailedError
557 +                    (String.format("Found leaked ForkJoinPool thread test=%s thread=%s%n",
558 +                                   toString(), name));
559 +            }
560 +        }
561      }
562  
563      /**
# Line 414 | Line 638 | public class JSR166TestCase extends Test
638      public void threadAssertEquals(Object x, Object y) {
639          try {
640              assertEquals(x, y);
641 <        } catch (AssertionFailedError t) {
642 <            threadRecordFailure(t);
643 <            throw t;
644 <        } catch (Throwable t) {
645 <            threadUnexpectedException(t);
641 >        } catch (AssertionFailedError fail) {
642 >            threadRecordFailure(fail);
643 >            throw fail;
644 >        } catch (Throwable fail) {
645 >            threadUnexpectedException(fail);
646          }
647      }
648  
# Line 430 | Line 654 | public class JSR166TestCase extends Test
654      public void threadAssertSame(Object x, Object y) {
655          try {
656              assertSame(x, y);
657 <        } catch (AssertionFailedError t) {
658 <            threadRecordFailure(t);
659 <            throw t;
657 >        } catch (AssertionFailedError fail) {
658 >            threadRecordFailure(fail);
659 >            throw fail;
660          }
661      }
662  
# Line 497 | Line 721 | public class JSR166TestCase extends Test
721      void joinPool(ExecutorService exec) {
722          try {
723              exec.shutdown();
724 <            assertTrue("ExecutorService did not terminate in a timely manner",
725 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
724 >            if (!exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
725 >                fail("ExecutorService " + exec +
726 >                     " did not terminate in a timely manner");
727          } catch (SecurityException ok) {
728              // Allowed in case test doesn't have privs
729 <        } catch (InterruptedException ie) {
729 >        } catch (InterruptedException fail) {
730              fail("Unexpected InterruptedException");
731          }
732      }
733  
734      /**
735 +     * A debugging tool to print all stack traces, as jstack does.
736 +     */
737 +    static void printAllStackTraces() {
738 +        for (ThreadInfo info :
739 +                 ManagementFactory.getThreadMXBean()
740 +                 .dumpAllThreads(true, true))
741 +            System.err.print(info);
742 +    }
743 +
744 +    /**
745       * Checks that thread does not terminate within the default
746       * millisecond delay of {@code timeoutMillis()}.
747       */
# Line 522 | Line 757 | public class JSR166TestCase extends Test
757              // No need to optimize the failing case via Thread.join.
758              delay(millis);
759              assertTrue(thread.isAlive());
760 <        } catch (InterruptedException ie) {
760 >        } catch (InterruptedException fail) {
761              fail("Unexpected InterruptedException");
762          }
763      }
# Line 544 | Line 779 | public class JSR166TestCase extends Test
779              delay(millis);
780              for (Thread thread : threads)
781                  assertTrue(thread.isAlive());
782 <        } catch (InterruptedException ie) {
782 >        } catch (InterruptedException fail) {
783              fail("Unexpected InterruptedException");
784          }
785      }
# Line 566 | Line 801 | public class JSR166TestCase extends Test
801              future.get(timeoutMillis, MILLISECONDS);
802              shouldThrow();
803          } catch (TimeoutException success) {
804 <        } catch (Exception e) {
805 <            threadUnexpectedException(e);
804 >        } catch (Exception fail) {
805 >            threadUnexpectedException(fail);
806          } finally { future.cancel(true); }
807          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
808      }
# Line 611 | Line 846 | public class JSR166TestCase extends Test
846      public static final Integer m6  = new Integer(-6);
847      public static final Integer m10 = new Integer(-10);
848  
614
849      /**
850       * Runs Runnable r with a security policy that permits precisely
851       * the specified permissions.  If there is no current security
# Line 623 | Line 857 | public class JSR166TestCase extends Test
857          SecurityManager sm = System.getSecurityManager();
858          if (sm == null) {
859              r.run();
860 +        }
861 +        runWithSecurityManagerWithPermissions(r, permissions);
862 +    }
863 +
864 +    /**
865 +     * Runs Runnable r with a security policy that permits precisely
866 +     * the specified permissions.  If there is no current security
867 +     * manager, a temporary one is set for the duration of the
868 +     * Runnable.  We require that any security manager permit
869 +     * getPolicy/setPolicy.
870 +     */
871 +    public void runWithSecurityManagerWithPermissions(Runnable r,
872 +                                                      Permission... permissions) {
873 +        SecurityManager sm = System.getSecurityManager();
874 +        if (sm == null) {
875              Policy savedPolicy = Policy.getPolicy();
876              try {
877                  Policy.setPolicy(permissivePolicy());
878                  System.setSecurityManager(new SecurityManager());
879 <                runWithPermissions(r, permissions);
879 >                runWithSecurityManagerWithPermissions(r, permissions);
880              } finally {
881                  System.setSecurityManager(null);
882                  Policy.setPolicy(savedPolicy);
# Line 675 | Line 924 | public class JSR166TestCase extends Test
924              return perms.implies(p);
925          }
926          public void refresh() {}
927 +        public String toString() {
928 +            List<Permission> ps = new ArrayList<Permission>();
929 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
930 +                ps.add(e.nextElement());
931 +            return "AdjustablePolicy with permissions " + ps;
932 +        }
933      }
934  
935      /**
# Line 703 | Line 958 | public class JSR166TestCase extends Test
958      void sleep(long millis) {
959          try {
960              delay(millis);
961 <        } catch (InterruptedException ie) {
961 >        } catch (InterruptedException fail) {
962              AssertionFailedError afe =
963                  new AssertionFailedError("Unexpected InterruptedException");
964 <            afe.initCause(ie);
964 >            afe.initCause(fail);
965              throw afe;
966          }
967      }
# Line 744 | Line 999 | public class JSR166TestCase extends Test
999      /**
1000       * Returns the number of milliseconds since time given by
1001       * startNanoTime, which must have been previously returned from a
1002 <     * call to {@link System.nanoTime()}.
1002 >     * call to {@link System#nanoTime()}.
1003       */
1004 <    long millisElapsedSince(long startNanoTime) {
1004 >    static long millisElapsedSince(long startNanoTime) {
1005          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1006      }
1007  
1008 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1009 + //         long startTime = System.nanoTime();
1010 + //         try {
1011 + //             r.run();
1012 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1013 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1014 + //             throw new AssertionFailedError("did not return promptly");
1015 + //     }
1016 +
1017 + //     void assertTerminatesPromptly(Runnable r) {
1018 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1019 + //     }
1020 +
1021 +    /**
1022 +     * Checks that timed f.get() returns the expected value, and does not
1023 +     * wait for the timeout to elapse before returning.
1024 +     */
1025 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1026 +        long startTime = System.nanoTime();
1027 +        try {
1028 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1029 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1030 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1031 +            throw new AssertionFailedError("timed get did not return promptly");
1032 +    }
1033 +
1034 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1035 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1036 +    }
1037 +
1038      /**
1039       * Returns a new started daemon Thread running the given runnable.
1040       */
# Line 768 | Line 1053 | public class JSR166TestCase extends Test
1053      void awaitTermination(Thread t, long timeoutMillis) {
1054          try {
1055              t.join(timeoutMillis);
1056 <        } catch (InterruptedException ie) {
1057 <            threadUnexpectedException(ie);
1056 >        } catch (InterruptedException fail) {
1057 >            threadUnexpectedException(fail);
1058          } finally {
1059              if (t.getState() != Thread.State.TERMINATED) {
1060                  t.interrupt();
# Line 795 | Line 1080 | public class JSR166TestCase extends Test
1080          public final void run() {
1081              try {
1082                  realRun();
1083 <            } catch (Throwable t) {
1084 <                threadUnexpectedException(t);
1083 >            } catch (Throwable fail) {
1084 >                threadUnexpectedException(fail);
1085              }
1086          }
1087      }
# Line 850 | Line 1135 | public class JSR166TestCase extends Test
1135                  threadShouldThrow("InterruptedException");
1136              } catch (InterruptedException success) {
1137                  threadAssertFalse(Thread.interrupted());
1138 <            } catch (Throwable t) {
1139 <                threadUnexpectedException(t);
1138 >            } catch (Throwable fail) {
1139 >                threadUnexpectedException(fail);
1140              }
1141          }
1142      }
# Line 862 | Line 1147 | public class JSR166TestCase extends Test
1147          public final T call() {
1148              try {
1149                  return realCall();
1150 <            } catch (Throwable t) {
1151 <                threadUnexpectedException(t);
1150 >            } catch (Throwable fail) {
1151 >                threadUnexpectedException(fail);
1152                  return null;
1153              }
1154          }
# Line 880 | Line 1165 | public class JSR166TestCase extends Test
1165                  return result;
1166              } catch (InterruptedException success) {
1167                  threadAssertFalse(Thread.interrupted());
1168 <            } catch (Throwable t) {
1169 <                threadUnexpectedException(t);
1168 >            } catch (Throwable fail) {
1169 >                threadUnexpectedException(fail);
1170              }
1171              return null;
1172          }
# Line 921 | Line 1206 | public class JSR166TestCase extends Test
1206      public void await(CountDownLatch latch) {
1207          try {
1208              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1209 <        } catch (Throwable t) {
1210 <            threadUnexpectedException(t);
1209 >        } catch (Throwable fail) {
1210 >            threadUnexpectedException(fail);
1211          }
1212      }
1213  
1214      public void await(Semaphore semaphore) {
1215          try {
1216              assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1217 <        } catch (Throwable t) {
1218 <            threadUnexpectedException(t);
1217 >        } catch (Throwable fail) {
1218 >            threadUnexpectedException(fail);
1219          }
1220      }
1221  
# Line 1121 | Line 1406 | public class JSR166TestCase extends Test
1406      public abstract class CheckedRecursiveAction extends RecursiveAction {
1407          protected abstract void realCompute() throws Throwable;
1408  
1409 <        public final void compute() {
1409 >        @Override protected final void compute() {
1410              try {
1411                  realCompute();
1412 <            } catch (Throwable t) {
1413 <                threadUnexpectedException(t);
1412 >            } catch (Throwable fail) {
1413 >                threadUnexpectedException(fail);
1414              }
1415          }
1416      }
# Line 1136 | Line 1421 | public class JSR166TestCase extends Test
1421      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1422          protected abstract T realCompute() throws Throwable;
1423  
1424 <        public final T compute() {
1424 >        @Override protected final T compute() {
1425              try {
1426                  return realCompute();
1427 <            } catch (Throwable t) {
1428 <                threadUnexpectedException(t);
1427 >            } catch (Throwable fail) {
1428 >                threadUnexpectedException(fail);
1429                  return null;
1430              }
1431          }
# Line 1164 | Line 1449 | public class JSR166TestCase extends Test
1449          public int await() {
1450              try {
1451                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1452 <            } catch (TimeoutException e) {
1452 >            } catch (TimeoutException timedOut) {
1453                  throw new AssertionFailedError("timed out");
1454 <            } catch (Exception e) {
1454 >            } catch (Exception fail) {
1455                  AssertionFailedError afe =
1456 <                    new AssertionFailedError("Unexpected exception: " + e);
1457 <                afe.initCause(e);
1456 >                    new AssertionFailedError("Unexpected exception: " + fail);
1457 >                afe.initCause(fail);
1458                  throw afe;
1459              }
1460          }
# Line 1197 | Line 1482 | public class JSR166TestCase extends Test
1482                  q.remove();
1483                  shouldThrow();
1484              } catch (NoSuchElementException success) {}
1485 <        } catch (InterruptedException ie) {
1201 <            threadUnexpectedException(ie);
1202 <        }
1485 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1486      }
1487  
1488      void assertSerialEquals(Object x, Object y) {
# Line 1218 | Line 1501 | public class JSR166TestCase extends Test
1501              oos.flush();
1502              oos.close();
1503              return bos.toByteArray();
1504 <        } catch (Throwable t) {
1505 <            threadUnexpectedException(t);
1504 >        } catch (Throwable fail) {
1505 >            threadUnexpectedException(fail);
1506              return new byte[0];
1507          }
1508      }
# Line 1232 | Line 1515 | public class JSR166TestCase extends Test
1515              T clone = (T) ois.readObject();
1516              assertSame(o.getClass(), clone.getClass());
1517              return clone;
1518 <        } catch (Throwable t) {
1519 <            threadUnexpectedException(t);
1518 >        } catch (Throwable fail) {
1519 >            threadUnexpectedException(fail);
1520              return null;
1521          }
1522      }
1523 +
1524 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1525 +                             Runnable... throwingActions) {
1526 +        for (Runnable throwingAction : throwingActions) {
1527 +            boolean threw = false;
1528 +            try { throwingAction.run(); }
1529 +            catch (Throwable t) {
1530 +                threw = true;
1531 +                if (!expectedExceptionClass.isInstance(t)) {
1532 +                    AssertionFailedError afe =
1533 +                        new AssertionFailedError
1534 +                        ("Expected " + expectedExceptionClass.getName() +
1535 +                         ", got " + t.getClass().getName());
1536 +                    afe.initCause(t);
1537 +                    threadUnexpectedException(afe);
1538 +                }
1539 +            }
1540 +            if (!threw)
1541 +                shouldThrow(expectedExceptionClass.getName());
1542 +        }
1543 +    }
1544 +
1545 +    public void assertIteratorExhausted(Iterator<?> it) {
1546 +        try {
1547 +            it.next();
1548 +            shouldThrow();
1549 +        } catch (NoSuchElementException success) {}
1550 +        assertFalse(it.hasNext());
1551 +    }
1552   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines