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.61 by jsr166, Mon Oct 11 03:54:10 2010 UTC vs.
Revision 1.146 by jsr166, Fri Sep 25 23:32:15 2015 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.PropertyPermission;
11 import java.util.concurrent.*;
12 import java.util.concurrent.atomic.AtomicReference;
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;
# Line 18 | 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.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 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 29 | 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 51 | 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>
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 96 | Line 135 | public class JSR166TestCase extends Test
135      private static final boolean useSecurityManager =
136          Boolean.getBoolean("jsr166.useSecurityManager");
137  
138 +    protected static final boolean expensiveTests =
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.
# Line 110 | 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 <    
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) {
145 <            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          }
149        System.exit(0);
239      }
240  
241      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 162 | 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 231 | 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  
242
470      /**
471       * Returns the shortest timed delay. This could
472       * be reimplemented to use for example a Property.
# Line 248 | Line 475 | public class JSR166TestCase extends Test
475          return 50;
476      }
477  
251
478      /**
479       * Sets delays as multiples of SHORT_DELAY.
480       */
# Line 256 | Line 482 | public class JSR166TestCase extends Test
482          SHORT_DELAY_MS = getShortDelay();
483          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
484          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
485 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
485 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
486 >    }
487 >
488 >    /**
489 >     * Returns a timeout in milliseconds to be used in tests that
490 >     * verify that operations block or time out.
491 >     */
492 >    long timeoutMillis() {
493 >        return SHORT_DELAY_MS / 4;
494 >    }
495 >
496 >    /**
497 >     * Returns a new Date instance representing a time at least
498 >     * delayMillis milliseconds in the future.
499 >     */
500 >    Date delayedDate(long 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 279 | 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 +     *
535       * Triggers test case failure if any thread assertions have failed,
536       * by rethrowing, in the test harness thread, any exception recorded
537       * earlier by threadRecordFailure.
538 +     *
539 +     * Triggers test case failure if interrupt status is set in the main thread.
540       */
541      public void tearDown() throws Exception {
542 <        Throwable t = threadFailure.get();
542 >        Throwable t = threadFailure.getAndSet(null);
543          if (t != null) {
544              if (t instanceof Error)
545                  throw (Error) t;
# Line 300 | Line 554 | public class JSR166TestCase extends Test
554                  throw afe;
555              }
556          }
557 +
558 +        if (Thread.interrupted())
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 380 | 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 396 | 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 431 | Line 713 | public class JSR166TestCase extends Test
713          else {
714              AssertionFailedError afe =
715                  new AssertionFailedError("unexpected exception: " + t);
716 <            t.initCause(t);
716 >            afe.initCause(t);
717              throw afe;
718          }
719      }
720  
721      /**
722 +     * Delays, via Thread.sleep, for the given millisecond delay, but
723 +     * if the sleep is shorter than specified, may re-sleep or yield
724 +     * until time elapses.
725 +     */
726 +    static void delay(long millis) throws InterruptedException {
727 +        long startTime = System.nanoTime();
728 +        long ns = millis * 1000 * 1000;
729 +        for (;;) {
730 +            if (millis > 0L)
731 +                Thread.sleep(millis);
732 +            else // too short to sleep
733 +                Thread.yield();
734 +            long d = ns - (System.nanoTime() - startTime);
735 +            if (d > 0L)
736 +                millis = d / (1000 * 1000);
737 +            else
738 +                break;
739 +        }
740 +    }
741 +
742 +    /**
743       * Waits out termination of a thread pool or fails doing so.
744       */
745 <    public 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(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()}.
799 +     */
800 +    void assertThreadStaysAlive(Thread thread) {
801 +        assertThreadStaysAlive(thread, timeoutMillis());
802 +    }
803 +
804 +    /**
805 +     * Checks that thread does not terminate within the given millisecond delay.
806 +     */
807 +    void assertThreadStaysAlive(Thread thread, long millis) {
808 +        try {
809 +            // No need to optimize the failing case via Thread.join.
810 +            delay(millis);
811 +            assertTrue(thread.isAlive());
812 +        } catch (InterruptedException fail) {
813 +            fail("Unexpected InterruptedException");
814 +        }
815 +    }
816 +
817 +    /**
818 +     * Checks that the threads do not terminate within the default
819 +     * millisecond delay of {@code timeoutMillis()}.
820 +     */
821 +    void assertThreadsStayAlive(Thread... threads) {
822 +        assertThreadsStayAlive(timeoutMillis(), threads);
823 +    }
824 +
825 +    /**
826 +     * Checks that the threads do not terminate within the given millisecond delay.
827 +     */
828 +    void assertThreadsStayAlive(long millis, Thread... threads) {
829 +        try {
830 +            // No need to optimize the failing case via Thread.join.
831 +            delay(millis);
832 +            for (Thread thread : threads)
833 +                assertTrue(thread.isAlive());
834 +        } catch (InterruptedException fail) {
835 +            fail("Unexpected InterruptedException");
836 +        }
837 +    }
838 +
839 +    /**
840 +     * Checks that future.get times out, with the default timeout of
841 +     * {@code timeoutMillis()}.
842 +     */
843 +    void assertFutureTimesOut(Future future) {
844 +        assertFutureTimesOut(future, timeoutMillis());
845 +    }
846 +
847 +    /**
848 +     * Checks that future.get times out, with the given millisecond timeout.
849 +     */
850 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
851 +        long startTime = System.nanoTime();
852 +        try {
853 +            future.get(timeoutMillis, MILLISECONDS);
854 +            shouldThrow();
855 +        } catch (TimeoutException success) {
856 +        } catch (Exception fail) {
857 +            threadUnexpectedException(fail);
858 +        } finally { future.cancel(true); }
859 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
860 +    }
861  
862      /**
863       * Fails with message "should throw exception".
# Line 491 | 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  
494
901      /**
902       * Runs Runnable r with a security policy that permits precisely
903       * the specified permissions.  If there is no current security
# Line 503 | Line 909 | public class JSR166TestCase extends Test
909          SecurityManager sm = System.getSecurityManager();
910          if (sm == null) {
911              r.run();
912 +        }
913 +        runWithSecurityManagerWithPermissions(r, permissions);
914 +    }
915 +
916 +    /**
917 +     * Runs Runnable r with a security policy that permits precisely
918 +     * the specified permissions.  If there is no current security
919 +     * manager, a temporary one is set for the duration of the
920 +     * Runnable.  We require that any security manager permit
921 +     * getPolicy/setPolicy.
922 +     */
923 +    public void runWithSecurityManagerWithPermissions(Runnable r,
924 +                                                      Permission... permissions) {
925 +        SecurityManager sm = System.getSecurityManager();
926 +        if (sm == null) {
927              Policy savedPolicy = Policy.getPolicy();
928              try {
929                  Policy.setPolicy(permissivePolicy());
930                  System.setSecurityManager(new SecurityManager());
931 <                runWithPermissions(r, permissions);
931 >                runWithSecurityManagerWithPermissions(r, permissions);
932              } finally {
933                  System.setSecurityManager(null);
934                  Policy.setPolicy(savedPolicy);
# Line 555 | Line 976 | public class JSR166TestCase extends Test
976              return perms.implies(p);
977          }
978          public void refresh() {}
979 +        public String toString() {
980 +            List<Permission> ps = new ArrayList<Permission>();
981 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
982 +                ps.add(e.nextElement());
983 +            return "AdjustablePolicy with permissions " + ps;
984 +        }
985      }
986  
987      /**
# Line 582 | Line 1009 | public class JSR166TestCase extends Test
1009       */
1010      void sleep(long millis) {
1011          try {
1012 <            Thread.sleep(millis);
1013 <        } catch (InterruptedException ie) {
1012 >            delay(millis);
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      }
1020  
1021      /**
1022 <     * Sleeps until the timeout has elapsed, or interrupted.
1023 <     * Does <em>NOT</em> throw InterruptedException.
1022 >     * Spin-waits up to the specified number of milliseconds for the given
1023 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1024       */
1025 <    void sleepTillInterrupted(long timeoutMillis) {
1025 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1026 >        long startTime = System.nanoTime();
1027 >        for (;;) {
1028 >            Thread.State s = thread.getState();
1029 >            if (s == Thread.State.BLOCKED ||
1030 >                s == Thread.State.WAITING ||
1031 >                s == Thread.State.TIMED_WAITING)
1032 >                return;
1033 >            else if (s == Thread.State.TERMINATED)
1034 >                fail("Unexpected thread termination");
1035 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1036 >                threadAssertTrue(thread.isAlive());
1037 >                return;
1038 >            }
1039 >            Thread.yield();
1040 >        }
1041 >    }
1042 >
1043 >    /**
1044 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1045 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
1046 >     */
1047 >    void waitForThreadToEnterWaitState(Thread thread) {
1048 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1049 >    }
1050 >
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()}.
1055 >     */
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 <            Thread.sleep(timeoutMillis);
1081 <        } catch (InterruptedException wakeup) {}
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      /**
# Line 619 | 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.isAlive()) {
1111 >            if (t.getState() != Thread.State.TERMINATED) {
1112                  t.interrupt();
1113                  fail("Test timed out");
1114              }
1115          }
1116      }
1117  
1118 +    /**
1119 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1120 +     * terminate (using {@link Thread#join(long)}), else interrupts
1121 +     * the thread (in the hope that it may terminate later) and fails.
1122 +     */
1123 +    void awaitTermination(Thread t) {
1124 +        awaitTermination(t, LONG_DELAY_MS);
1125 +    }
1126 +
1127      // Some convenient Runnable classes
1128  
1129      public abstract class CheckedRunnable implements Runnable {
# Line 637 | 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 691 | Line 1186 | public class JSR166TestCase extends Test
1186                  realRun();
1187                  threadShouldThrow("InterruptedException");
1188              } catch (InterruptedException success) {
1189 <            } catch (Throwable t) {
1190 <                threadUnexpectedException(t);
1189 >                threadAssertFalse(Thread.interrupted());
1190 >            } catch (Throwable fail) {
1191 >                threadUnexpectedException(fail);
1192              }
1193          }
1194      }
# Line 703 | 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 720 | Line 1216 | public class JSR166TestCase extends Test
1216                  threadShouldThrow("InterruptedException");
1217                  return result;
1218              } catch (InterruptedException success) {
1219 <            } catch (Throwable t) {
1220 <                threadUnexpectedException(t);
1219 >                threadAssertFalse(Thread.interrupted());
1220 >            } catch (Throwable fail) {
1221 >                threadUnexpectedException(fail);
1222              }
1223              return null;
1224          }
# Line 738 | 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) {
1245          return new CheckedCallable<String>() {
1246 <            public String realCall() {
1246 >            protected String realCall() {
1247                  try {
1248                      latch.await();
1249                  } catch (InterruptedException quittingTime) {}
# Line 751 | Line 1251 | public class JSR166TestCase extends Test
1251              }};
1252      }
1253  
1254 +    public Runnable awaiter(final CountDownLatch latch) {
1255 +        return new CheckedRunnable() {
1256 +            public void realRun() throws InterruptedException {
1257 +                await(latch);
1258 +            }};
1259 +    }
1260 +
1261 +    public void await(CountDownLatch latch) {
1262 +        try {
1263 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
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 fail) {
1273 +            threadUnexpectedException(fail);
1274 +        }
1275 +    }
1276 +
1277 + //     /**
1278 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1279 + //      */
1280 + //     public void await(AtomicBoolean flag) {
1281 + //         await(flag, LONG_DELAY_MS);
1282 + //     }
1283 +
1284 + //     /**
1285 + //      * Spin-waits up to the specified timeout until flag becomes true.
1286 + //      */
1287 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1288 + //         long startTime = System.nanoTime();
1289 + //         while (!flag.get()) {
1290 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1291 + //                 throw new AssertionFailedError("timed out");
1292 + //             Thread.yield();
1293 + //         }
1294 + //     }
1295 +
1296      public static class NPETask implements Callable<String> {
1297          public String call() { throw new NullPointerException(); }
1298      }
# Line 761 | Line 1303 | public class JSR166TestCase extends Test
1303  
1304      public class ShortRunnable extends CheckedRunnable {
1305          protected void realRun() throws Throwable {
1306 <            Thread.sleep(SHORT_DELAY_MS);
1306 >            delay(SHORT_DELAY_MS);
1307          }
1308      }
1309  
1310      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1311          protected void realRun() throws InterruptedException {
1312 <            Thread.sleep(SHORT_DELAY_MS);
1312 >            delay(SHORT_DELAY_MS);
1313          }
1314      }
1315  
1316      public class SmallRunnable extends CheckedRunnable {
1317          protected void realRun() throws Throwable {
1318 <            Thread.sleep(SMALL_DELAY_MS);
1318 >            delay(SMALL_DELAY_MS);
1319          }
1320      }
1321  
1322      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1323          protected void realRun() {
1324              try {
1325 <                Thread.sleep(SMALL_DELAY_MS);
1325 >                delay(SMALL_DELAY_MS);
1326              } catch (InterruptedException ok) {}
1327          }
1328      }
1329  
1330      public class SmallCallable extends CheckedCallable {
1331          protected Object realCall() throws InterruptedException {
1332 <            Thread.sleep(SMALL_DELAY_MS);
1332 >            delay(SMALL_DELAY_MS);
1333              return Boolean.TRUE;
1334          }
1335      }
1336  
1337      public class MediumRunnable extends CheckedRunnable {
1338          protected void realRun() throws Throwable {
1339 <            Thread.sleep(MEDIUM_DELAY_MS);
1339 >            delay(MEDIUM_DELAY_MS);
1340          }
1341      }
1342  
1343      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1344          protected void realRun() throws InterruptedException {
1345 <            Thread.sleep(MEDIUM_DELAY_MS);
1345 >            delay(MEDIUM_DELAY_MS);
1346          }
1347      }
1348  
1349 +    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1350 +        return new CheckedRunnable() {
1351 +            protected void realRun() {
1352 +                try {
1353 +                    delay(timeoutMillis);
1354 +                } catch (InterruptedException ok) {}
1355 +            }};
1356 +    }
1357 +
1358      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1359          protected void realRun() {
1360              try {
1361 <                Thread.sleep(MEDIUM_DELAY_MS);
1361 >                delay(MEDIUM_DELAY_MS);
1362              } catch (InterruptedException ok) {}
1363          }
1364      }
# Line 815 | Line 1366 | public class JSR166TestCase extends Test
1366      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1367          protected void realRun() {
1368              try {
1369 <                Thread.sleep(LONG_DELAY_MS);
1369 >                delay(LONG_DELAY_MS);
1370              } catch (InterruptedException ok) {}
1371          }
1372      }
# Line 839 | Line 1390 | public class JSR166TestCase extends Test
1390                  public boolean isDone() { return done; }
1391                  public void run() {
1392                      try {
1393 <                        Thread.sleep(timeoutMillis);
1393 >                        delay(timeoutMillis);
1394                          done = true;
1395                      } catch (InterruptedException ok) {}
1396                  }
# Line 850 | Line 1401 | public class JSR166TestCase extends Test
1401          public volatile boolean done = false;
1402          public void run() {
1403              try {
1404 <                Thread.sleep(SHORT_DELAY_MS);
1404 >                delay(SHORT_DELAY_MS);
1405                  done = true;
1406              } catch (InterruptedException ok) {}
1407          }
# Line 860 | Line 1411 | public class JSR166TestCase extends Test
1411          public volatile boolean done = false;
1412          public void run() {
1413              try {
1414 <                Thread.sleep(SMALL_DELAY_MS);
1414 >                delay(SMALL_DELAY_MS);
1415                  done = true;
1416              } catch (InterruptedException ok) {}
1417          }
# Line 870 | Line 1421 | public class JSR166TestCase extends Test
1421          public volatile boolean done = false;
1422          public void run() {
1423              try {
1424 <                Thread.sleep(MEDIUM_DELAY_MS);
1424 >                delay(MEDIUM_DELAY_MS);
1425                  done = true;
1426              } catch (InterruptedException ok) {}
1427          }
# Line 880 | Line 1431 | public class JSR166TestCase extends Test
1431          public volatile boolean done = false;
1432          public void run() {
1433              try {
1434 <                Thread.sleep(LONG_DELAY_MS);
1434 >                delay(LONG_DELAY_MS);
1435                  done = true;
1436              } catch (InterruptedException ok) {}
1437          }
# Line 897 | Line 1448 | public class JSR166TestCase extends Test
1448          public volatile boolean done = false;
1449          public Object call() {
1450              try {
1451 <                Thread.sleep(SMALL_DELAY_MS);
1451 >                delay(SMALL_DELAY_MS);
1452                  done = true;
1453              } catch (InterruptedException ok) {}
1454              return Boolean.TRUE;
# Line 910 | 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 925 | 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 944 | Line 1495 | public class JSR166TestCase extends Test
1495      }
1496  
1497      /**
1498 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1499 <     * of throwing checked exceptions.
1498 >     * A CyclicBarrier that uses timed await and fails with
1499 >     * AssertionFailedErrors instead of throwing checked exceptions.
1500       */
1501      public class CheckedBarrier extends CyclicBarrier {
1502          public CheckedBarrier(int parties) { super(parties); }
1503  
1504          public int await() {
1505              try {
1506 <                return super.await();
1507 <            } catch (Exception e) {
1506 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1507 >            } catch (TimeoutException timedOut) {
1508 >                throw new AssertionFailedError("timed out");
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          }
1516      }
1517  
1518 +    void checkEmpty(BlockingQueue q) {
1519 +        try {
1520 +            assertTrue(q.isEmpty());
1521 +            assertEquals(0, q.size());
1522 +            assertNull(q.peek());
1523 +            assertNull(q.poll());
1524 +            assertNull(q.poll(0, MILLISECONDS));
1525 +            assertEquals(q.toString(), "[]");
1526 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1527 +            assertFalse(q.iterator().hasNext());
1528 +            try {
1529 +                q.element();
1530 +                shouldThrow();
1531 +            } catch (NoSuchElementException success) {}
1532 +            try {
1533 +                q.iterator().next();
1534 +                shouldThrow();
1535 +            } catch (NoSuchElementException success) {}
1536 +            try {
1537 +                q.remove();
1538 +                shouldThrow();
1539 +            } catch (NoSuchElementException success) {}
1540 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1541 +    }
1542 +
1543 +    void assertSerialEquals(Object x, Object y) {
1544 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1545 +    }
1546 +
1547 +    void assertNotSerialEquals(Object x, Object y) {
1548 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1549 +    }
1550 +
1551 +    byte[] serialBytes(Object o) {
1552 +        try {
1553 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1554 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1555 +            oos.writeObject(o);
1556 +            oos.flush();
1557 +            oos.close();
1558 +            return bos.toByteArray();
1559 +        } catch (Throwable fail) {
1560 +            threadUnexpectedException(fail);
1561 +            return new byte[0];
1562 +        }
1563 +    }
1564 +
1565 +    @SuppressWarnings("unchecked")
1566 +    <T> T serialClone(T o) {
1567 +        try {
1568 +            ObjectInputStream ois = new ObjectInputStream
1569 +                (new ByteArrayInputStream(serialBytes(o)));
1570 +            T clone = (T) ois.readObject();
1571 +            assertSame(o.getClass(), clone.getClass());
1572 +            return clone;
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