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.93 by jsr166, Sun Dec 16 17:22:42 2012 UTC vs.
Revision 1.146 by jsr166, Fri Sep 25 23:32:15 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.ForkJoinPool;
44 > import java.util.concurrent.Future;
45 > import java.util.concurrent.RecursiveAction;
46 > import java.util.concurrent.RecursiveTask;
47 > import java.util.concurrent.RejectedExecutionHandler;
48 > import java.util.concurrent.Semaphore;
49 > import java.util.concurrent.ThreadFactory;
50 > import java.util.concurrent.ThreadPoolExecutor;
51 > import java.util.concurrent.TimeoutException;
52   import java.util.concurrent.atomic.AtomicReference;
53 < import static java.util.concurrent.TimeUnit.MILLISECONDS;
54 < import static java.util.concurrent.TimeUnit.NANOSECONDS;
55 < import java.security.CodeSource;
56 < import java.security.Permission;
57 < import java.security.PermissionCollection;
58 < import java.security.Permissions;
59 < import java.security.Policy;
31 < import java.security.ProtectionDomain;
32 < import java.security.SecurityPermission;
53 > import java.util.regex.Pattern;
54 >
55 > import junit.framework.AssertionFailedError;
56 > import junit.framework.Test;
57 > import junit.framework.TestCase;
58 > import junit.framework.TestResult;
59 > import junit.framework.TestSuite;
60  
61   /**
62   * Base class for JSR166 Junit TCK tests.  Defines some constants,
# Line 41 | Line 68 | import java.security.SecurityPermission;
68   *
69   * <ol>
70   *
71 < * <li> All assertions in code running in generated threads must use
71 > * <li>All assertions in code running in generated threads must use
72   * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
73   * #threadAssertEquals}, or {@link #threadAssertNull}, (not
74   * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
75   * particularly recommended) for other code to use these forms too.
76   * Only the most typically used JUnit assertion methods are defined
77 < * this way, but enough to live with.</li>
77 > * this way, but enough to live with.
78   *
79 < * <li> If you override {@link #setUp} or {@link #tearDown}, make sure
79 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
80   * to invoke {@code super.setUp} and {@code super.tearDown} within
81   * them. These methods are used to clear and check for thread
82 < * assertion failures.</li>
82 > * assertion failures.
83   *
84   * <li>All delays and timeouts must use one of the constants {@code
85   * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
# Line 63 | Line 90 | import java.security.SecurityPermission;
90   * is always discriminable as larger than SHORT and smaller than
91   * MEDIUM.  And so on. These constants are set to conservative values,
92   * but even so, if there is ever any doubt, they can all be increased
93 < * in one spot to rerun tests on slower platforms.</li>
93 > * in one spot to rerun tests on slower platforms.
94   *
95 < * <li> All threads generated must be joined inside each test case
95 > * <li>All threads generated must be joined inside each test case
96   * method (or {@code fail} to do so) before returning from the
97   * method. The {@code joinPool} method can be used to do this when
98 < * using Executors.</li>
98 > * using Executors.
99   *
100   * </ol>
101   *
102   * <p><b>Other notes</b>
103   * <ul>
104   *
105 < * <li> Usually, there is one testcase method per JSR166 method
105 > * <li>Usually, there is one testcase method per JSR166 method
106   * covering "normal" operation, and then as many exception-testing
107   * methods as there are exceptions the method can throw. Sometimes
108   * there are multiple tests per JSR166 method when the different
109   * "normal" behaviors differ significantly. And sometimes testcases
110   * cover multiple methods when they cannot be tested in
111 < * isolation.</li>
111 > * isolation.
112   *
113 < * <li> The documentation style for testcases is to provide as javadoc
113 > * <li>The documentation style for testcases is to provide as javadoc
114   * a simple sentence or two describing the property that the testcase
115   * method purports to test. The javadocs do not say anything about how
116 < * the property is tested. To find out, read the code.</li>
116 > * the property is tested. To find out, read the code.
117   *
118 < * <li> These tests are "conformance tests", and do not attempt to
118 > * <li>These tests are "conformance tests", and do not attempt to
119   * test throughput, latency, scalability or other performance factors
120   * (see the separate "jtreg" tests for a set intended to check these
121   * for the most central aspects of functionality.) So, most tests use
122   * the smallest sensible numbers of threads, collection sizes, etc
123 < * needed to check basic conformance.</li>
123 > * needed to check basic conformance.
124   *
125   * <li>The test classes currently do not declare inclusion in
126   * any particular package to simplify things for people integrating
127 < * them in TCK test suites.</li>
127 > * them in TCK test suites.
128   *
129 < * <li> As a convenience, the {@code main} of this class (JSR166TestCase)
130 < * runs all JSR166 unit tests.</li>
129 > * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
130 > * runs all JSR166 unit tests.
131   *
132   * </ul>
133   */
# Line 112 | Line 139 | public class JSR166TestCase extends Test
139          Boolean.getBoolean("jsr166.expensiveTests");
140  
141      /**
142 +     * If true, also run tests that are not part of the official tck
143 +     * because they test unspecified implementation details.
144 +     */
145 +    protected static final boolean testImplementationDetails =
146 +        Boolean.getBoolean("jsr166.testImplementationDetails");
147 +
148 +    /**
149       * If true, report on stdout all "slow" tests, that is, ones that
150       * take more than profileThreshold milliseconds to execute.
151       */
# Line 125 | Line 159 | public class JSR166TestCase extends Test
159      private static final long profileThreshold =
160          Long.getLong("jsr166.profileThreshold", 100);
161  
162 +    /**
163 +     * The number of repetitions per test (for tickling rare bugs).
164 +     */
165 +    private static final int runsPerTest =
166 +        Integer.getInteger("jsr166.runsPerTest", 1);
167 +
168 +    /**
169 +     * The number of repetitions of the test suite (for finding leaks?).
170 +     */
171 +    private static final int suiteRuns =
172 +        Integer.getInteger("jsr166.suiteRuns", 1);
173 +
174 +    public JSR166TestCase() { super(); }
175 +    public JSR166TestCase(String name) { super(name); }
176 +
177 +    /**
178 +     * A filter for tests to run, matching strings of the form
179 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
180 +     * Usefully combined with jsr166.runsPerTest.
181 +     */
182 +    private static final Pattern methodFilter = methodFilter();
183 +
184 +    private static Pattern methodFilter() {
185 +        String regex = System.getProperty("jsr166.methodFilter");
186 +        return (regex == null) ? null : Pattern.compile(regex);
187 +    }
188 +
189      protected void runTest() throws Throwable {
190 <        if (profileTests)
191 <            runTestProfiled();
192 <        else
193 <            super.runTest();
190 >        if (methodFilter == null
191 >            || methodFilter.matcher(toString()).find()) {
192 >            for (int i = 0; i < runsPerTest; i++) {
193 >                if (profileTests)
194 >                    runTestProfiled();
195 >                else
196 >                    super.runTest();
197 >            }
198 >        }
199      }
200  
201      protected void runTestProfiled() throws Throwable {
202 <        long t0 = System.nanoTime();
203 <        try {
202 >        for (int i = 0; i < 2; i++) {
203 >            long startTime = System.nanoTime();
204              super.runTest();
205 <        } finally {
206 <            long elapsedMillis =
207 <                (System.nanoTime() - t0) / (1000L * 1000L);
208 <            if (elapsedMillis >= profileThreshold)
205 >            long elapsedMillis = millisElapsedSince(startTime);
206 >            if (elapsedMillis < profileThreshold)
207 >                break;
208 >            // Never report first run of any test; treat it as a
209 >            // warmup run, notably to trigger all needed classloading,
210 >            if (i > 0)
211                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
212          }
213      }
214  
215      /**
216 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
216 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
217       */
218      public static void main(String[] args) {
219 +        main(suite(), args);
220 +    }
221 +
222 +    /**
223 +     * Runs all unit tests in the given test suite.
224 +     * Actual behavior influenced by jsr166.* system properties.
225 +     */
226 +    static void main(Test suite, String[] args) {
227          if (useSecurityManager) {
228              System.err.println("Setting a permissive security manager");
229              Policy.setPolicy(permissivePolicy());
230              System.setSecurityManager(new SecurityManager());
231          }
232 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
233 <
234 <        Test s = suite();
235 <        for (int i = 0; i < iters; ++i) {
160 <            junit.textui.TestRunner.run(s);
232 >        for (int i = 0; i < suiteRuns; i++) {
233 >            TestResult result = junit.textui.TestRunner.run(suite);
234 >            if (!result.wasSuccessful())
235 >                System.exit(1);
236              System.gc();
237              System.runFinalization();
238          }
164        System.exit(0);
239      }
240  
241      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 177 | Line 251 | public class JSR166TestCase extends Test
251          return suite;
252      }
253  
254 +    public static void addNamedTestClasses(TestSuite suite,
255 +                                           String... testClassNames) {
256 +        for (String testClassName : testClassNames) {
257 +            try {
258 +                Class<?> testClass = Class.forName(testClassName);
259 +                Method m = testClass.getDeclaredMethod("suite",
260 +                                                       new Class<?>[0]);
261 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
262 +            } catch (Exception e) {
263 +                throw new Error("Missing test class", e);
264 +            }
265 +        }
266 +    }
267 +
268 +    public static final double JAVA_CLASS_VERSION;
269 +    public static final String JAVA_SPECIFICATION_VERSION;
270 +    static {
271 +        try {
272 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
273 +                new java.security.PrivilegedAction<Double>() {
274 +                public Double run() {
275 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
276 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
277 +                new java.security.PrivilegedAction<String>() {
278 +                public String run() {
279 +                    return System.getProperty("java.specification.version");}});
280 +        } catch (Throwable t) {
281 +            throw new Error(t);
282 +        }
283 +    }
284 +
285 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
286 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
287 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
288 +    public static boolean atLeastJava9() {
289 +        return JAVA_CLASS_VERSION >= 53.0
290 +            // As of 2015-09, java9 still uses 52.0 class file version
291 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
292 +    }
293 +    public static boolean atLeastJava10() {
294 +        return JAVA_CLASS_VERSION >= 54.0
295 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
296 +    }
297 +
298      /**
299       * Collects all JSR166 unit tests as one suite.
300       */
301      public static Test suite() {
302 <        return newTestSuite(
302 >        // Java7+ test classes
303 >        TestSuite suite = newTestSuite(
304              ForkJoinPoolTest.suite(),
305              ForkJoinTaskTest.suite(),
306              RecursiveActionTest.suite(),
# Line 246 | Line 365 | public class JSR166TestCase extends Test
365              TreeSetTest.suite(),
366              TreeSubMapTest.suite(),
367              TreeSubSetTest.suite());
368 +
369 +        // Java8+ test classes
370 +        if (atLeastJava8()) {
371 +            String[] java8TestClassNames = {
372 +                "Atomic8Test",
373 +                "CompletableFutureTest",
374 +                "ConcurrentHashMap8Test",
375 +                "CountedCompleterTest",
376 +                "DoubleAccumulatorTest",
377 +                "DoubleAdderTest",
378 +                "ForkJoinPool8Test",
379 +                "ForkJoinTask8Test",
380 +                "LongAccumulatorTest",
381 +                "LongAdderTest",
382 +                "SplittableRandomTest",
383 +                "StampedLockTest",
384 +                "SubmissionPublisherTest",
385 +                "ThreadLocalRandom8Test",
386 +            };
387 +            addNamedTestClasses(suite, java8TestClassNames);
388 +        }
389 +
390 +        // Java9+ test classes
391 +        if (atLeastJava9()) {
392 +            String[] java9TestClassNames = {
393 +                // Currently empty, but expecting varhandle tests
394 +            };
395 +            addNamedTestClasses(suite, java9TestClassNames);
396 +        }
397 +
398 +        return suite;
399 +    }
400 +
401 +    /** Returns list of junit-style test method names in given class. */
402 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
403 +        Method[] methods = testClass.getDeclaredMethods();
404 +        ArrayList<String> names = new ArrayList<String>(methods.length);
405 +        for (Method method : methods) {
406 +            if (method.getName().startsWith("test")
407 +                && Modifier.isPublic(method.getModifiers())
408 +                // method.getParameterCount() requires jdk8+
409 +                && method.getParameterTypes().length == 0) {
410 +                names.add(method.getName());
411 +            }
412 +        }
413 +        return names;
414 +    }
415 +
416 +    /**
417 +     * Returns junit-style testSuite for the given test class, but
418 +     * parameterized by passing extra data to each test.
419 +     */
420 +    public static <ExtraData> Test parameterizedTestSuite
421 +        (Class<? extends JSR166TestCase> testClass,
422 +         Class<ExtraData> dataClass,
423 +         ExtraData data) {
424 +        try {
425 +            TestSuite suite = new TestSuite();
426 +            Constructor c =
427 +                testClass.getDeclaredConstructor(dataClass, String.class);
428 +            for (String methodName : testMethodNames(testClass))
429 +                suite.addTest((Test) c.newInstance(data, methodName));
430 +            return suite;
431 +        } catch (Exception e) {
432 +            throw new Error(e);
433 +        }
434      }
435  
436 +    /**
437 +     * Returns junit-style testSuite for the jdk8 extension of the
438 +     * given test class, but parameterized by passing extra data to
439 +     * each test.  Uses reflection to allow compilation in jdk7.
440 +     */
441 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
442 +        (Class<? extends JSR166TestCase> testClass,
443 +         Class<ExtraData> dataClass,
444 +         ExtraData data) {
445 +        if (atLeastJava8()) {
446 +            String name = testClass.getName();
447 +            String name8 = name.replaceAll("Test$", "8Test");
448 +            if (name.equals(name8)) throw new Error(name);
449 +            try {
450 +                return (Test)
451 +                    Class.forName(name8)
452 +                    .getMethod("testSuite", new Class[] { dataClass })
453 +                    .invoke(null, data);
454 +            } catch (Exception e) {
455 +                throw new Error(e);
456 +            }
457 +        } else {
458 +            return new TestSuite();
459 +        }
460 +
461 +    }
462 +
463 +    // Delays for timing-dependent tests, in milliseconds.
464  
465      public static long SHORT_DELAY_MS;
466      public static long SMALL_DELAY_MS;
467      public static long MEDIUM_DELAY_MS;
468      public static long LONG_DELAY_MS;
469  
257
470      /**
471       * Returns the shortest timed delay. This could
472       * be reimplemented to use for example a Property.
# Line 282 | Line 494 | public class JSR166TestCase extends Test
494      }
495  
496      /**
497 <     * Returns a new Date instance representing a time delayMillis
498 <     * milliseconds in the future.
497 >     * Returns a new Date instance representing a time at least
498 >     * delayMillis milliseconds in the future.
499       */
500      Date delayedDate(long delayMillis) {
501 <        return new Date(System.currentTimeMillis() + delayMillis);
501 >        // Add 1 because currentTimeMillis is known to round into the past.
502 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
503      }
504  
505      /**
# Line 309 | Line 522 | public class JSR166TestCase extends Test
522          setDelays();
523      }
524  
525 +    void tearDownFail(String format, Object... args) {
526 +        String msg = toString() + ": " + String.format(format, args);
527 +        System.err.println(msg);
528 +        printAllStackTraces();
529 +        throw new AssertionFailedError(msg);
530 +    }
531 +
532      /**
533       * Extra checks that get done for all test cases.
534       *
# Line 336 | Line 556 | public class JSR166TestCase extends Test
556          }
557  
558          if (Thread.interrupted())
559 <            throw new AssertionFailedError("interrupt status set in main thread");
559 >            tearDownFail("interrupt status set in main thread");
560 >
561 >        checkForkJoinPoolThreadLeaks();
562 >    }
563 >
564 >    /**
565 >     * Finds missing try { ... } finally { joinPool(e); }
566 >     */
567 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
568 >        Thread[] survivors = new Thread[7];
569 >        int count = Thread.enumerate(survivors);
570 >        for (int i = 0; i < count; i++) {
571 >            Thread thread = survivors[i];
572 >            String name = thread.getName();
573 >            if (name.startsWith("ForkJoinPool-")) {
574 >                // give thread some time to terminate
575 >                thread.join(LONG_DELAY_MS);
576 >                if (thread.isAlive())
577 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
578 >                                 thread);
579 >            }
580 >        }
581 >
582 >        if (!ForkJoinPool.commonPool()
583 >            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
584 >            tearDownFail("ForkJoin common pool thread stuck");
585      }
586  
587      /**
# Line 417 | Line 662 | public class JSR166TestCase extends Test
662      public void threadAssertEquals(Object x, Object y) {
663          try {
664              assertEquals(x, y);
665 <        } catch (AssertionFailedError t) {
666 <            threadRecordFailure(t);
667 <            throw t;
668 <        } catch (Throwable t) {
669 <            threadUnexpectedException(t);
665 >        } catch (AssertionFailedError fail) {
666 >            threadRecordFailure(fail);
667 >            throw fail;
668 >        } catch (Throwable fail) {
669 >            threadUnexpectedException(fail);
670          }
671      }
672  
# Line 433 | Line 678 | public class JSR166TestCase extends Test
678      public void threadAssertSame(Object x, Object y) {
679          try {
680              assertSame(x, y);
681 <        } catch (AssertionFailedError t) {
682 <            threadRecordFailure(t);
683 <            throw t;
681 >        } catch (AssertionFailedError fail) {
682 >            threadRecordFailure(fail);
683 >            throw fail;
684          }
685      }
686  
# Line 497 | Line 742 | public class JSR166TestCase extends Test
742      /**
743       * Waits out termination of a thread pool or fails doing so.
744       */
745 <    void joinPool(ExecutorService exec) {
745 >    void joinPool(ExecutorService pool) {
746          try {
747 <            exec.shutdown();
748 <            assertTrue("ExecutorService did not terminate in a timely manner",
749 <                       exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
747 >            pool.shutdown();
748 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
749 >                fail("ExecutorService " + pool +
750 >                     " did not terminate in a timely manner");
751          } catch (SecurityException ok) {
752              // Allowed in case test doesn't have privs
753 <        } catch (InterruptedException ie) {
753 >        } catch (InterruptedException fail) {
754              fail("Unexpected InterruptedException");
755          }
756      }
757  
758 +    /** Like Runnable, but with the freedom to throw anything */
759 +    interface Action { public void run() throws Throwable; }
760 +
761 +    /**
762 +     * Runs all the given actions in parallel, failing if any fail.
763 +     * Useful for running multiple variants of tests that are
764 +     * necessarily individually slow because they must block.
765 +     */
766 +    void testInParallel(Action ... actions) {
767 +        ExecutorService pool = Executors.newCachedThreadPool();
768 +        try {
769 +            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
770 +            for (final Action action : actions)
771 +                futures.add(pool.submit(new CheckedRunnable() {
772 +                    public void realRun() throws Throwable { action.run();}}));
773 +            for (Future<?> future : futures)
774 +                try {
775 +                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
776 +                } catch (ExecutionException ex) {
777 +                    threadUnexpectedException(ex.getCause());
778 +                } catch (Exception ex) {
779 +                    threadUnexpectedException(ex);
780 +                }
781 +        } finally {
782 +            joinPool(pool);
783 +        }
784 +    }
785 +
786 +    /**
787 +     * A debugging tool to print all stack traces, as jstack does.
788 +     */
789 +    static void printAllStackTraces() {
790 +        for (ThreadInfo info :
791 +                 ManagementFactory.getThreadMXBean()
792 +                 .dumpAllThreads(true, true))
793 +            System.err.print(info);
794 +    }
795 +
796      /**
797       * Checks that thread does not terminate within the default
798       * millisecond delay of {@code timeoutMillis()}.
# Line 525 | Line 809 | public class JSR166TestCase extends Test
809              // No need to optimize the failing case via Thread.join.
810              delay(millis);
811              assertTrue(thread.isAlive());
812 <        } catch (InterruptedException ie) {
812 >        } catch (InterruptedException fail) {
813              fail("Unexpected InterruptedException");
814          }
815      }
# Line 547 | Line 831 | public class JSR166TestCase extends Test
831              delay(millis);
832              for (Thread thread : threads)
833                  assertTrue(thread.isAlive());
834 <        } catch (InterruptedException ie) {
834 >        } catch (InterruptedException fail) {
835              fail("Unexpected InterruptedException");
836          }
837      }
# Line 569 | Line 853 | public class JSR166TestCase extends Test
853              future.get(timeoutMillis, MILLISECONDS);
854              shouldThrow();
855          } catch (TimeoutException success) {
856 <        } catch (Exception e) {
857 <            threadUnexpectedException(e);
856 >        } catch (Exception fail) {
857 >            threadUnexpectedException(fail);
858          } finally { future.cancel(true); }
859          assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
860      }
# Line 614 | Line 898 | public class JSR166TestCase extends Test
898      public static final Integer m6  = new Integer(-6);
899      public static final Integer m10 = new Integer(-10);
900  
617
901      /**
902       * Runs Runnable r with a security policy that permits precisely
903       * the specified permissions.  If there is no current security
# Line 727 | Line 1010 | public class JSR166TestCase extends Test
1010      void sleep(long millis) {
1011          try {
1012              delay(millis);
1013 <        } catch (InterruptedException ie) {
1013 >        } catch (InterruptedException fail) {
1014              AssertionFailedError afe =
1015                  new AssertionFailedError("Unexpected InterruptedException");
1016 <            afe.initCause(ie);
1016 >            afe.initCause(fail);
1017              throw afe;
1018          }
1019      }
# Line 768 | Line 1051 | public class JSR166TestCase extends Test
1051      /**
1052       * Returns the number of milliseconds since time given by
1053       * startNanoTime, which must have been previously returned from a
1054 <     * call to {@link System.nanoTime()}.
1054 >     * call to {@link System#nanoTime()}.
1055       */
1056 <    long millisElapsedSince(long startNanoTime) {
1056 >    static long millisElapsedSince(long startNanoTime) {
1057          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1058      }
1059  
1060 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1061 + //         long startTime = System.nanoTime();
1062 + //         try {
1063 + //             r.run();
1064 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1065 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1066 + //             throw new AssertionFailedError("did not return promptly");
1067 + //     }
1068 +
1069 + //     void assertTerminatesPromptly(Runnable r) {
1070 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1071 + //     }
1072 +
1073 +    /**
1074 +     * Checks that timed f.get() returns the expected value, and does not
1075 +     * wait for the timeout to elapse before returning.
1076 +     */
1077 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1078 +        long startTime = System.nanoTime();
1079 +        try {
1080 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1081 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1082 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1083 +            throw new AssertionFailedError("timed get did not return promptly");
1084 +    }
1085 +
1086 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1087 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1088 +    }
1089 +
1090      /**
1091       * Returns a new started daemon Thread running the given runnable.
1092       */
# Line 792 | Line 1105 | public class JSR166TestCase extends Test
1105      void awaitTermination(Thread t, long timeoutMillis) {
1106          try {
1107              t.join(timeoutMillis);
1108 <        } catch (InterruptedException ie) {
1109 <            threadUnexpectedException(ie);
1108 >        } catch (InterruptedException fail) {
1109 >            threadUnexpectedException(fail);
1110          } finally {
1111              if (t.getState() != Thread.State.TERMINATED) {
1112                  t.interrupt();
# Line 819 | Line 1132 | public class JSR166TestCase extends Test
1132          public final void run() {
1133              try {
1134                  realRun();
1135 <            } catch (Throwable t) {
1136 <                threadUnexpectedException(t);
1135 >            } catch (Throwable fail) {
1136 >                threadUnexpectedException(fail);
1137              }
1138          }
1139      }
# Line 874 | Line 1187 | public class JSR166TestCase extends Test
1187                  threadShouldThrow("InterruptedException");
1188              } catch (InterruptedException success) {
1189                  threadAssertFalse(Thread.interrupted());
1190 <            } catch (Throwable t) {
1191 <                threadUnexpectedException(t);
1190 >            } catch (Throwable fail) {
1191 >                threadUnexpectedException(fail);
1192              }
1193          }
1194      }
# Line 886 | Line 1199 | public class JSR166TestCase extends Test
1199          public final T call() {
1200              try {
1201                  return realCall();
1202 <            } catch (Throwable t) {
1203 <                threadUnexpectedException(t);
1202 >            } catch (Throwable fail) {
1203 >                threadUnexpectedException(fail);
1204                  return null;
1205              }
1206          }
# Line 904 | Line 1217 | public class JSR166TestCase extends Test
1217                  return result;
1218              } catch (InterruptedException success) {
1219                  threadAssertFalse(Thread.interrupted());
1220 <            } catch (Throwable t) {
1221 <                threadUnexpectedException(t);
1220 >            } catch (Throwable fail) {
1221 >                threadUnexpectedException(fail);
1222              }
1223              return null;
1224          }
# Line 922 | Line 1235 | public class JSR166TestCase extends Test
1235      public static final String TEST_STRING = "a test string";
1236  
1237      public static class StringTask implements Callable<String> {
1238 <        public String call() { return TEST_STRING; }
1238 >        final String value;
1239 >        public StringTask() { this(TEST_STRING); }
1240 >        public StringTask(String value) { this.value = value; }
1241 >        public String call() { return value; }
1242      }
1243  
1244      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 945 | Line 1261 | public class JSR166TestCase extends Test
1261      public void await(CountDownLatch latch) {
1262          try {
1263              assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1264 <        } catch (Throwable t) {
1265 <            threadUnexpectedException(t);
1264 >        } catch (Throwable fail) {
1265 >            threadUnexpectedException(fail);
1266          }
1267      }
1268  
1269      public void await(Semaphore semaphore) {
1270          try {
1271              assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1272 <        } catch (Throwable t) {
1273 <            threadUnexpectedException(t);
1272 >        } catch (Throwable fail) {
1273 >            threadUnexpectedException(fail);
1274          }
1275      }
1276  
# Line 1145 | Line 1461 | public class JSR166TestCase extends Test
1461      public abstract class CheckedRecursiveAction extends RecursiveAction {
1462          protected abstract void realCompute() throws Throwable;
1463  
1464 <        public final void compute() {
1464 >        @Override protected final void compute() {
1465              try {
1466                  realCompute();
1467 <            } catch (Throwable t) {
1468 <                threadUnexpectedException(t);
1467 >            } catch (Throwable fail) {
1468 >                threadUnexpectedException(fail);
1469              }
1470          }
1471      }
# Line 1160 | Line 1476 | public class JSR166TestCase extends Test
1476      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1477          protected abstract T realCompute() throws Throwable;
1478  
1479 <        public final T compute() {
1479 >        @Override protected final T compute() {
1480              try {
1481                  return realCompute();
1482 <            } catch (Throwable t) {
1483 <                threadUnexpectedException(t);
1482 >            } catch (Throwable fail) {
1483 >                threadUnexpectedException(fail);
1484                  return null;
1485              }
1486          }
# Line 1188 | Line 1504 | public class JSR166TestCase extends Test
1504          public int await() {
1505              try {
1506                  return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1507 <            } catch (TimeoutException e) {
1507 >            } catch (TimeoutException timedOut) {
1508                  throw new AssertionFailedError("timed out");
1509 <            } catch (Exception e) {
1509 >            } catch (Exception fail) {
1510                  AssertionFailedError afe =
1511 <                    new AssertionFailedError("Unexpected exception: " + e);
1512 <                afe.initCause(e);
1511 >                    new AssertionFailedError("Unexpected exception: " + fail);
1512 >                afe.initCause(fail);
1513                  throw afe;
1514              }
1515          }
# Line 1221 | Line 1537 | public class JSR166TestCase extends Test
1537                  q.remove();
1538                  shouldThrow();
1539              } catch (NoSuchElementException success) {}
1540 <        } catch (InterruptedException ie) {
1225 <            threadUnexpectedException(ie);
1226 <        }
1540 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1541      }
1542  
1543      void assertSerialEquals(Object x, Object y) {
# Line 1242 | Line 1556 | public class JSR166TestCase extends Test
1556              oos.flush();
1557              oos.close();
1558              return bos.toByteArray();
1559 <        } catch (Throwable t) {
1560 <            threadUnexpectedException(t);
1559 >        } catch (Throwable fail) {
1560 >            threadUnexpectedException(fail);
1561              return new byte[0];
1562          }
1563      }
# Line 1256 | Line 1570 | public class JSR166TestCase extends Test
1570              T clone = (T) ois.readObject();
1571              assertSame(o.getClass(), clone.getClass());
1572              return clone;
1573 <        } catch (Throwable t) {
1574 <            threadUnexpectedException(t);
1573 >        } catch (Throwable fail) {
1574 >            threadUnexpectedException(fail);
1575              return null;
1576          }
1577      }
1578 +
1579 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1580 +                             Runnable... throwingActions) {
1581 +        for (Runnable throwingAction : throwingActions) {
1582 +            boolean threw = false;
1583 +            try { throwingAction.run(); }
1584 +            catch (Throwable t) {
1585 +                threw = true;
1586 +                if (!expectedExceptionClass.isInstance(t)) {
1587 +                    AssertionFailedError afe =
1588 +                        new AssertionFailedError
1589 +                        ("Expected " + expectedExceptionClass.getName() +
1590 +                         ", got " + t.getClass().getName());
1591 +                    afe.initCause(t);
1592 +                    threadUnexpectedException(afe);
1593 +                }
1594 +            }
1595 +            if (!threw)
1596 +                shouldThrow(expectedExceptionClass.getName());
1597 +        }
1598 +    }
1599 +
1600 +    public void assertIteratorExhausted(Iterator<?> it) {
1601 +        try {
1602 +            it.next();
1603 +            shouldThrow();
1604 +        } catch (NoSuchElementException success) {}
1605 +        assertFalse(it.hasNext());
1606 +    }
1607   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines