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.69 by dl, Fri Nov 19 00:20:12 2010 UTC vs.
Revision 1.149 by jsr166, Sat Oct 3 16:57:25 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 19 | 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 30 | 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 52 | 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 101 | 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 114 | 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 +    public void runBare() throws Throwable {
190 +        if (methodFilter == null
191 +            || methodFilter.matcher(toString()).find())
192 +            super.runBare();
193 +    }
194 +
195      protected void runTest() throws Throwable {
196 <        if (profileTests)
197 <            runTestProfiled();
198 <        else
199 <            super.runTest();
196 >        for (int i = 0; i < runsPerTest; i++) {
197 >            if (profileTests)
198 >                runTestProfiled();
199 >            else
200 >                super.runTest();
201 >        }
202      }
203  
204      protected void runTestProfiled() throws Throwable {
205 <        long t0 = System.nanoTime();
206 <        try {
205 >        for (int i = 0; i < 2; i++) {
206 >            long startTime = System.nanoTime();
207              super.runTest();
208 <        } finally {
209 <            long elapsedMillis =
210 <                (System.nanoTime() - t0) / (1000L * 1000L);
211 <            if (elapsedMillis >= profileThreshold)
208 >            long elapsedMillis = millisElapsedSince(startTime);
209 >            if (elapsedMillis < profileThreshold)
210 >                break;
211 >            // Never report first run of any test; treat it as a
212 >            // warmup run, notably to trigger all needed classloading,
213 >            if (i > 0)
214                  System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
215          }
216      }
217  
218      /**
219 <     * Runs all JSR166 unit tests using junit.textui.TestRunner
219 >     * Runs all JSR166 unit tests using junit.textui.TestRunner.
220       */
221      public static void main(String[] args) {
222 +        main(suite(), args);
223 +    }
224 +
225 +    /**
226 +     * Runs all unit tests in the given test suite.
227 +     * Actual behavior influenced by jsr166.* system properties.
228 +     */
229 +    static void main(Test suite, String[] args) {
230          if (useSecurityManager) {
231              System.err.println("Setting a permissive security manager");
232              Policy.setPolicy(permissivePolicy());
233              System.setSecurityManager(new SecurityManager());
234          }
235 <        int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
236 <
237 <        Test s = suite();
238 <        for (int i = 0; i < iters; ++i) {
149 <            junit.textui.TestRunner.run(s);
235 >        for (int i = 0; i < suiteRuns; i++) {
236 >            TestResult result = junit.textui.TestRunner.run(suite);
237 >            if (!result.wasSuccessful())
238 >                System.exit(1);
239              System.gc();
240              System.runFinalization();
241          }
153        System.exit(0);
242      }
243  
244      public static TestSuite newTestSuite(Object... suiteOrClasses) {
# Line 166 | Line 254 | public class JSR166TestCase extends Test
254          return suite;
255      }
256  
257 +    public static void addNamedTestClasses(TestSuite suite,
258 +                                           String... testClassNames) {
259 +        for (String testClassName : testClassNames) {
260 +            try {
261 +                Class<?> testClass = Class.forName(testClassName);
262 +                Method m = testClass.getDeclaredMethod("suite",
263 +                                                       new Class<?>[0]);
264 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
265 +            } catch (Exception e) {
266 +                throw new Error("Missing test class", e);
267 +            }
268 +        }
269 +    }
270 +
271 +    public static final double JAVA_CLASS_VERSION;
272 +    public static final String JAVA_SPECIFICATION_VERSION;
273 +    static {
274 +        try {
275 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
276 +                new java.security.PrivilegedAction<Double>() {
277 +                public Double run() {
278 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
279 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
280 +                new java.security.PrivilegedAction<String>() {
281 +                public String run() {
282 +                    return System.getProperty("java.specification.version");}});
283 +        } catch (Throwable t) {
284 +            throw new Error(t);
285 +        }
286 +    }
287 +
288 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
289 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
290 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
291 +    public static boolean atLeastJava9() {
292 +        return JAVA_CLASS_VERSION >= 53.0
293 +            // As of 2015-09, java9 still uses 52.0 class file version
294 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
295 +    }
296 +    public static boolean atLeastJava10() {
297 +        return JAVA_CLASS_VERSION >= 54.0
298 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
299 +    }
300 +
301      /**
302       * Collects all JSR166 unit tests as one suite.
303       */
304      public static Test suite() {
305 <        return newTestSuite(
305 >        // Java7+ test classes
306 >        TestSuite suite = newTestSuite(
307              ForkJoinPoolTest.suite(),
308              ForkJoinTaskTest.suite(),
309              RecursiveActionTest.suite(),
# Line 235 | Line 368 | public class JSR166TestCase extends Test
368              TreeSetTest.suite(),
369              TreeSubMapTest.suite(),
370              TreeSubSetTest.suite());
371 +
372 +        // Java8+ test classes
373 +        if (atLeastJava8()) {
374 +            String[] java8TestClassNames = {
375 +                "Atomic8Test",
376 +                "CompletableFutureTest",
377 +                "ConcurrentHashMap8Test",
378 +                "CountedCompleterTest",
379 +                "DoubleAccumulatorTest",
380 +                "DoubleAdderTest",
381 +                "ForkJoinPool8Test",
382 +                "ForkJoinTask8Test",
383 +                "LongAccumulatorTest",
384 +                "LongAdderTest",
385 +                "SplittableRandomTest",
386 +                "StampedLockTest",
387 +                "SubmissionPublisherTest",
388 +                "ThreadLocalRandom8Test",
389 +            };
390 +            addNamedTestClasses(suite, java8TestClassNames);
391 +        }
392 +
393 +        // Java9+ test classes
394 +        if (atLeastJava9()) {
395 +            String[] java9TestClassNames = {
396 +                // Currently empty, but expecting varhandle tests
397 +            };
398 +            addNamedTestClasses(suite, java9TestClassNames);
399 +        }
400 +
401 +        return suite;
402 +    }
403 +
404 +    /** Returns list of junit-style test method names in given class. */
405 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
406 +        Method[] methods = testClass.getDeclaredMethods();
407 +        ArrayList<String> names = new ArrayList<String>(methods.length);
408 +        for (Method method : methods) {
409 +            if (method.getName().startsWith("test")
410 +                && Modifier.isPublic(method.getModifiers())
411 +                // method.getParameterCount() requires jdk8+
412 +                && method.getParameterTypes().length == 0) {
413 +                names.add(method.getName());
414 +            }
415 +        }
416 +        return names;
417 +    }
418 +
419 +    /**
420 +     * Returns junit-style testSuite for the given test class, but
421 +     * parameterized by passing extra data to each test.
422 +     */
423 +    public static <ExtraData> Test parameterizedTestSuite
424 +        (Class<? extends JSR166TestCase> testClass,
425 +         Class<ExtraData> dataClass,
426 +         ExtraData data) {
427 +        try {
428 +            TestSuite suite = new TestSuite();
429 +            Constructor c =
430 +                testClass.getDeclaredConstructor(dataClass, String.class);
431 +            for (String methodName : testMethodNames(testClass))
432 +                suite.addTest((Test) c.newInstance(data, methodName));
433 +            return suite;
434 +        } catch (Exception e) {
435 +            throw new Error(e);
436 +        }
437      }
438  
439 +    /**
440 +     * Returns junit-style testSuite for the jdk8 extension of the
441 +     * given test class, but parameterized by passing extra data to
442 +     * each test.  Uses reflection to allow compilation in jdk7.
443 +     */
444 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
445 +        (Class<? extends JSR166TestCase> testClass,
446 +         Class<ExtraData> dataClass,
447 +         ExtraData data) {
448 +        if (atLeastJava8()) {
449 +            String name = testClass.getName();
450 +            String name8 = name.replaceAll("Test$", "8Test");
451 +            if (name.equals(name8)) throw new Error(name);
452 +            try {
453 +                return (Test)
454 +                    Class.forName(name8)
455 +                    .getMethod("testSuite", new Class[] { dataClass })
456 +                    .invoke(null, data);
457 +            } catch (Exception e) {
458 +                throw new Error(e);
459 +            }
460 +        } else {
461 +            return new TestSuite();
462 +        }
463 +
464 +    }
465 +
466 +    // Delays for timing-dependent tests, in milliseconds.
467  
468      public static long SHORT_DELAY_MS;
469      public static long SMALL_DELAY_MS;
470      public static long MEDIUM_DELAY_MS;
471      public static long LONG_DELAY_MS;
472  
246
473      /**
474       * Returns the shortest timed delay. This could
475       * be reimplemented to use for example a Property.
# Line 252 | Line 478 | public class JSR166TestCase extends Test
478          return 50;
479      }
480  
255
481      /**
482       * Sets delays as multiples of SHORT_DELAY.
483       */
# Line 260 | Line 485 | public class JSR166TestCase extends Test
485          SHORT_DELAY_MS = getShortDelay();
486          SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
487          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
488 <        LONG_DELAY_MS   = SHORT_DELAY_MS * 50;
488 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
489 >    }
490 >
491 >    /**
492 >     * Returns a timeout in milliseconds to be used in tests that
493 >     * verify that operations block or time out.
494 >     */
495 >    long timeoutMillis() {
496 >        return SHORT_DELAY_MS / 4;
497 >    }
498 >
499 >    /**
500 >     * Returns a new Date instance representing a time at least
501 >     * delayMillis milliseconds in the future.
502 >     */
503 >    Date delayedDate(long delayMillis) {
504 >        // Add 1 because currentTimeMillis is known to round into the past.
505 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
506      }
507  
508      /**
# Line 283 | Line 525 | public class JSR166TestCase extends Test
525          setDelays();
526      }
527  
528 +    void tearDownFail(String format, Object... args) {
529 +        String msg = toString() + ": " + String.format(format, args);
530 +        System.err.println(msg);
531 +        printAllStackTraces();
532 +        throw new AssertionFailedError(msg);
533 +    }
534 +
535      /**
536 +     * Extra checks that get done for all test cases.
537 +     *
538       * Triggers test case failure if any thread assertions have failed,
539       * by rethrowing, in the test harness thread, any exception recorded
540       * earlier by threadRecordFailure.
541 +     *
542 +     * Triggers test case failure if interrupt status is set in the main thread.
543       */
544      public void tearDown() throws Exception {
545 <        Throwable t = threadFailure.getAndSet(null);
545 >        Throwable t = threadFailure.getAndSet(null);
546          if (t != null) {
547              if (t instanceof Error)
548                  throw (Error) t;
# Line 304 | Line 557 | public class JSR166TestCase extends Test
557                  throw afe;
558              }
559          }
560 +
561 +        if (Thread.interrupted())
562 +            tearDownFail("interrupt status set in main thread");
563 +
564 +        checkForkJoinPoolThreadLeaks();
565 +    }
566 +
567 +    /**
568 +     * Finds missing try { ... } finally { joinPool(e); }
569 +     */
570 +    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
571 +        Thread[] survivors = new Thread[7];
572 +        int count = Thread.enumerate(survivors);
573 +        for (int i = 0; i < count; i++) {
574 +            Thread thread = survivors[i];
575 +            String name = thread.getName();
576 +            if (name.startsWith("ForkJoinPool-")) {
577 +                // give thread some time to terminate
578 +                thread.join(LONG_DELAY_MS);
579 +                if (thread.isAlive())
580 +                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
581 +                                 thread);
582 +            }
583 +        }
584 +
585 +        if (!ForkJoinPool.commonPool()
586 +            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
587 +            tearDownFail("ForkJoin common pool thread stuck");
588      }
589  
590      /**
# Line 384 | Line 665 | public class JSR166TestCase extends Test
665      public void threadAssertEquals(Object x, Object y) {
666          try {
667              assertEquals(x, y);
668 <        } catch (AssertionFailedError t) {
669 <            threadRecordFailure(t);
670 <            throw t;
671 <        } catch (Throwable t) {
672 <            threadUnexpectedException(t);
668 >        } catch (AssertionFailedError fail) {
669 >            threadRecordFailure(fail);
670 >            throw fail;
671 >        } catch (Throwable fail) {
672 >            threadUnexpectedException(fail);
673          }
674      }
675  
# Line 400 | Line 681 | public class JSR166TestCase extends Test
681      public void threadAssertSame(Object x, Object y) {
682          try {
683              assertSame(x, y);
684 <        } catch (AssertionFailedError t) {
685 <            threadRecordFailure(t);
686 <            throw t;
684 >        } catch (AssertionFailedError fail) {
685 >            threadRecordFailure(fail);
686 >            throw fail;
687          }
688      }
689  
# Line 435 | Line 716 | public class JSR166TestCase extends Test
716          else {
717              AssertionFailedError afe =
718                  new AssertionFailedError("unexpected exception: " + t);
719 <            t.initCause(t);
719 >            afe.initCause(t);
720              throw afe;
721          }
722      }
723  
724      /**
725 +     * Delays, via Thread.sleep, for the given millisecond delay, but
726 +     * if the sleep is shorter than specified, may re-sleep or yield
727 +     * until time elapses.
728 +     */
729 +    static void delay(long millis) throws InterruptedException {
730 +        long startTime = System.nanoTime();
731 +        long ns = millis * 1000 * 1000;
732 +        for (;;) {
733 +            if (millis > 0L)
734 +                Thread.sleep(millis);
735 +            else // too short to sleep
736 +                Thread.yield();
737 +            long d = ns - (System.nanoTime() - startTime);
738 +            if (d > 0L)
739 +                millis = d / (1000 * 1000);
740 +            else
741 +                break;
742 +        }
743 +    }
744 +
745 +    /**
746 +     * Allows use of try-with-resources with per-test thread pools.
747 +     */
748 +    static class PoolCloser<T extends ExecutorService>
749 +            implements AutoCloseable {
750 +        public final T pool;
751 +        public PoolCloser(T pool) { this.pool = pool; }
752 +        public void close() { joinPool(pool); }
753 +    }
754 +
755 +    /**
756       * Waits out termination of a thread pool or fails doing so.
757       */
758 <    public void joinPool(ExecutorService exec) {
758 >    static void joinPool(ExecutorService pool) {
759          try {
760 <            exec.shutdown();
761 <            assertTrue("ExecutorService did not terminate in a timely manner",
762 <                       exec.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
760 >            pool.shutdown();
761 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS))
762 >                fail("ExecutorService " + pool +
763 >                     " did not terminate in a timely manner");
764          } catch (SecurityException ok) {
765              // Allowed in case test doesn't have privs
766 <        } catch (InterruptedException ie) {
766 >        } catch (InterruptedException fail) {
767 >            fail("Unexpected InterruptedException");
768 >        }
769 >    }
770 >
771 >    /** Like Runnable, but with the freedom to throw anything */
772 >    interface Action { public void run() throws Throwable; }
773 >
774 >    /**
775 >     * Runs all the given actions in parallel, failing if any fail.
776 >     * Useful for running multiple variants of tests that are
777 >     * necessarily individually slow because they must block.
778 >     */
779 >    void testInParallel(Action ... actions) {
780 >        ExecutorService pool = Executors.newCachedThreadPool();
781 >        try {
782 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
783 >            for (final Action action : actions)
784 >                futures.add(pool.submit(new CheckedRunnable() {
785 >                    public void realRun() throws Throwable { action.run();}}));
786 >            for (Future<?> future : futures)
787 >                try {
788 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
789 >                } catch (ExecutionException ex) {
790 >                    threadUnexpectedException(ex.getCause());
791 >                } catch (Exception ex) {
792 >                    threadUnexpectedException(ex);
793 >                }
794 >        } finally {
795 >            joinPool(pool);
796 >        }
797 >    }
798 >
799 >    /**
800 >     * A debugging tool to print all stack traces, as jstack does.
801 >     */
802 >    static void printAllStackTraces() {
803 >        for (ThreadInfo info :
804 >                 ManagementFactory.getThreadMXBean()
805 >                 .dumpAllThreads(true, true))
806 >            System.err.print(info);
807 >    }
808 >
809 >    /**
810 >     * Checks that thread does not terminate within the default
811 >     * millisecond delay of {@code timeoutMillis()}.
812 >     */
813 >    void assertThreadStaysAlive(Thread thread) {
814 >        assertThreadStaysAlive(thread, timeoutMillis());
815 >    }
816 >
817 >    /**
818 >     * Checks that thread does not terminate within the given millisecond delay.
819 >     */
820 >    void assertThreadStaysAlive(Thread thread, long millis) {
821 >        try {
822 >            // No need to optimize the failing case via Thread.join.
823 >            delay(millis);
824 >            assertTrue(thread.isAlive());
825 >        } catch (InterruptedException fail) {
826              fail("Unexpected InterruptedException");
827          }
828      }
829  
830 +    /**
831 +     * Checks that the threads do not terminate within the default
832 +     * millisecond delay of {@code timeoutMillis()}.
833 +     */
834 +    void assertThreadsStayAlive(Thread... threads) {
835 +        assertThreadsStayAlive(timeoutMillis(), threads);
836 +    }
837 +
838 +    /**
839 +     * Checks that the threads do not terminate within the given millisecond delay.
840 +     */
841 +    void assertThreadsStayAlive(long millis, Thread... threads) {
842 +        try {
843 +            // No need to optimize the failing case via Thread.join.
844 +            delay(millis);
845 +            for (Thread thread : threads)
846 +                assertTrue(thread.isAlive());
847 +        } catch (InterruptedException fail) {
848 +            fail("Unexpected InterruptedException");
849 +        }
850 +    }
851 +
852 +    /**
853 +     * Checks that future.get times out, with the default timeout of
854 +     * {@code timeoutMillis()}.
855 +     */
856 +    void assertFutureTimesOut(Future future) {
857 +        assertFutureTimesOut(future, timeoutMillis());
858 +    }
859 +
860 +    /**
861 +     * Checks that future.get times out, with the given millisecond timeout.
862 +     */
863 +    void assertFutureTimesOut(Future future, long timeoutMillis) {
864 +        long startTime = System.nanoTime();
865 +        try {
866 +            future.get(timeoutMillis, MILLISECONDS);
867 +            shouldThrow();
868 +        } catch (TimeoutException success) {
869 +        } catch (Exception fail) {
870 +            threadUnexpectedException(fail);
871 +        } finally { future.cancel(true); }
872 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
873 +    }
874  
875      /**
876       * Fails with message "should throw exception".
# Line 495 | Line 911 | public class JSR166TestCase extends Test
911      public static final Integer m6  = new Integer(-6);
912      public static final Integer m10 = new Integer(-10);
913  
498
914      /**
915       * Runs Runnable r with a security policy that permits precisely
916       * the specified permissions.  If there is no current security
# Line 507 | Line 922 | public class JSR166TestCase extends Test
922          SecurityManager sm = System.getSecurityManager();
923          if (sm == null) {
924              r.run();
925 +        }
926 +        runWithSecurityManagerWithPermissions(r, permissions);
927 +    }
928 +
929 +    /**
930 +     * Runs Runnable r with a security policy that permits precisely
931 +     * the specified permissions.  If there is no current security
932 +     * manager, a temporary one is set for the duration of the
933 +     * Runnable.  We require that any security manager permit
934 +     * getPolicy/setPolicy.
935 +     */
936 +    public void runWithSecurityManagerWithPermissions(Runnable r,
937 +                                                      Permission... permissions) {
938 +        SecurityManager sm = System.getSecurityManager();
939 +        if (sm == null) {
940              Policy savedPolicy = Policy.getPolicy();
941              try {
942                  Policy.setPolicy(permissivePolicy());
943                  System.setSecurityManager(new SecurityManager());
944 <                runWithPermissions(r, permissions);
944 >                runWithSecurityManagerWithPermissions(r, permissions);
945              } finally {
946                  System.setSecurityManager(null);
947                  Policy.setPolicy(savedPolicy);
# Line 559 | Line 989 | public class JSR166TestCase extends Test
989              return perms.implies(p);
990          }
991          public void refresh() {}
992 +        public String toString() {
993 +            List<Permission> ps = new ArrayList<Permission>();
994 +            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
995 +                ps.add(e.nextElement());
996 +            return "AdjustablePolicy with permissions " + ps;
997 +        }
998      }
999  
1000      /**
# Line 586 | Line 1022 | public class JSR166TestCase extends Test
1022       */
1023      void sleep(long millis) {
1024          try {
1025 <            Thread.sleep(millis);
1026 <        } catch (InterruptedException ie) {
1025 >            delay(millis);
1026 >        } catch (InterruptedException fail) {
1027              AssertionFailedError afe =
1028                  new AssertionFailedError("Unexpected InterruptedException");
1029 <            afe.initCause(ie);
1029 >            afe.initCause(fail);
1030              throw afe;
1031          }
1032      }
1033  
1034      /**
1035 <     * Sleeps until the timeout has elapsed, or interrupted.
600 <     * Does <em>NOT</em> throw InterruptedException.
601 <     */
602 <    void sleepTillInterrupted(long timeoutMillis) {
603 <        try {
604 <            Thread.sleep(timeoutMillis);
605 <        } catch (InterruptedException wakeup) {}
606 <    }
607 <
608 <    /**
609 <     * Waits up to the specified number of milliseconds for the given
1035 >     * Spin-waits up to the specified number of milliseconds for the given
1036       * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1037       */
1038      void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1039 <        long timeoutNanos = timeoutMillis * 1000L * 1000L;
614 <        long t0 = System.nanoTime();
1039 >        long startTime = System.nanoTime();
1040          for (;;) {
1041              Thread.State s = thread.getState();
1042              if (s == Thread.State.BLOCKED ||
# Line 620 | Line 1045 | public class JSR166TestCase extends Test
1045                  return;
1046              else if (s == Thread.State.TERMINATED)
1047                  fail("Unexpected thread termination");
1048 <            else if (System.nanoTime() - t0 > timeoutNanos) {
1048 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1049                  threadAssertTrue(thread.isAlive());
1050                  return;
1051              }
# Line 629 | Line 1054 | public class JSR166TestCase extends Test
1054      }
1055  
1056      /**
1057 +     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1058 +     * state: BLOCKED, WAITING, or TIMED_WAITING.
1059 +     */
1060 +    void waitForThreadToEnterWaitState(Thread thread) {
1061 +        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1062 +    }
1063 +
1064 +    /**
1065       * Returns the number of milliseconds since time given by
1066       * startNanoTime, which must have been previously returned from a
1067 <     * call to {@link System.nanoTime()}.
1067 >     * call to {@link System#nanoTime()}.
1068       */
1069 <    long millisElapsedSince(long startNanoTime) {
1069 >    static long millisElapsedSince(long startNanoTime) {
1070          return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1071      }
1072  
1073 + //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1074 + //         long startTime = System.nanoTime();
1075 + //         try {
1076 + //             r.run();
1077 + //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1078 + //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1079 + //             throw new AssertionFailedError("did not return promptly");
1080 + //     }
1081 +
1082 + //     void assertTerminatesPromptly(Runnable r) {
1083 + //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1084 + //     }
1085 +
1086 +    /**
1087 +     * Checks that timed f.get() returns the expected value, and does not
1088 +     * wait for the timeout to elapse before returning.
1089 +     */
1090 +    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1091 +        long startTime = System.nanoTime();
1092 +        try {
1093 +            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1094 +        } catch (Throwable fail) { threadUnexpectedException(fail); }
1095 +        if (millisElapsedSince(startTime) > timeoutMillis/2)
1096 +            throw new AssertionFailedError("timed get did not return promptly");
1097 +    }
1098 +
1099 +    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1100 +        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1101 +    }
1102 +
1103      /**
1104       * Returns a new started daemon Thread running the given runnable.
1105       */
# Line 655 | Line 1118 | public class JSR166TestCase extends Test
1118      void awaitTermination(Thread t, long timeoutMillis) {
1119          try {
1120              t.join(timeoutMillis);
1121 <        } catch (InterruptedException ie) {
1122 <            threadUnexpectedException(ie);
1121 >        } catch (InterruptedException fail) {
1122 >            threadUnexpectedException(fail);
1123          } finally {
1124 <            if (t.isAlive()) {
1124 >            if (t.getState() != Thread.State.TERMINATED) {
1125                  t.interrupt();
1126                  fail("Test timed out");
1127              }
1128          }
1129      }
1130  
1131 +    /**
1132 +     * Waits for LONG_DELAY_MS milliseconds for the thread to
1133 +     * terminate (using {@link Thread#join(long)}), else interrupts
1134 +     * the thread (in the hope that it may terminate later) and fails.
1135 +     */
1136 +    void awaitTermination(Thread t) {
1137 +        awaitTermination(t, LONG_DELAY_MS);
1138 +    }
1139 +
1140      // Some convenient Runnable classes
1141  
1142      public abstract class CheckedRunnable implements Runnable {
# Line 673 | Line 1145 | public class JSR166TestCase extends Test
1145          public final void run() {
1146              try {
1147                  realRun();
1148 <            } catch (Throwable t) {
1149 <                threadUnexpectedException(t);
1148 >            } catch (Throwable fail) {
1149 >                threadUnexpectedException(fail);
1150              }
1151          }
1152      }
# Line 727 | Line 1199 | public class JSR166TestCase extends Test
1199                  realRun();
1200                  threadShouldThrow("InterruptedException");
1201              } catch (InterruptedException success) {
1202 <            } catch (Throwable t) {
1203 <                threadUnexpectedException(t);
1202 >                threadAssertFalse(Thread.interrupted());
1203 >            } catch (Throwable fail) {
1204 >                threadUnexpectedException(fail);
1205              }
1206          }
1207      }
# Line 739 | Line 1212 | public class JSR166TestCase extends Test
1212          public final T call() {
1213              try {
1214                  return realCall();
1215 <            } catch (Throwable t) {
1216 <                threadUnexpectedException(t);
1215 >            } catch (Throwable fail) {
1216 >                threadUnexpectedException(fail);
1217                  return null;
1218              }
1219          }
# Line 756 | Line 1229 | public class JSR166TestCase extends Test
1229                  threadShouldThrow("InterruptedException");
1230                  return result;
1231              } catch (InterruptedException success) {
1232 <            } catch (Throwable t) {
1233 <                threadUnexpectedException(t);
1232 >                threadAssertFalse(Thread.interrupted());
1233 >            } catch (Throwable fail) {
1234 >                threadUnexpectedException(fail);
1235              }
1236              return null;
1237          }
# Line 774 | Line 1248 | public class JSR166TestCase extends Test
1248      public static final String TEST_STRING = "a test string";
1249  
1250      public static class StringTask implements Callable<String> {
1251 <        public String call() { return TEST_STRING; }
1251 >        final String value;
1252 >        public StringTask() { this(TEST_STRING); }
1253 >        public StringTask(String value) { this.value = value; }
1254 >        public String call() { return value; }
1255      }
1256  
1257      public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
# Line 787 | Line 1264 | public class JSR166TestCase extends Test
1264              }};
1265      }
1266  
1267 +    public Runnable countDowner(final CountDownLatch latch) {
1268 +        return new CheckedRunnable() {
1269 +            public void realRun() throws InterruptedException {
1270 +                latch.countDown();
1271 +            }};
1272 +    }
1273 +
1274 +    public Runnable awaiter(final CountDownLatch latch) {
1275 +        return new CheckedRunnable() {
1276 +            public void realRun() throws InterruptedException {
1277 +                await(latch);
1278 +            }};
1279 +    }
1280 +
1281 +    public void await(CountDownLatch latch) {
1282 +        try {
1283 +            assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1284 +        } catch (Throwable fail) {
1285 +            threadUnexpectedException(fail);
1286 +        }
1287 +    }
1288 +
1289 +    public void await(Semaphore semaphore) {
1290 +        try {
1291 +            assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1292 +        } catch (Throwable fail) {
1293 +            threadUnexpectedException(fail);
1294 +        }
1295 +    }
1296 +
1297 + //     /**
1298 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1299 + //      */
1300 + //     public void await(AtomicBoolean flag) {
1301 + //         await(flag, LONG_DELAY_MS);
1302 + //     }
1303 +
1304 + //     /**
1305 + //      * Spin-waits up to the specified timeout until flag becomes true.
1306 + //      */
1307 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1308 + //         long startTime = System.nanoTime();
1309 + //         while (!flag.get()) {
1310 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1311 + //                 throw new AssertionFailedError("timed out");
1312 + //             Thread.yield();
1313 + //         }
1314 + //     }
1315 +
1316      public static class NPETask implements Callable<String> {
1317          public String call() { throw new NullPointerException(); }
1318      }
# Line 797 | Line 1323 | public class JSR166TestCase extends Test
1323  
1324      public class ShortRunnable extends CheckedRunnable {
1325          protected void realRun() throws Throwable {
1326 <            Thread.sleep(SHORT_DELAY_MS);
1326 >            delay(SHORT_DELAY_MS);
1327          }
1328      }
1329  
1330      public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1331          protected void realRun() throws InterruptedException {
1332 <            Thread.sleep(SHORT_DELAY_MS);
1332 >            delay(SHORT_DELAY_MS);
1333          }
1334      }
1335  
1336      public class SmallRunnable extends CheckedRunnable {
1337          protected void realRun() throws Throwable {
1338 <            Thread.sleep(SMALL_DELAY_MS);
1338 >            delay(SMALL_DELAY_MS);
1339          }
1340      }
1341  
1342      public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1343          protected void realRun() {
1344              try {
1345 <                Thread.sleep(SMALL_DELAY_MS);
1345 >                delay(SMALL_DELAY_MS);
1346              } catch (InterruptedException ok) {}
1347          }
1348      }
1349  
1350      public class SmallCallable extends CheckedCallable {
1351          protected Object realCall() throws InterruptedException {
1352 <            Thread.sleep(SMALL_DELAY_MS);
1352 >            delay(SMALL_DELAY_MS);
1353              return Boolean.TRUE;
1354          }
1355      }
1356  
1357      public class MediumRunnable extends CheckedRunnable {
1358          protected void realRun() throws Throwable {
1359 <            Thread.sleep(MEDIUM_DELAY_MS);
1359 >            delay(MEDIUM_DELAY_MS);
1360          }
1361      }
1362  
1363      public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1364          protected void realRun() throws InterruptedException {
1365 <            Thread.sleep(MEDIUM_DELAY_MS);
1365 >            delay(MEDIUM_DELAY_MS);
1366          }
1367      }
1368  
# Line 844 | Line 1370 | public class JSR166TestCase extends Test
1370          return new CheckedRunnable() {
1371              protected void realRun() {
1372                  try {
1373 <                    Thread.sleep(timeoutMillis);
1373 >                    delay(timeoutMillis);
1374                  } catch (InterruptedException ok) {}
1375              }};
1376      }
# Line 852 | Line 1378 | public class JSR166TestCase extends Test
1378      public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1379          protected void realRun() {
1380              try {
1381 <                Thread.sleep(MEDIUM_DELAY_MS);
1381 >                delay(MEDIUM_DELAY_MS);
1382              } catch (InterruptedException ok) {}
1383          }
1384      }
# Line 860 | Line 1386 | public class JSR166TestCase extends Test
1386      public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1387          protected void realRun() {
1388              try {
1389 <                Thread.sleep(LONG_DELAY_MS);
1389 >                delay(LONG_DELAY_MS);
1390              } catch (InterruptedException ok) {}
1391          }
1392      }
# Line 884 | Line 1410 | public class JSR166TestCase extends Test
1410                  public boolean isDone() { return done; }
1411                  public void run() {
1412                      try {
1413 <                        Thread.sleep(timeoutMillis);
1413 >                        delay(timeoutMillis);
1414                          done = true;
1415                      } catch (InterruptedException ok) {}
1416                  }
# Line 895 | Line 1421 | public class JSR166TestCase extends Test
1421          public volatile boolean done = false;
1422          public void run() {
1423              try {
1424 <                Thread.sleep(SHORT_DELAY_MS);
1424 >                delay(SHORT_DELAY_MS);
1425                  done = true;
1426              } catch (InterruptedException ok) {}
1427          }
# Line 905 | Line 1431 | public class JSR166TestCase extends Test
1431          public volatile boolean done = false;
1432          public void run() {
1433              try {
1434 <                Thread.sleep(SMALL_DELAY_MS);
1434 >                delay(SMALL_DELAY_MS);
1435                  done = true;
1436              } catch (InterruptedException ok) {}
1437          }
# Line 915 | Line 1441 | public class JSR166TestCase extends Test
1441          public volatile boolean done = false;
1442          public void run() {
1443              try {
1444 <                Thread.sleep(MEDIUM_DELAY_MS);
1444 >                delay(MEDIUM_DELAY_MS);
1445                  done = true;
1446              } catch (InterruptedException ok) {}
1447          }
# Line 925 | Line 1451 | public class JSR166TestCase extends Test
1451          public volatile boolean done = false;
1452          public void run() {
1453              try {
1454 <                Thread.sleep(LONG_DELAY_MS);
1454 >                delay(LONG_DELAY_MS);
1455                  done = true;
1456              } catch (InterruptedException ok) {}
1457          }
# Line 942 | Line 1468 | public class JSR166TestCase extends Test
1468          public volatile boolean done = false;
1469          public Object call() {
1470              try {
1471 <                Thread.sleep(SMALL_DELAY_MS);
1471 >                delay(SMALL_DELAY_MS);
1472                  done = true;
1473              } catch (InterruptedException ok) {}
1474              return Boolean.TRUE;
# Line 955 | Line 1481 | public class JSR166TestCase extends Test
1481      public abstract class CheckedRecursiveAction extends RecursiveAction {
1482          protected abstract void realCompute() throws Throwable;
1483  
1484 <        public final void compute() {
1484 >        @Override protected final void compute() {
1485              try {
1486                  realCompute();
1487 <            } catch (Throwable t) {
1488 <                threadUnexpectedException(t);
1487 >            } catch (Throwable fail) {
1488 >                threadUnexpectedException(fail);
1489              }
1490          }
1491      }
# Line 970 | Line 1496 | public class JSR166TestCase extends Test
1496      public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1497          protected abstract T realCompute() throws Throwable;
1498  
1499 <        public final T compute() {
1499 >        @Override protected final T compute() {
1500              try {
1501                  return realCompute();
1502 <            } catch (Throwable t) {
1503 <                threadUnexpectedException(t);
1502 >            } catch (Throwable fail) {
1503 >                threadUnexpectedException(fail);
1504                  return null;
1505              }
1506          }
# Line 989 | Line 1515 | public class JSR166TestCase extends Test
1515      }
1516  
1517      /**
1518 <     * A CyclicBarrier that fails with AssertionFailedErrors instead
1519 <     * of throwing checked exceptions.
1518 >     * A CyclicBarrier that uses timed await and fails with
1519 >     * AssertionFailedErrors instead of throwing checked exceptions.
1520       */
1521      public class CheckedBarrier extends CyclicBarrier {
1522          public CheckedBarrier(int parties) { super(parties); }
1523  
1524          public int await() {
1525              try {
1526 <                return super.await();
1527 <            } catch (Exception e) {
1526 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1527 >            } catch (TimeoutException timedOut) {
1528 >                throw new AssertionFailedError("timed out");
1529 >            } catch (Exception fail) {
1530                  AssertionFailedError afe =
1531 <                    new AssertionFailedError("Unexpected exception: " + e);
1532 <                afe.initCause(e);
1531 >                    new AssertionFailedError("Unexpected exception: " + fail);
1532 >                afe.initCause(fail);
1533                  throw afe;
1534              }
1535          }
1536      }
1537  
1538 +    void checkEmpty(BlockingQueue q) {
1539 +        try {
1540 +            assertTrue(q.isEmpty());
1541 +            assertEquals(0, q.size());
1542 +            assertNull(q.peek());
1543 +            assertNull(q.poll());
1544 +            assertNull(q.poll(0, MILLISECONDS));
1545 +            assertEquals(q.toString(), "[]");
1546 +            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1547 +            assertFalse(q.iterator().hasNext());
1548 +            try {
1549 +                q.element();
1550 +                shouldThrow();
1551 +            } catch (NoSuchElementException success) {}
1552 +            try {
1553 +                q.iterator().next();
1554 +                shouldThrow();
1555 +            } catch (NoSuchElementException success) {}
1556 +            try {
1557 +                q.remove();
1558 +                shouldThrow();
1559 +            } catch (NoSuchElementException success) {}
1560 +        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1561 +    }
1562 +
1563 +    void assertSerialEquals(Object x, Object y) {
1564 +        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1565 +    }
1566 +
1567 +    void assertNotSerialEquals(Object x, Object y) {
1568 +        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1569 +    }
1570 +
1571 +    byte[] serialBytes(Object o) {
1572 +        try {
1573 +            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1574 +            ObjectOutputStream oos = new ObjectOutputStream(bos);
1575 +            oos.writeObject(o);
1576 +            oos.flush();
1577 +            oos.close();
1578 +            return bos.toByteArray();
1579 +        } catch (Throwable fail) {
1580 +            threadUnexpectedException(fail);
1581 +            return new byte[0];
1582 +        }
1583 +    }
1584 +
1585 +    @SuppressWarnings("unchecked")
1586 +    <T> T serialClone(T o) {
1587 +        try {
1588 +            ObjectInputStream ois = new ObjectInputStream
1589 +                (new ByteArrayInputStream(serialBytes(o)));
1590 +            T clone = (T) ois.readObject();
1591 +            assertSame(o.getClass(), clone.getClass());
1592 +            return clone;
1593 +        } catch (Throwable fail) {
1594 +            threadUnexpectedException(fail);
1595 +            return null;
1596 +        }
1597 +    }
1598 +
1599 +    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1600 +                             Runnable... throwingActions) {
1601 +        for (Runnable throwingAction : throwingActions) {
1602 +            boolean threw = false;
1603 +            try { throwingAction.run(); }
1604 +            catch (Throwable t) {
1605 +                threw = true;
1606 +                if (!expectedExceptionClass.isInstance(t)) {
1607 +                    AssertionFailedError afe =
1608 +                        new AssertionFailedError
1609 +                        ("Expected " + expectedExceptionClass.getName() +
1610 +                         ", got " + t.getClass().getName());
1611 +                    afe.initCause(t);
1612 +                    threadUnexpectedException(afe);
1613 +                }
1614 +            }
1615 +            if (!threw)
1616 +                shouldThrow(expectedExceptionClass.getName());
1617 +        }
1618 +    }
1619 +
1620 +    public void assertIteratorExhausted(Iterator<?> it) {
1621 +        try {
1622 +            it.next();
1623 +            shouldThrow();
1624 +        } catch (NoSuchElementException success) {}
1625 +        assertFalse(it.hasNext());
1626 +    }
1627   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines