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.3 by dl, Sat Sep 20 18:20:08 2003 UTC vs.
Revision 1.181 by jsr166, Mon Nov 9 06:06:54 2015 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
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/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.*;
11 < import java.util.concurrent.*;
12 < import java.io.*;
13 <
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 > import static java.util.concurrent.TimeUnit.MINUTES;
11 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
12 >
13 > import java.io.ByteArrayInputStream;
14 > import java.io.ByteArrayOutputStream;
15 > import java.io.ObjectInputStream;
16 > import java.io.ObjectOutputStream;
17 > import java.lang.management.ManagementFactory;
18 > import java.lang.management.ThreadInfo;
19 > import java.lang.management.ThreadMXBean;
20 > import java.lang.reflect.Constructor;
21 > import java.lang.reflect.Method;
22 > import java.lang.reflect.Modifier;
23 > import java.nio.file.Files;
24 > import java.nio.file.Paths;
25 > import java.security.CodeSource;
26 > import java.security.Permission;
27 > import java.security.PermissionCollection;
28 > import java.security.Permissions;
29 > import java.security.Policy;
30 > import java.security.ProtectionDomain;
31 > import java.security.SecurityPermission;
32 > import java.util.ArrayList;
33 > import java.util.Arrays;
34 > import java.util.Date;
35 > import java.util.Enumeration;
36 > import java.util.Iterator;
37 > import java.util.List;
38 > import java.util.NoSuchElementException;
39 > import java.util.PropertyPermission;
40 > import java.util.concurrent.BlockingQueue;
41 > import java.util.concurrent.Callable;
42 > import java.util.concurrent.CountDownLatch;
43 > import java.util.concurrent.CyclicBarrier;
44 > import java.util.concurrent.ExecutionException;
45 > import java.util.concurrent.Executors;
46 > import java.util.concurrent.ExecutorService;
47 > import java.util.concurrent.ForkJoinPool;
48 > import java.util.concurrent.Future;
49 > import java.util.concurrent.RecursiveAction;
50 > import java.util.concurrent.RecursiveTask;
51 > import java.util.concurrent.RejectedExecutionHandler;
52 > import java.util.concurrent.Semaphore;
53 > import java.util.concurrent.ThreadFactory;
54 > import java.util.concurrent.ThreadPoolExecutor;
55 > import java.util.concurrent.TimeoutException;
56 > import java.util.concurrent.atomic.AtomicReference;
57 > import java.util.regex.Matcher;
58 > import java.util.regex.Pattern;
59 >
60 > import junit.framework.AssertionFailedError;
61 > import junit.framework.Test;
62 > import junit.framework.TestCase;
63 > import junit.framework.TestResult;
64 > import junit.framework.TestSuite;
65  
66   /**
67 < * Base class for JSR166 Junit TCK tests.  Defines some constants and
68 < * utility methods, as well as a simple framework for helping to make
69 < * sure that assertions failing in generated threads cause the
70 < * associated test that generated them to itself fail (which JUnit doe
71 < * not otherwise arrange).  The rules for creating such tests are:
67 > * Base class for JSR166 Junit TCK tests.  Defines some constants,
68 > * utility methods and classes, as well as a simple framework for
69 > * helping to make sure that assertions failing in generated threads
70 > * cause the associated test that generated them to itself fail (which
71 > * JUnit does not otherwise arrange).  The rules for creating such
72 > * tests are:
73   *
74   * <ol>
75   *
76 < * <li> All assertions in code running in generated threads must use
77 < * the forms {@link threadFail} , {@link threadAssertTrue} {@link
78 < * threadAssertEquals}, or {@link threadAssertNull}, (not
79 < * <tt>fail</tt>, <tt>assertTrue</tt>, etc.) It is OK (but not
76 > * <li>All assertions in code running in generated threads must use
77 > * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
78 > * #threadAssertEquals}, or {@link #threadAssertNull}, (not
79 > * {@code fail}, {@code assertTrue}, etc.) It is OK (but not
80   * particularly recommended) for other code to use these forms too.
81   * Only the most typically used JUnit assertion methods are defined
82 < * this way, but enough to live with.</li>
82 > * this way, but enough to live with.
83   *
84 < * <li> If you override {@link setUp} or {@link tearDown}, make sure
85 < * to invoke <tt>super.setUp</tt> and <tt>super.tearDown</tt> within
84 > * <li>If you override {@link #setUp} or {@link #tearDown}, make sure
85 > * to invoke {@code super.setUp} and {@code super.tearDown} within
86   * them. These methods are used to clear and check for thread
87 < * assertion failures.</li>
87 > * assertion failures.
88   *
89 < * <li>All delays and timeouts must use one of the constants {@link
90 < * SHORT_DELAY_MS}, {@link SMALL_DELAY_MS}, {@link MEDIUM_DELAY_MS},
91 < * {@link LONG_DELAY_MS}. The idea here is that a SHORT is always
92 < * discriminatable from zero time, and always allows enough time for
93 < * the small amounts of computation (creating a thread, calling a few
89 > * <li>All delays and timeouts must use one of the constants {@code
90 > * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
91 > * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
92 > * discriminable from zero time, and always allows enough time for the
93 > * small amounts of computation (creating a thread, calling a few
94   * methods, etc) needed to reach a timeout point. Similarly, a SMALL
95   * is always discriminable as larger than SHORT and smaller than
96   * MEDIUM.  And so on. These constants are set to conservative values,
97   * but even so, if there is ever any doubt, they can all be increased
98 < * in one spot to rerun tests on slower platforms</li>
98 > * in one spot to rerun tests on slower platforms.
99   *
100 < * <li> All threads generated must be joined inside each test case
101 < * method (or <tt>fail</tt> to do so) before returning from the
102 < * method. The {@link joinPool} method can be used to do this when
103 < * using Executors.</li>
100 > * <li>All threads generated must be joined inside each test case
101 > * method (or {@code fail} to do so) before returning from the
102 > * method. The {@code joinPool} method can be used to do this when
103 > * using Executors.
104   *
105   * </ol>
106 + *
107 + * <p><b>Other notes</b>
108 + * <ul>
109 + *
110 + * <li>Usually, there is one testcase method per JSR166 method
111 + * covering "normal" operation, and then as many exception-testing
112 + * methods as there are exceptions the method can throw. Sometimes
113 + * there are multiple tests per JSR166 method when the different
114 + * "normal" behaviors differ significantly. And sometimes testcases
115 + * cover multiple methods when they cannot be tested in isolation.
116 + *
117 + * <li>The documentation style for testcases is to provide as javadoc
118 + * a simple sentence or two describing the property that the testcase
119 + * method purports to test. The javadocs do not say anything about how
120 + * the property is tested. To find out, read the code.
121 + *
122 + * <li>These tests are "conformance tests", and do not attempt to
123 + * test throughput, latency, scalability or other performance factors
124 + * (see the separate "jtreg" tests for a set intended to check these
125 + * for the most central aspects of functionality.) So, most tests use
126 + * the smallest sensible numbers of threads, collection sizes, etc
127 + * needed to check basic conformance.
128 + *
129 + * <li>The test classes currently do not declare inclusion in
130 + * any particular package to simplify things for people integrating
131 + * them in TCK test suites.
132 + *
133 + * <li>As a convenience, the {@code main} of this class (JSR166TestCase)
134 + * runs all JSR166 unit tests.
135 + *
136 + * </ul>
137   */
138   public class JSR166TestCase extends TestCase {
139 +    private static final boolean useSecurityManager =
140 +        Boolean.getBoolean("jsr166.useSecurityManager");
141 +
142 +    protected static final boolean expensiveTests =
143 +        Boolean.getBoolean("jsr166.expensiveTests");
144 +
145 +    /**
146 +     * If true, also run tests that are not part of the official tck
147 +     * because they test unspecified implementation details.
148 +     */
149 +    protected static final boolean testImplementationDetails =
150 +        Boolean.getBoolean("jsr166.testImplementationDetails");
151 +
152 +    /**
153 +     * If true, report on stdout all "slow" tests, that is, ones that
154 +     * take more than profileThreshold milliseconds to execute.
155 +     */
156 +    private static final boolean profileTests =
157 +        Boolean.getBoolean("jsr166.profileTests");
158 +
159 +    /**
160 +     * The number of milliseconds that tests are permitted for
161 +     * execution without being reported, when profileTests is set.
162 +     */
163 +    private static final long profileThreshold =
164 +        Long.getLong("jsr166.profileThreshold", 100);
165 +
166 +    /**
167 +     * The number of repetitions per test (for tickling rare bugs).
168 +     */
169 +    private static final int runsPerTest =
170 +        Integer.getInteger("jsr166.runsPerTest", 1);
171 +
172 +    /**
173 +     * The number of repetitions of the test suite (for finding leaks?).
174 +     */
175 +    private static final int suiteRuns =
176 +        Integer.getInteger("jsr166.suiteRuns", 1);
177 +
178 +    /**
179 +     * The scaling factor to apply to standard delays used in tests.
180 +     */
181 +    private static final int delayFactor =
182 +        Integer.getInteger("jsr166.delay.factor", 1);
183 +
184 +    public JSR166TestCase() { super(); }
185 +    public JSR166TestCase(String name) { super(name); }
186 +
187 +    /**
188 +     * A filter for tests to run, matching strings of the form
189 +     * methodName(className), e.g. "testInvokeAll5(ForkJoinPoolTest)"
190 +     * Usefully combined with jsr166.runsPerTest.
191 +     */
192 +    private static final Pattern methodFilter = methodFilter();
193 +
194 +    private static Pattern methodFilter() {
195 +        String regex = System.getProperty("jsr166.methodFilter");
196 +        return (regex == null) ? null : Pattern.compile(regex);
197 +    }
198 +
199 +    // Instrumentation to debug very rare, but very annoying hung test runs.
200 +    static volatile TestCase currentTestCase;
201 +    // static volatile int currentRun = 0;
202 +    static {
203 +        Runnable checkForWedgedTest = new Runnable() { public void run() {
204 +            // Avoid spurious reports with enormous runsPerTest.
205 +            // A single test case run should never take more than 1 second.
206 +            // But let's cap it at the high end too ...
207 +            final int timeoutMinutes =
208 +                Math.min(15, Math.max(runsPerTest / 60, 1));
209 +            for (TestCase lastTestCase = currentTestCase;;) {
210 +                try { MINUTES.sleep(timeoutMinutes); }
211 +                catch (InterruptedException unexpected) { break; }
212 +                if (lastTestCase == currentTestCase) {
213 +                    System.err.printf(
214 +                        "Looks like we're stuck running test: %s%n",
215 +                        lastTestCase);
216 + //                     System.err.printf(
217 + //                         "Looks like we're stuck running test: %s (%d/%d)%n",
218 + //                         lastTestCase, currentRun, runsPerTest);
219 + //                     System.err.println("availableProcessors=" +
220 + //                         Runtime.getRuntime().availableProcessors());
221 + //                     System.err.printf("cpu model = %s%n", cpuModel());
222 +                    dumpTestThreads();
223 +                    // one stack dump is probably enough; more would be spam
224 +                    break;
225 +                }
226 +                lastTestCase = currentTestCase;
227 +            }}};
228 +        Thread thread = new Thread(checkForWedgedTest, "checkForWedgedTest");
229 +        thread.setDaemon(true);
230 +        thread.start();
231 +    }
232 +
233 + //     public static String cpuModel() {
234 + //         try {
235 + //             Matcher matcher = Pattern.compile("model name\\s*: (.*)")
236 + //                 .matcher(new String(
237 + //                      Files.readAllBytes(Paths.get("/proc/cpuinfo")), "UTF-8"));
238 + //             matcher.find();
239 + //             return matcher.group(1);
240 + //         } catch (Exception ex) { return null; }
241 + //     }
242 +
243 +    public void runBare() throws Throwable {
244 +        currentTestCase = this;
245 +        if (methodFilter == null
246 +            || methodFilter.matcher(toString()).find())
247 +            super.runBare();
248 +    }
249 +
250 +    protected void runTest() throws Throwable {
251 +        for (int i = 0; i < runsPerTest; i++) {
252 +            // currentRun = i;
253 +            if (profileTests)
254 +                runTestProfiled();
255 +            else
256 +                super.runTest();
257 +        }
258 +    }
259 +
260 +    protected void runTestProfiled() throws Throwable {
261 +        for (int i = 0; i < 2; i++) {
262 +            long startTime = System.nanoTime();
263 +            super.runTest();
264 +            long elapsedMillis = millisElapsedSince(startTime);
265 +            if (elapsedMillis < profileThreshold)
266 +                break;
267 +            // Never report first run of any test; treat it as a
268 +            // warmup run, notably to trigger all needed classloading,
269 +            if (i > 0)
270 +                System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
271 +        }
272 +    }
273 +
274 +    /**
275 +     * Runs all JSR166 unit tests using junit.textui.TestRunner.
276 +     */
277 +    public static void main(String[] args) {
278 +        main(suite(), args);
279 +    }
280 +
281 +    static class PithyResultPrinter extends junit.textui.ResultPrinter {
282 +        PithyResultPrinter(java.io.PrintStream writer) { super(writer); }
283 +        long runTime;
284 +        public void startTest(Test test) {}
285 +        protected void printHeader(long runTime) {
286 +            this.runTime = runTime; // defer printing for later
287 +        }
288 +        protected void printFooter(TestResult result) {
289 +            if (result.wasSuccessful()) {
290 +                getWriter().println("OK (" + result.runCount() + " tests)"
291 +                    + "  Time: " + elapsedTimeAsString(runTime));
292 +            } else {
293 +                getWriter().println("Time: " + elapsedTimeAsString(runTime));
294 +                super.printFooter(result);
295 +            }
296 +        }
297 +    }
298 +
299 +    /**
300 +     * Returns a TestRunner that doesn't bother with unnecessary
301 +     * fluff, like printing a "." for each test case.
302 +     */
303 +    static junit.textui.TestRunner newPithyTestRunner() {
304 +        junit.textui.TestRunner runner = new junit.textui.TestRunner();
305 +        runner.setPrinter(new PithyResultPrinter(System.out));
306 +        return runner;
307 +    }
308 +
309 +    /**
310 +     * Runs all unit tests in the given test suite.
311 +     * Actual behavior influenced by jsr166.* system properties.
312 +     */
313 +    static void main(Test suite, String[] args) {
314 +        if (useSecurityManager) {
315 +            System.err.println("Setting a permissive security manager");
316 +            Policy.setPolicy(permissivePolicy());
317 +            System.setSecurityManager(new SecurityManager());
318 +        }
319 +        for (int i = 0; i < suiteRuns; i++) {
320 +            TestResult result = newPithyTestRunner().doRun(suite);
321 +            if (!result.wasSuccessful())
322 +                System.exit(1);
323 +            System.gc();
324 +            System.runFinalization();
325 +        }
326 +    }
327 +
328 +    public static TestSuite newTestSuite(Object... suiteOrClasses) {
329 +        TestSuite suite = new TestSuite();
330 +        for (Object suiteOrClass : suiteOrClasses) {
331 +            if (suiteOrClass instanceof TestSuite)
332 +                suite.addTest((TestSuite) suiteOrClass);
333 +            else if (suiteOrClass instanceof Class)
334 +                suite.addTest(new TestSuite((Class<?>) suiteOrClass));
335 +            else
336 +                throw new ClassCastException("not a test suite or class");
337 +        }
338 +        return suite;
339 +    }
340 +
341 +    public static void addNamedTestClasses(TestSuite suite,
342 +                                           String... testClassNames) {
343 +        for (String testClassName : testClassNames) {
344 +            try {
345 +                Class<?> testClass = Class.forName(testClassName);
346 +                Method m = testClass.getDeclaredMethod("suite",
347 +                                                       new Class<?>[0]);
348 +                suite.addTest(newTestSuite((Test)m.invoke(null)));
349 +            } catch (Exception e) {
350 +                throw new Error("Missing test class", e);
351 +            }
352 +        }
353 +    }
354 +
355 +    public static final double JAVA_CLASS_VERSION;
356 +    public static final String JAVA_SPECIFICATION_VERSION;
357 +    static {
358 +        try {
359 +            JAVA_CLASS_VERSION = java.security.AccessController.doPrivileged(
360 +                new java.security.PrivilegedAction<Double>() {
361 +                public Double run() {
362 +                    return Double.valueOf(System.getProperty("java.class.version"));}});
363 +            JAVA_SPECIFICATION_VERSION = java.security.AccessController.doPrivileged(
364 +                new java.security.PrivilegedAction<String>() {
365 +                public String run() {
366 +                    return System.getProperty("java.specification.version");}});
367 +        } catch (Throwable t) {
368 +            throw new Error(t);
369 +        }
370 +    }
371 +
372 +    public static boolean atLeastJava6() { return JAVA_CLASS_VERSION >= 50.0; }
373 +    public static boolean atLeastJava7() { return JAVA_CLASS_VERSION >= 51.0; }
374 +    public static boolean atLeastJava8() { return JAVA_CLASS_VERSION >= 52.0; }
375 +    public static boolean atLeastJava9() {
376 +        return JAVA_CLASS_VERSION >= 53.0
377 +            // As of 2015-09, java9 still uses 52.0 class file version
378 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?(9|[0-9][0-9])$");
379 +    }
380 +    public static boolean atLeastJava10() {
381 +        return JAVA_CLASS_VERSION >= 54.0
382 +            || JAVA_SPECIFICATION_VERSION.matches("^(1\\.)?[0-9][0-9]$");
383 +    }
384 +
385 +    /**
386 +     * Collects all JSR166 unit tests as one suite.
387 +     */
388 +    public static Test suite() {
389 +        // Java7+ test classes
390 +        TestSuite suite = newTestSuite(
391 +            ForkJoinPoolTest.suite(),
392 +            ForkJoinTaskTest.suite(),
393 +            RecursiveActionTest.suite(),
394 +            RecursiveTaskTest.suite(),
395 +            LinkedTransferQueueTest.suite(),
396 +            PhaserTest.suite(),
397 +            ThreadLocalRandomTest.suite(),
398 +            AbstractExecutorServiceTest.suite(),
399 +            AbstractQueueTest.suite(),
400 +            AbstractQueuedSynchronizerTest.suite(),
401 +            AbstractQueuedLongSynchronizerTest.suite(),
402 +            ArrayBlockingQueueTest.suite(),
403 +            ArrayDequeTest.suite(),
404 +            AtomicBooleanTest.suite(),
405 +            AtomicIntegerArrayTest.suite(),
406 +            AtomicIntegerFieldUpdaterTest.suite(),
407 +            AtomicIntegerTest.suite(),
408 +            AtomicLongArrayTest.suite(),
409 +            AtomicLongFieldUpdaterTest.suite(),
410 +            AtomicLongTest.suite(),
411 +            AtomicMarkableReferenceTest.suite(),
412 +            AtomicReferenceArrayTest.suite(),
413 +            AtomicReferenceFieldUpdaterTest.suite(),
414 +            AtomicReferenceTest.suite(),
415 +            AtomicStampedReferenceTest.suite(),
416 +            ConcurrentHashMapTest.suite(),
417 +            ConcurrentLinkedDequeTest.suite(),
418 +            ConcurrentLinkedQueueTest.suite(),
419 +            ConcurrentSkipListMapTest.suite(),
420 +            ConcurrentSkipListSubMapTest.suite(),
421 +            ConcurrentSkipListSetTest.suite(),
422 +            ConcurrentSkipListSubSetTest.suite(),
423 +            CopyOnWriteArrayListTest.suite(),
424 +            CopyOnWriteArraySetTest.suite(),
425 +            CountDownLatchTest.suite(),
426 +            CyclicBarrierTest.suite(),
427 +            DelayQueueTest.suite(),
428 +            EntryTest.suite(),
429 +            ExchangerTest.suite(),
430 +            ExecutorsTest.suite(),
431 +            ExecutorCompletionServiceTest.suite(),
432 +            FutureTaskTest.suite(),
433 +            LinkedBlockingDequeTest.suite(),
434 +            LinkedBlockingQueueTest.suite(),
435 +            LinkedListTest.suite(),
436 +            LockSupportTest.suite(),
437 +            PriorityBlockingQueueTest.suite(),
438 +            PriorityQueueTest.suite(),
439 +            ReentrantLockTest.suite(),
440 +            ReentrantReadWriteLockTest.suite(),
441 +            ScheduledExecutorTest.suite(),
442 +            ScheduledExecutorSubclassTest.suite(),
443 +            SemaphoreTest.suite(),
444 +            SynchronousQueueTest.suite(),
445 +            SystemTest.suite(),
446 +            ThreadLocalTest.suite(),
447 +            ThreadPoolExecutorTest.suite(),
448 +            ThreadPoolExecutorSubclassTest.suite(),
449 +            ThreadTest.suite(),
450 +            TimeUnitTest.suite(),
451 +            TreeMapTest.suite(),
452 +            TreeSetTest.suite(),
453 +            TreeSubMapTest.suite(),
454 +            TreeSubSetTest.suite());
455 +
456 +        // Java8+ test classes
457 +        if (atLeastJava8()) {
458 +            String[] java8TestClassNames = {
459 +                "Atomic8Test",
460 +                "CompletableFutureTest",
461 +                "ConcurrentHashMap8Test",
462 +                "CountedCompleterTest",
463 +                "DoubleAccumulatorTest",
464 +                "DoubleAdderTest",
465 +                "ForkJoinPool8Test",
466 +                "ForkJoinTask8Test",
467 +                "LongAccumulatorTest",
468 +                "LongAdderTest",
469 +                "SplittableRandomTest",
470 +                "StampedLockTest",
471 +                "SubmissionPublisherTest",
472 +                "ThreadLocalRandom8Test",
473 +            };
474 +            addNamedTestClasses(suite, java8TestClassNames);
475 +        }
476 +
477 +        // Java9+ test classes
478 +        if (atLeastJava9()) {
479 +            String[] java9TestClassNames = {
480 +                // Currently empty, but expecting varhandle tests
481 +            };
482 +            addNamedTestClasses(suite, java9TestClassNames);
483 +        }
484 +
485 +        return suite;
486 +    }
487 +
488 +    /** Returns list of junit-style test method names in given class. */
489 +    public static ArrayList<String> testMethodNames(Class<?> testClass) {
490 +        Method[] methods = testClass.getDeclaredMethods();
491 +        ArrayList<String> names = new ArrayList<String>(methods.length);
492 +        for (Method method : methods) {
493 +            if (method.getName().startsWith("test")
494 +                && Modifier.isPublic(method.getModifiers())
495 +                // method.getParameterCount() requires jdk8+
496 +                && method.getParameterTypes().length == 0) {
497 +                names.add(method.getName());
498 +            }
499 +        }
500 +        return names;
501 +    }
502 +
503 +    /**
504 +     * Returns junit-style testSuite for the given test class, but
505 +     * parameterized by passing extra data to each test.
506 +     */
507 +    public static <ExtraData> Test parameterizedTestSuite
508 +        (Class<? extends JSR166TestCase> testClass,
509 +         Class<ExtraData> dataClass,
510 +         ExtraData data) {
511 +        try {
512 +            TestSuite suite = new TestSuite();
513 +            Constructor c =
514 +                testClass.getDeclaredConstructor(dataClass, String.class);
515 +            for (String methodName : testMethodNames(testClass))
516 +                suite.addTest((Test) c.newInstance(data, methodName));
517 +            return suite;
518 +        } catch (Exception e) {
519 +            throw new Error(e);
520 +        }
521 +    }
522 +
523 +    /**
524 +     * Returns junit-style testSuite for the jdk8 extension of the
525 +     * given test class, but parameterized by passing extra data to
526 +     * each test.  Uses reflection to allow compilation in jdk7.
527 +     */
528 +    public static <ExtraData> Test jdk8ParameterizedTestSuite
529 +        (Class<? extends JSR166TestCase> testClass,
530 +         Class<ExtraData> dataClass,
531 +         ExtraData data) {
532 +        if (atLeastJava8()) {
533 +            String name = testClass.getName();
534 +            String name8 = name.replaceAll("Test$", "8Test");
535 +            if (name.equals(name8)) throw new Error(name);
536 +            try {
537 +                return (Test)
538 +                    Class.forName(name8)
539 +                    .getMethod("testSuite", new Class[] { dataClass })
540 +                    .invoke(null, data);
541 +            } catch (Exception e) {
542 +                throw new Error(e);
543 +            }
544 +        } else {
545 +            return new TestSuite();
546 +        }
547 +    }
548 +
549 +    // Delays for timing-dependent tests, in milliseconds.
550  
551      public static long SHORT_DELAY_MS;
552      public static long SMALL_DELAY_MS;
553      public static long MEDIUM_DELAY_MS;
554      public static long LONG_DELAY_MS;
555  
61
556      /**
557 <     * Return the shortest timed delay. This could
558 <     * be reimplmented to use for example a Property.
559 <     */
557 >     * Returns the shortest timed delay. This can be scaled up for
558 >     * slow machines using the jsr166.delay.factor system property.
559 >     */
560      protected long getShortDelay() {
561 <        return 50;
561 >        return 50 * delayFactor;
562      }
563  
70
564      /**
565 <     * Set delays as multiples fo SHORT_DELAY.
565 >     * Sets delays as multiples of SHORT_DELAY.
566       */
567 <    protected  void setDelays() {
567 >    protected void setDelays() {
568          SHORT_DELAY_MS = getShortDelay();
569 <        SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
569 >        SMALL_DELAY_MS  = SHORT_DELAY_MS * 5;
570          MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
571 <        LONG_DELAY_MS = SHORT_DELAY_MS * 50;
571 >        LONG_DELAY_MS   = SHORT_DELAY_MS * 200;
572 >    }
573 >
574 >    /**
575 >     * Returns a timeout in milliseconds to be used in tests that
576 >     * verify that operations block or time out.
577 >     */
578 >    long timeoutMillis() {
579 >        return SHORT_DELAY_MS / 4;
580 >    }
581 >
582 >    /**
583 >     * Returns a new Date instance representing a time at least
584 >     * delayMillis milliseconds in the future.
585 >     */
586 >    Date delayedDate(long delayMillis) {
587 >        // Add 1 because currentTimeMillis is known to round into the past.
588 >        return new Date(System.currentTimeMillis() + delayMillis + 1);
589      }
590  
591      /**
592 <     * Flag set true if any threadAssert methods fail
592 >     * The first exception encountered if any threadAssertXXX method fails.
593       */
594 <    protected volatile boolean threadFailed;
594 >    private final AtomicReference<Throwable> threadFailure
595 >        = new AtomicReference<Throwable>(null);
596  
597      /**
598 <     * Initialize test to indicat that no thread assertions have failed
598 >     * Records an exception so that it can be rethrown later in the test
599 >     * harness thread, triggering a test case failure.  Only the first
600 >     * failure is recorded; subsequent calls to this method from within
601 >     * the same test have no effect.
602       */
603 <    public void setUp() {
603 >    public void threadRecordFailure(Throwable t) {
604 >        System.err.println(t);
605 >        dumpTestThreads();
606 >        threadFailure.compareAndSet(null, t);
607 >    }
608 >
609 >    public void setUp() {
610          setDelays();
611 <        threadFailed = false;  
611 >    }
612 >
613 >    void tearDownFail(String format, Object... args) {
614 >        String msg = toString() + ": " + String.format(format, args);
615 >        System.err.println(msg);
616 >        dumpTestThreads();
617 >        throw new AssertionFailedError(msg);
618 >    }
619 >
620 >    /**
621 >     * Extra checks that get done for all test cases.
622 >     *
623 >     * Triggers test case failure if any thread assertions have failed,
624 >     * by rethrowing, in the test harness thread, any exception recorded
625 >     * earlier by threadRecordFailure.
626 >     *
627 >     * Triggers test case failure if interrupt status is set in the main thread.
628 >     */
629 >    public void tearDown() throws Exception {
630 >        Throwable t = threadFailure.getAndSet(null);
631 >        if (t != null) {
632 >            if (t instanceof Error)
633 >                throw (Error) t;
634 >            else if (t instanceof RuntimeException)
635 >                throw (RuntimeException) t;
636 >            else if (t instanceof Exception)
637 >                throw (Exception) t;
638 >            else {
639 >                AssertionFailedError afe =
640 >                    new AssertionFailedError(t.toString());
641 >                afe.initCause(t);
642 >                throw afe;
643 >            }
644 >        }
645 >
646 >        if (Thread.interrupted())
647 >            tearDownFail("interrupt status set in main thread");
648 >
649 >        checkForkJoinPoolThreadLeaks();
650      }
651  
652      /**
653 <     * Trigger test case failure if any thread assertions have failed
653 >     * Finds missing PoolCleaners
654       */
655 <    public void tearDown() {
656 <        assertFalse(threadFailed);  
655 >    void checkForkJoinPoolThreadLeaks() throws InterruptedException {
656 >        Thread[] survivors = new Thread[7];
657 >        int count = Thread.enumerate(survivors);
658 >        for (int i = 0; i < count; i++) {
659 >            Thread thread = survivors[i];
660 >            String name = thread.getName();
661 >            if (name.startsWith("ForkJoinPool-")) {
662 >                // give thread some time to terminate
663 >                thread.join(LONG_DELAY_MS);
664 >                if (thread.isAlive())
665 >                    tearDownFail("Found leaked ForkJoinPool thread thread=%s",
666 >                                 thread);
667 >            }
668 >        }
669 >
670 >        if (!ForkJoinPool.commonPool()
671 >            .awaitQuiescence(LONG_DELAY_MS, MILLISECONDS))
672 >            tearDownFail("ForkJoin common pool thread stuck");
673      }
674  
675 +    /**
676 +     * Just like fail(reason), but additionally recording (using
677 +     * threadRecordFailure) any AssertionFailedError thrown, so that
678 +     * the current testcase will fail.
679 +     */
680      public void threadFail(String reason) {
681 <        threadFailed = true;
682 <        fail(reason);
681 >        try {
682 >            fail(reason);
683 >        } catch (AssertionFailedError t) {
684 >            threadRecordFailure(t);
685 >            throw t;
686 >        }
687      }
688  
689 +    /**
690 +     * Just like assertTrue(b), but additionally recording (using
691 +     * threadRecordFailure) any AssertionFailedError thrown, so that
692 +     * the current testcase will fail.
693 +     */
694      public void threadAssertTrue(boolean b) {
695 <        if (!b) {
108 <            threadFailed = true;
695 >        try {
696              assertTrue(b);
697 +        } catch (AssertionFailedError t) {
698 +            threadRecordFailure(t);
699 +            throw t;
700          }
701      }
702 +
703 +    /**
704 +     * Just like assertFalse(b), but additionally recording (using
705 +     * threadRecordFailure) any AssertionFailedError thrown, so that
706 +     * the current testcase will fail.
707 +     */
708      public void threadAssertFalse(boolean b) {
709 <        if (b) {
114 <            threadFailed = true;
709 >        try {
710              assertFalse(b);
711 +        } catch (AssertionFailedError t) {
712 +            threadRecordFailure(t);
713 +            throw t;
714          }
715      }
716 +
717 +    /**
718 +     * Just like assertNull(x), but additionally recording (using
719 +     * threadRecordFailure) any AssertionFailedError thrown, so that
720 +     * the current testcase will fail.
721 +     */
722      public void threadAssertNull(Object x) {
723 <        if (x != null) {
120 <            threadFailed = true;
723 >        try {
724              assertNull(x);
725 +        } catch (AssertionFailedError t) {
726 +            threadRecordFailure(t);
727 +            throw t;
728          }
729      }
730 +
731 +    /**
732 +     * Just like assertEquals(x, y), but additionally recording (using
733 +     * threadRecordFailure) any AssertionFailedError thrown, so that
734 +     * the current testcase will fail.
735 +     */
736      public void threadAssertEquals(long x, long y) {
737 <        if (x != y) {
126 <            threadFailed = true;
737 >        try {
738              assertEquals(x, y);
739 +        } catch (AssertionFailedError t) {
740 +            threadRecordFailure(t);
741 +            throw t;
742          }
743      }
744 +
745 +    /**
746 +     * Just like assertEquals(x, y), but additionally recording (using
747 +     * threadRecordFailure) any AssertionFailedError thrown, so that
748 +     * the current testcase will fail.
749 +     */
750      public void threadAssertEquals(Object x, Object y) {
751 <        if (x != y && (x == null || !x.equals(y))) {
132 <            threadFailed = true;
751 >        try {
752              assertEquals(x, y);
753 +        } catch (AssertionFailedError fail) {
754 +            threadRecordFailure(fail);
755 +            throw fail;
756 +        } catch (Throwable fail) {
757 +            threadUnexpectedException(fail);
758 +        }
759 +    }
760 +
761 +    /**
762 +     * Just like assertSame(x, y), but additionally recording (using
763 +     * threadRecordFailure) any AssertionFailedError thrown, so that
764 +     * the current testcase will fail.
765 +     */
766 +    public void threadAssertSame(Object x, Object y) {
767 +        try {
768 +            assertSame(x, y);
769 +        } catch (AssertionFailedError fail) {
770 +            threadRecordFailure(fail);
771 +            throw fail;
772          }
773      }
774  
775 +    /**
776 +     * Calls threadFail with message "should throw exception".
777 +     */
778      public void threadShouldThrow() {
779 <        threadFailed = true;
780 <        fail("should throw exception");
779 >        threadFail("should throw exception");
780 >    }
781 >
782 >    /**
783 >     * Calls threadFail with message "should throw" + exceptionName.
784 >     */
785 >    public void threadShouldThrow(String exceptionName) {
786 >        threadFail("should throw " + exceptionName);
787 >    }
788 >
789 >    /**
790 >     * Records the given exception using {@link #threadRecordFailure},
791 >     * then rethrows the exception, wrapping it in an
792 >     * AssertionFailedError if necessary.
793 >     */
794 >    public void threadUnexpectedException(Throwable t) {
795 >        threadRecordFailure(t);
796 >        t.printStackTrace();
797 >        if (t instanceof RuntimeException)
798 >            throw (RuntimeException) t;
799 >        else if (t instanceof Error)
800 >            throw (Error) t;
801 >        else {
802 >            AssertionFailedError afe =
803 >                new AssertionFailedError("unexpected exception: " + t);
804 >            afe.initCause(t);
805 >            throw afe;
806 >        }
807 >    }
808 >
809 >    /**
810 >     * Delays, via Thread.sleep, for the given millisecond delay, but
811 >     * if the sleep is shorter than specified, may re-sleep or yield
812 >     * until time elapses.  Ensures that the given time, as measured
813 >     * by System.nanoTime(), has elapsed.
814 >     */
815 >    static void delay(long millis) throws InterruptedException {
816 >        long nanos = millis * (1000 * 1000);
817 >        final long wakeupTime = System.nanoTime() + nanos;
818 >        do {
819 >            if (millis > 0L)
820 >                Thread.sleep(millis);
821 >            else // too short to sleep
822 >                Thread.yield();
823 >            nanos = wakeupTime - System.nanoTime();
824 >            millis = nanos / (1000 * 1000);
825 >        } while (nanos >= 0L);
826 >    }
827 >
828 >    /**
829 >     * Allows use of try-with-resources with per-test thread pools.
830 >     */
831 >    class PoolCleaner implements AutoCloseable {
832 >        private final ExecutorService pool;
833 >        public PoolCleaner(ExecutorService pool) { this.pool = pool; }
834 >        public void close() { joinPool(pool); }
835 >    }
836 >
837 >    /**
838 >     * An extension of PoolCleaner that has an action to release the pool.
839 >     */
840 >    class PoolCleanerWithReleaser extends PoolCleaner {
841 >        private final Runnable releaser;
842 >        public PoolCleanerWithReleaser(ExecutorService pool, Runnable releaser) {
843 >            super(pool);
844 >            this.releaser = releaser;
845 >        }
846 >        public void close() {
847 >            try {
848 >                releaser.run();
849 >            } finally {
850 >                super.close();
851 >            }
852 >        }
853      }
854  
855 <    public void threadUnexpectedException() {
856 <        threadFailed = true;
144 <        fail("Unexpected exception");
855 >    PoolCleaner cleaner(ExecutorService pool) {
856 >        return new PoolCleaner(pool);
857      }
858  
859 +    PoolCleaner cleaner(ExecutorService pool, Runnable releaser) {
860 +        return new PoolCleanerWithReleaser(pool, releaser);
861 +    }
862 +
863 +    PoolCleaner cleaner(ExecutorService pool, CountDownLatch latch) {
864 +        return new PoolCleanerWithReleaser(pool, releaser(latch));
865 +    }
866 +
867 +    Runnable releaser(final CountDownLatch latch) {
868 +        return new Runnable() { public void run() {
869 +            do { latch.countDown(); }
870 +            while (latch.getCount() > 0);
871 +        }};
872 +    }
873  
874      /**
875 <     * Wait out termination of a thread pool or fail doing so
875 >     * Waits out termination of a thread pool or fails doing so.
876       */
877 <    public void joinPool(ExecutorService exec) {
877 >    void joinPool(ExecutorService pool) {
878          try {
879 <            exec.shutdown();
880 <            assertTrue(exec.awaitTermination(LONG_DELAY_MS, TimeUnit.MILLISECONDS));
881 <        } catch(InterruptedException ie) {
882 <            fail("Unexpected exception");
879 >            pool.shutdown();
880 >            if (!pool.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)) {
881 >                try {
882 >                    threadFail("ExecutorService " + pool +
883 >                               " did not terminate in a timely manner");
884 >                } finally {
885 >                    // last resort, for the benefit of subsequent tests
886 >                    pool.shutdownNow();
887 >                    pool.awaitTermination(MEDIUM_DELAY_MS, MILLISECONDS);
888 >                }
889 >            }
890 >        } catch (SecurityException ok) {
891 >            // Allowed in case test doesn't have privs
892 >        } catch (InterruptedException fail) {
893 >            threadFail("Unexpected InterruptedException");
894          }
895      }
896  
897 <    
897 >    /** Like Runnable, but with the freedom to throw anything */
898 >    interface Action { public void run() throws Throwable; }
899 >
900 >    /**
901 >     * Runs all the given actions in parallel, failing if any fail.
902 >     * Useful for running multiple variants of tests that are
903 >     * necessarily individually slow because they must block.
904 >     */
905 >    void testInParallel(Action ... actions) {
906 >        ExecutorService pool = Executors.newCachedThreadPool();
907 >        try (PoolCleaner cleaner = cleaner(pool)) {
908 >            ArrayList<Future<?>> futures = new ArrayList<>(actions.length);
909 >            for (final Action action : actions)
910 >                futures.add(pool.submit(new CheckedRunnable() {
911 >                    public void realRun() throws Throwable { action.run();}}));
912 >            for (Future<?> future : futures)
913 >                try {
914 >                    assertNull(future.get(LONG_DELAY_MS, MILLISECONDS));
915 >                } catch (ExecutionException ex) {
916 >                    threadUnexpectedException(ex.getCause());
917 >                } catch (Exception ex) {
918 >                    threadUnexpectedException(ex);
919 >                }
920 >        }
921 >    }
922 >
923 >    /**
924 >     * A debugging tool to print stack traces of most threads, as jstack does.
925 >     * Uninteresting threads are filtered out.
926 >     */
927 >    static void dumpTestThreads() {
928 >        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
929 >        System.err.println("------ stacktrace dump start ------");
930 >        for (ThreadInfo info : threadMXBean.dumpAllThreads(true, true)) {
931 >            String name = info.getThreadName();
932 >            if ("Signal Dispatcher".equals(name))
933 >                continue;
934 >            if ("Reference Handler".equals(name)
935 >                && info.getLockName().startsWith("java.lang.ref.Reference$Lock"))
936 >                continue;
937 >            if ("Finalizer".equals(name)
938 >                && info.getLockName().startsWith("java.lang.ref.ReferenceQueue$Lock"))
939 >                continue;
940 >            if ("checkForWedgedTest".equals(name))
941 >                continue;
942 >            System.err.print(info);
943 >        }
944 >        System.err.println("------ stacktrace dump end ------");
945 >    }
946 >
947 >    /**
948 >     * Checks that thread does not terminate within the default
949 >     * millisecond delay of {@code timeoutMillis()}.
950 >     */
951 >    void assertThreadStaysAlive(Thread thread) {
952 >        assertThreadStaysAlive(thread, timeoutMillis());
953 >    }
954 >
955 >    /**
956 >     * Checks that thread does not terminate within the given millisecond delay.
957 >     */
958 >    void assertThreadStaysAlive(Thread thread, long millis) {
959 >        try {
960 >            // No need to optimize the failing case via Thread.join.
961 >            delay(millis);
962 >            assertTrue(thread.isAlive());
963 >        } catch (InterruptedException fail) {
964 >            threadFail("Unexpected InterruptedException");
965 >        }
966 >    }
967 >
968 >    /**
969 >     * Checks that the threads do not terminate within the default
970 >     * millisecond delay of {@code timeoutMillis()}.
971 >     */
972 >    void assertThreadsStayAlive(Thread... threads) {
973 >        assertThreadsStayAlive(timeoutMillis(), threads);
974 >    }
975 >
976 >    /**
977 >     * Checks that the threads do not terminate within the given millisecond delay.
978 >     */
979 >    void assertThreadsStayAlive(long millis, Thread... threads) {
980 >        try {
981 >            // No need to optimize the failing case via Thread.join.
982 >            delay(millis);
983 >            for (Thread thread : threads)
984 >                assertTrue(thread.isAlive());
985 >        } catch (InterruptedException fail) {
986 >            threadFail("Unexpected InterruptedException");
987 >        }
988 >    }
989 >
990 >    /**
991 >     * Checks that future.get times out, with the default timeout of
992 >     * {@code timeoutMillis()}.
993 >     */
994 >    void assertFutureTimesOut(Future future) {
995 >        assertFutureTimesOut(future, timeoutMillis());
996 >    }
997 >
998 >    /**
999 >     * Checks that future.get times out, with the given millisecond timeout.
1000 >     */
1001 >    void assertFutureTimesOut(Future future, long timeoutMillis) {
1002 >        long startTime = System.nanoTime();
1003 >        try {
1004 >            future.get(timeoutMillis, MILLISECONDS);
1005 >            shouldThrow();
1006 >        } catch (TimeoutException success) {
1007 >        } catch (Exception fail) {
1008 >            threadUnexpectedException(fail);
1009 >        } finally { future.cancel(true); }
1010 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
1011 >    }
1012 >
1013 >    /**
1014 >     * Fails with message "should throw exception".
1015 >     */
1016      public void shouldThrow() {
1017          fail("Should throw exception");
1018      }
1019  
1020 <    public void unexpectedException() {
1021 <        fail("Unexpected exception");
1020 >    /**
1021 >     * Fails with message "should throw " + exceptionName.
1022 >     */
1023 >    public void shouldThrow(String exceptionName) {
1024 >        fail("Should throw " + exceptionName);
1025      }
1026  
169
1027      /**
1028       * The number of elements to place in collections, arrays, etc.
1029       */
# Line 174 | Line 1031 | public class JSR166TestCase extends Test
1031  
1032      // Some convenient Integer constants
1033  
1034 <    public static final Integer zero = new Integer(0);
1035 <    public static final Integer one = new Integer(1);
1036 <    public static final Integer two = new Integer(2);
1037 <    public static final Integer three  = new Integer(3);
1034 >    public static final Integer zero  = new Integer(0);
1035 >    public static final Integer one   = new Integer(1);
1036 >    public static final Integer two   = new Integer(2);
1037 >    public static final Integer three = new Integer(3);
1038      public static final Integer four  = new Integer(4);
1039      public static final Integer five  = new Integer(5);
1040 <    public static final Integer six = new Integer(6);
1040 >    public static final Integer six   = new Integer(6);
1041      public static final Integer seven = new Integer(7);
1042      public static final Integer eight = new Integer(8);
1043 <    public static final Integer nine = new Integer(9);
1043 >    public static final Integer nine  = new Integer(9);
1044      public static final Integer m1  = new Integer(-1);
1045      public static final Integer m2  = new Integer(-2);
1046      public static final Integer m3  = new Integer(-3);
1047 <    public static final Integer m4 = new Integer(-4);
1048 <    public static final Integer m5 = new Integer(-5);
1047 >    public static final Integer m4  = new Integer(-4);
1048 >    public static final Integer m5  = new Integer(-5);
1049 >    public static final Integer m6  = new Integer(-6);
1050      public static final Integer m10 = new Integer(-10);
1051  
1052 +    /**
1053 +     * Runs Runnable r with a security policy that permits precisely
1054 +     * the specified permissions.  If there is no current security
1055 +     * manager, the runnable is run twice, both with and without a
1056 +     * security manager.  We require that any security manager permit
1057 +     * getPolicy/setPolicy.
1058 +     */
1059 +    public void runWithPermissions(Runnable r, Permission... permissions) {
1060 +        SecurityManager sm = System.getSecurityManager();
1061 +        if (sm == null) {
1062 +            r.run();
1063 +        }
1064 +        runWithSecurityManagerWithPermissions(r, permissions);
1065 +    }
1066  
1067 <    // Some convenient Runnable classes
1067 >    /**
1068 >     * Runs Runnable r with a security policy that permits precisely
1069 >     * the specified permissions.  If there is no current security
1070 >     * manager, a temporary one is set for the duration of the
1071 >     * Runnable.  We require that any security manager permit
1072 >     * getPolicy/setPolicy.
1073 >     */
1074 >    public void runWithSecurityManagerWithPermissions(Runnable r,
1075 >                                                      Permission... permissions) {
1076 >        SecurityManager sm = System.getSecurityManager();
1077 >        if (sm == null) {
1078 >            Policy savedPolicy = Policy.getPolicy();
1079 >            try {
1080 >                Policy.setPolicy(permissivePolicy());
1081 >                System.setSecurityManager(new SecurityManager());
1082 >                runWithSecurityManagerWithPermissions(r, permissions);
1083 >            } finally {
1084 >                System.setSecurityManager(null);
1085 >                Policy.setPolicy(savedPolicy);
1086 >            }
1087 >        } else {
1088 >            Policy savedPolicy = Policy.getPolicy();
1089 >            AdjustablePolicy policy = new AdjustablePolicy(permissions);
1090 >            Policy.setPolicy(policy);
1091  
1092 <    public static class NoOpRunnable implements Runnable {
1093 <        public void run() {}
1092 >            try {
1093 >                r.run();
1094 >            } finally {
1095 >                policy.addPermission(new SecurityPermission("setPolicy"));
1096 >                Policy.setPolicy(savedPolicy);
1097 >            }
1098 >        }
1099      }
1100  
1101 <    public static class NoOpCallable implements Callable {
1102 <        public Object call() { return Boolean.TRUE; }
1101 >    /**
1102 >     * Runs a runnable without any permissions.
1103 >     */
1104 >    public void runWithoutPermissions(Runnable r) {
1105 >        runWithPermissions(r);
1106      }
1107  
1108 <    public class ShortRunnable implements Runnable {
1109 <        public void run() {
1110 <            try {
1111 <                Thread.sleep(SHORT_DELAY_MS);
1108 >    /**
1109 >     * A security policy where new permissions can be dynamically added
1110 >     * or all cleared.
1111 >     */
1112 >    public static class AdjustablePolicy extends java.security.Policy {
1113 >        Permissions perms = new Permissions();
1114 >        AdjustablePolicy(Permission... permissions) {
1115 >            for (Permission permission : permissions)
1116 >                perms.add(permission);
1117 >        }
1118 >        void addPermission(Permission perm) { perms.add(perm); }
1119 >        void clearPermissions() { perms = new Permissions(); }
1120 >        public PermissionCollection getPermissions(CodeSource cs) {
1121 >            return perms;
1122 >        }
1123 >        public PermissionCollection getPermissions(ProtectionDomain pd) {
1124 >            return perms;
1125 >        }
1126 >        public boolean implies(ProtectionDomain pd, Permission p) {
1127 >            return perms.implies(p);
1128 >        }
1129 >        public void refresh() {}
1130 >        public String toString() {
1131 >            List<Permission> ps = new ArrayList<Permission>();
1132 >            for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
1133 >                ps.add(e.nextElement());
1134 >            return "AdjustablePolicy with permissions " + ps;
1135 >        }
1136 >    }
1137 >
1138 >    /**
1139 >     * Returns a policy containing all the permissions we ever need.
1140 >     */
1141 >    public static Policy permissivePolicy() {
1142 >        return new AdjustablePolicy
1143 >            // Permissions j.u.c. needs directly
1144 >            (new RuntimePermission("modifyThread"),
1145 >             new RuntimePermission("getClassLoader"),
1146 >             new RuntimePermission("setContextClassLoader"),
1147 >             // Permissions needed to change permissions!
1148 >             new SecurityPermission("getPolicy"),
1149 >             new SecurityPermission("setPolicy"),
1150 >             new RuntimePermission("setSecurityManager"),
1151 >             // Permissions needed by the junit test harness
1152 >             new RuntimePermission("accessDeclaredMembers"),
1153 >             new PropertyPermission("*", "read"),
1154 >             new java.io.FilePermission("<<ALL FILES>>", "read"));
1155 >    }
1156 >
1157 >    /**
1158 >     * Sleeps until the given time has elapsed.
1159 >     * Throws AssertionFailedError if interrupted.
1160 >     */
1161 >    void sleep(long millis) {
1162 >        try {
1163 >            delay(millis);
1164 >        } catch (InterruptedException fail) {
1165 >            AssertionFailedError afe =
1166 >                new AssertionFailedError("Unexpected InterruptedException");
1167 >            afe.initCause(fail);
1168 >            throw afe;
1169 >        }
1170 >    }
1171 >
1172 >    /**
1173 >     * Spin-waits up to the specified number of milliseconds for the given
1174 >     * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
1175 >     */
1176 >    void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
1177 >        long startTime = System.nanoTime();
1178 >        for (;;) {
1179 >            Thread.State s = thread.getState();
1180 >            if (s == Thread.State.BLOCKED ||
1181 >                s == Thread.State.WAITING ||
1182 >                s == Thread.State.TIMED_WAITING)
1183 >                return;
1184 >            else if (s == Thread.State.TERMINATED)
1185 >                fail("Unexpected thread termination");
1186 >            else if (millisElapsedSince(startTime) > timeoutMillis) {
1187 >                threadAssertTrue(thread.isAlive());
1188 >                return;
1189              }
1190 <            catch(Exception e) {
1191 <                threadUnexpectedException();
1190 >            Thread.yield();
1191 >        }
1192 >    }
1193 >
1194 >    /**
1195 >     * Waits up to LONG_DELAY_MS for the given thread to enter a wait
1196 >     * state: BLOCKED, WAITING, or TIMED_WAITING.
1197 >     */
1198 >    void waitForThreadToEnterWaitState(Thread thread) {
1199 >        waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
1200 >    }
1201 >
1202 >    /**
1203 >     * Returns the number of milliseconds since time given by
1204 >     * startNanoTime, which must have been previously returned from a
1205 >     * call to {@link System#nanoTime()}.
1206 >     */
1207 >    static long millisElapsedSince(long startNanoTime) {
1208 >        return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
1209 >    }
1210 >
1211 > //     void assertTerminatesPromptly(long timeoutMillis, Runnable r) {
1212 > //         long startTime = System.nanoTime();
1213 > //         try {
1214 > //             r.run();
1215 > //         } catch (Throwable fail) { threadUnexpectedException(fail); }
1216 > //         if (millisElapsedSince(startTime) > timeoutMillis/2)
1217 > //             throw new AssertionFailedError("did not return promptly");
1218 > //     }
1219 >
1220 > //     void assertTerminatesPromptly(Runnable r) {
1221 > //         assertTerminatesPromptly(LONG_DELAY_MS/2, r);
1222 > //     }
1223 >
1224 >    /**
1225 >     * Checks that timed f.get() returns the expected value, and does not
1226 >     * wait for the timeout to elapse before returning.
1227 >     */
1228 >    <T> void checkTimedGet(Future<T> f, T expectedValue, long timeoutMillis) {
1229 >        long startTime = System.nanoTime();
1230 >        try {
1231 >            assertEquals(expectedValue, f.get(timeoutMillis, MILLISECONDS));
1232 >        } catch (Throwable fail) { threadUnexpectedException(fail); }
1233 >        if (millisElapsedSince(startTime) > timeoutMillis/2)
1234 >            throw new AssertionFailedError("timed get did not return promptly");
1235 >    }
1236 >
1237 >    <T> void checkTimedGet(Future<T> f, T expectedValue) {
1238 >        checkTimedGet(f, expectedValue, LONG_DELAY_MS);
1239 >    }
1240 >
1241 >    /**
1242 >     * Returns a new started daemon Thread running the given runnable.
1243 >     */
1244 >    Thread newStartedThread(Runnable runnable) {
1245 >        Thread t = new Thread(runnable);
1246 >        t.setDaemon(true);
1247 >        t.start();
1248 >        return t;
1249 >    }
1250 >
1251 >    /**
1252 >     * Waits for the specified time (in milliseconds) for the thread
1253 >     * to terminate (using {@link Thread#join(long)}), else interrupts
1254 >     * the thread (in the hope that it may terminate later) and fails.
1255 >     */
1256 >    void awaitTermination(Thread t, long timeoutMillis) {
1257 >        try {
1258 >            t.join(timeoutMillis);
1259 >        } catch (InterruptedException fail) {
1260 >            threadUnexpectedException(fail);
1261 >        } finally {
1262 >            if (t.getState() != Thread.State.TERMINATED) {
1263 >                t.interrupt();
1264 >                threadFail("timed out waiting for thread to terminate");
1265              }
1266          }
1267      }
1268  
1269 <    public class ShortInterruptedRunnable implements Runnable {
1270 <        public void run() {
1269 >    /**
1270 >     * Waits for LONG_DELAY_MS milliseconds for the thread to
1271 >     * terminate (using {@link Thread#join(long)}), else interrupts
1272 >     * the thread (in the hope that it may terminate later) and fails.
1273 >     */
1274 >    void awaitTermination(Thread t) {
1275 >        awaitTermination(t, LONG_DELAY_MS);
1276 >    }
1277 >
1278 >    // Some convenient Runnable classes
1279 >
1280 >    public abstract class CheckedRunnable implements Runnable {
1281 >        protected abstract void realRun() throws Throwable;
1282 >
1283 >        public final void run() {
1284              try {
1285 <                Thread.sleep(SHORT_DELAY_MS);
1286 <                threadShouldThrow();
1285 >                realRun();
1286 >            } catch (Throwable fail) {
1287 >                threadUnexpectedException(fail);
1288              }
1289 <            catch(InterruptedException success) {
1289 >        }
1290 >    }
1291 >
1292 >    public abstract class RunnableShouldThrow implements Runnable {
1293 >        protected abstract void realRun() throws Throwable;
1294 >
1295 >        final Class<?> exceptionClass;
1296 >
1297 >        <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
1298 >            this.exceptionClass = exceptionClass;
1299 >        }
1300 >
1301 >        public final void run() {
1302 >            try {
1303 >                realRun();
1304 >                threadShouldThrow(exceptionClass.getSimpleName());
1305 >            } catch (Throwable t) {
1306 >                if (! exceptionClass.isInstance(t))
1307 >                    threadUnexpectedException(t);
1308              }
1309          }
1310      }
1311  
1312 <    public class SmallRunnable implements Runnable {
1313 <        public void run() {
1312 >    public abstract class ThreadShouldThrow extends Thread {
1313 >        protected abstract void realRun() throws Throwable;
1314 >
1315 >        final Class<?> exceptionClass;
1316 >
1317 >        <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
1318 >            this.exceptionClass = exceptionClass;
1319 >        }
1320 >
1321 >        public final void run() {
1322              try {
1323 <                Thread.sleep(SMALL_DELAY_MS);
1323 >                realRun();
1324 >                threadShouldThrow(exceptionClass.getSimpleName());
1325 >            } catch (Throwable t) {
1326 >                if (! exceptionClass.isInstance(t))
1327 >                    threadUnexpectedException(t);
1328              }
1329 <            catch(Exception e) {
1330 <                threadUnexpectedException();
1329 >        }
1330 >    }
1331 >
1332 >    public abstract class CheckedInterruptedRunnable implements Runnable {
1333 >        protected abstract void realRun() throws Throwable;
1334 >
1335 >        public final void run() {
1336 >            try {
1337 >                realRun();
1338 >                threadShouldThrow("InterruptedException");
1339 >            } catch (InterruptedException success) {
1340 >                threadAssertFalse(Thread.interrupted());
1341 >            } catch (Throwable fail) {
1342 >                threadUnexpectedException(fail);
1343              }
1344          }
1345      }
1346  
1347 <    public class SmallCallable implements Callable {
1348 <        public Object call() {
1347 >    public abstract class CheckedCallable<T> implements Callable<T> {
1348 >        protected abstract T realCall() throws Throwable;
1349 >
1350 >        public final T call() {
1351              try {
1352 <                Thread.sleep(SMALL_DELAY_MS);
1352 >                return realCall();
1353 >            } catch (Throwable fail) {
1354 >                threadUnexpectedException(fail);
1355 >                return null;
1356              }
1357 <            catch(Exception e) {
1358 <                threadUnexpectedException();
1357 >        }
1358 >    }
1359 >
1360 >    public abstract class CheckedInterruptedCallable<T>
1361 >        implements Callable<T> {
1362 >        protected abstract T realCall() throws Throwable;
1363 >
1364 >        public final T call() {
1365 >            try {
1366 >                T result = realCall();
1367 >                threadShouldThrow("InterruptedException");
1368 >                return result;
1369 >            } catch (InterruptedException success) {
1370 >                threadAssertFalse(Thread.interrupted());
1371 >            } catch (Throwable fail) {
1372 >                threadUnexpectedException(fail);
1373              }
1374 +            return null;
1375 +        }
1376 +    }
1377 +
1378 +    public static class NoOpRunnable implements Runnable {
1379 +        public void run() {}
1380 +    }
1381 +
1382 +    public static class NoOpCallable implements Callable {
1383 +        public Object call() { return Boolean.TRUE; }
1384 +    }
1385 +
1386 +    public static final String TEST_STRING = "a test string";
1387 +
1388 +    public static class StringTask implements Callable<String> {
1389 +        final String value;
1390 +        public StringTask() { this(TEST_STRING); }
1391 +        public StringTask(String value) { this.value = value; }
1392 +        public String call() { return value; }
1393 +    }
1394 +
1395 +    public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
1396 +        return new CheckedCallable<String>() {
1397 +            protected String realCall() {
1398 +                try {
1399 +                    latch.await();
1400 +                } catch (InterruptedException quittingTime) {}
1401 +                return TEST_STRING;
1402 +            }};
1403 +    }
1404 +
1405 +    public Runnable countDowner(final CountDownLatch latch) {
1406 +        return new CheckedRunnable() {
1407 +            public void realRun() throws InterruptedException {
1408 +                latch.countDown();
1409 +            }};
1410 +    }
1411 +
1412 +    class LatchAwaiter extends CheckedRunnable {
1413 +        static final int NEW = 0;
1414 +        static final int RUNNING = 1;
1415 +        static final int DONE = 2;
1416 +        final CountDownLatch latch;
1417 +        int state = NEW;
1418 +        LatchAwaiter(CountDownLatch latch) { this.latch = latch; }
1419 +        public void realRun() throws InterruptedException {
1420 +            state = 1;
1421 +            await(latch);
1422 +            state = 2;
1423 +        }
1424 +    }
1425 +
1426 +    public LatchAwaiter awaiter(CountDownLatch latch) {
1427 +        return new LatchAwaiter(latch);
1428 +    }
1429 +
1430 +    public void await(CountDownLatch latch) {
1431 +        try {
1432 +            if (!latch.await(LONG_DELAY_MS, MILLISECONDS))
1433 +                fail("timed out waiting for CountDownLatch for "
1434 +                     + (LONG_DELAY_MS/1000) + " sec");
1435 +        } catch (Throwable fail) {
1436 +            threadUnexpectedException(fail);
1437 +        }
1438 +    }
1439 +
1440 +    public void await(Semaphore semaphore) {
1441 +        try {
1442 +            if (!semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS))
1443 +                fail("timed out waiting for Semaphore for "
1444 +                     + (LONG_DELAY_MS/1000) + " sec");
1445 +        } catch (Throwable fail) {
1446 +            threadUnexpectedException(fail);
1447 +        }
1448 +    }
1449 +
1450 + //     /**
1451 + //      * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1452 + //      */
1453 + //     public void await(AtomicBoolean flag) {
1454 + //         await(flag, LONG_DELAY_MS);
1455 + //     }
1456 +
1457 + //     /**
1458 + //      * Spin-waits up to the specified timeout until flag becomes true.
1459 + //      */
1460 + //     public void await(AtomicBoolean flag, long timeoutMillis) {
1461 + //         long startTime = System.nanoTime();
1462 + //         while (!flag.get()) {
1463 + //             if (millisElapsedSince(startTime) > timeoutMillis)
1464 + //                 throw new AssertionFailedError("timed out");
1465 + //             Thread.yield();
1466 + //         }
1467 + //     }
1468 +
1469 +    public static class NPETask implements Callable<String> {
1470 +        public String call() { throw new NullPointerException(); }
1471 +    }
1472 +
1473 +    public static class CallableOne implements Callable<Integer> {
1474 +        public Integer call() { return one; }
1475 +    }
1476 +
1477 +    public class ShortRunnable extends CheckedRunnable {
1478 +        protected void realRun() throws Throwable {
1479 +            delay(SHORT_DELAY_MS);
1480 +        }
1481 +    }
1482 +
1483 +    public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1484 +        protected void realRun() throws InterruptedException {
1485 +            delay(SHORT_DELAY_MS);
1486 +        }
1487 +    }
1488 +
1489 +    public class SmallRunnable extends CheckedRunnable {
1490 +        protected void realRun() throws Throwable {
1491 +            delay(SMALL_DELAY_MS);
1492 +        }
1493 +    }
1494 +
1495 +    public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1496 +        protected void realRun() {
1497 +            try {
1498 +                delay(SMALL_DELAY_MS);
1499 +            } catch (InterruptedException ok) {}
1500 +        }
1501 +    }
1502 +
1503 +    public class SmallCallable extends CheckedCallable {
1504 +        protected Object realCall() throws InterruptedException {
1505 +            delay(SMALL_DELAY_MS);
1506              return Boolean.TRUE;
1507          }
1508      }
1509  
1510 <    public class SmallInterruptedRunnable implements Runnable {
1510 >    public class MediumRunnable extends CheckedRunnable {
1511 >        protected void realRun() throws Throwable {
1512 >            delay(MEDIUM_DELAY_MS);
1513 >        }
1514 >    }
1515 >
1516 >    public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1517 >        protected void realRun() throws InterruptedException {
1518 >            delay(MEDIUM_DELAY_MS);
1519 >        }
1520 >    }
1521 >
1522 >    public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1523 >        return new CheckedRunnable() {
1524 >            protected void realRun() {
1525 >                try {
1526 >                    delay(timeoutMillis);
1527 >                } catch (InterruptedException ok) {}
1528 >            }};
1529 >    }
1530 >
1531 >    public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1532 >        protected void realRun() {
1533 >            try {
1534 >                delay(MEDIUM_DELAY_MS);
1535 >            } catch (InterruptedException ok) {}
1536 >        }
1537 >    }
1538 >
1539 >    public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1540 >        protected void realRun() {
1541 >            try {
1542 >                delay(LONG_DELAY_MS);
1543 >            } catch (InterruptedException ok) {}
1544 >        }
1545 >    }
1546 >
1547 >    /**
1548 >     * For use as ThreadFactory in constructors
1549 >     */
1550 >    public static class SimpleThreadFactory implements ThreadFactory {
1551 >        public Thread newThread(Runnable r) {
1552 >            return new Thread(r);
1553 >        }
1554 >    }
1555 >
1556 >    public interface TrackedRunnable extends Runnable {
1557 >        boolean isDone();
1558 >    }
1559 >
1560 >    public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1561 >        return new TrackedRunnable() {
1562 >                private volatile boolean done = false;
1563 >                public boolean isDone() { return done; }
1564 >                public void run() {
1565 >                    try {
1566 >                        delay(timeoutMillis);
1567 >                        done = true;
1568 >                    } catch (InterruptedException ok) {}
1569 >                }
1570 >            };
1571 >    }
1572 >
1573 >    public static class TrackedShortRunnable implements Runnable {
1574 >        public volatile boolean done = false;
1575          public void run() {
1576              try {
1577 <                Thread.sleep(SMALL_DELAY_MS);
1578 <                threadShouldThrow();
1579 <            }
256 <            catch(InterruptedException success) {
257 <            }
1577 >                delay(SHORT_DELAY_MS);
1578 >                done = true;
1579 >            } catch (InterruptedException ok) {}
1580          }
1581      }
1582  
1583 +    public static class TrackedSmallRunnable implements Runnable {
1584 +        public volatile boolean done = false;
1585 +        public void run() {
1586 +            try {
1587 +                delay(SMALL_DELAY_MS);
1588 +                done = true;
1589 +            } catch (InterruptedException ok) {}
1590 +        }
1591 +    }
1592  
1593 <    public class MediumRunnable implements Runnable {
1593 >    public static class TrackedMediumRunnable implements Runnable {
1594 >        public volatile boolean done = false;
1595          public void run() {
1596              try {
1597 <                Thread.sleep(MEDIUM_DELAY_MS);
1598 <            }
1599 <            catch(Exception e) {
268 <                threadUnexpectedException();
269 <            }
1597 >                delay(MEDIUM_DELAY_MS);
1598 >                done = true;
1599 >            } catch (InterruptedException ok) {}
1600          }
1601      }
1602  
1603 <    public class MediumInterruptedRunnable implements Runnable {
1603 >    public static class TrackedLongRunnable implements Runnable {
1604 >        public volatile boolean done = false;
1605          public void run() {
1606              try {
1607 <                Thread.sleep(MEDIUM_DELAY_MS);
1608 <                threadShouldThrow();
1607 >                delay(LONG_DELAY_MS);
1608 >                done = true;
1609 >            } catch (InterruptedException ok) {}
1610 >        }
1611 >    }
1612 >
1613 >    public static class TrackedNoOpRunnable implements Runnable {
1614 >        public volatile boolean done = false;
1615 >        public void run() {
1616 >            done = true;
1617 >        }
1618 >    }
1619 >
1620 >    public static class TrackedCallable implements Callable {
1621 >        public volatile boolean done = false;
1622 >        public Object call() {
1623 >            try {
1624 >                delay(SMALL_DELAY_MS);
1625 >                done = true;
1626 >            } catch (InterruptedException ok) {}
1627 >            return Boolean.TRUE;
1628 >        }
1629 >    }
1630 >
1631 >    /**
1632 >     * Analog of CheckedRunnable for RecursiveAction
1633 >     */
1634 >    public abstract class CheckedRecursiveAction extends RecursiveAction {
1635 >        protected abstract void realCompute() throws Throwable;
1636 >
1637 >        @Override protected final void compute() {
1638 >            try {
1639 >                realCompute();
1640 >            } catch (Throwable fail) {
1641 >                threadUnexpectedException(fail);
1642              }
1643 <            catch(InterruptedException success) {
1643 >        }
1644 >    }
1645 >
1646 >    /**
1647 >     * Analog of CheckedCallable for RecursiveTask
1648 >     */
1649 >    public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1650 >        protected abstract T realCompute() throws Throwable;
1651 >
1652 >        @Override protected final T compute() {
1653 >            try {
1654 >                return realCompute();
1655 >            } catch (Throwable fail) {
1656 >                threadUnexpectedException(fail);
1657 >                return null;
1658              }
1659          }
1660      }
1661  
1662 <    public class MediumPossiblyInterruptedRunnable implements Runnable {
1663 <        public void run() {
1662 >    /**
1663 >     * For use as RejectedExecutionHandler in constructors
1664 >     */
1665 >    public static class NoOpREHandler implements RejectedExecutionHandler {
1666 >        public void rejectedExecution(Runnable r,
1667 >                                      ThreadPoolExecutor executor) {}
1668 >    }
1669 >
1670 >    /**
1671 >     * A CyclicBarrier that uses timed await and fails with
1672 >     * AssertionFailedErrors instead of throwing checked exceptions.
1673 >     */
1674 >    public class CheckedBarrier extends CyclicBarrier {
1675 >        public CheckedBarrier(int parties) { super(parties); }
1676 >
1677 >        public int await() {
1678              try {
1679 <                Thread.sleep(MEDIUM_DELAY_MS);
1679 >                return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1680 >            } catch (TimeoutException timedOut) {
1681 >                throw new AssertionFailedError("timed out");
1682 >            } catch (Exception fail) {
1683 >                AssertionFailedError afe =
1684 >                    new AssertionFailedError("Unexpected exception: " + fail);
1685 >                afe.initCause(fail);
1686 >                throw afe;
1687              }
1688 <            catch(InterruptedException success) {
1688 >        }
1689 >    }
1690 >
1691 >    void checkEmpty(BlockingQueue q) {
1692 >        try {
1693 >            assertTrue(q.isEmpty());
1694 >            assertEquals(0, q.size());
1695 >            assertNull(q.peek());
1696 >            assertNull(q.poll());
1697 >            assertNull(q.poll(0, MILLISECONDS));
1698 >            assertEquals(q.toString(), "[]");
1699 >            assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1700 >            assertFalse(q.iterator().hasNext());
1701 >            try {
1702 >                q.element();
1703 >                shouldThrow();
1704 >            } catch (NoSuchElementException success) {}
1705 >            try {
1706 >                q.iterator().next();
1707 >                shouldThrow();
1708 >            } catch (NoSuchElementException success) {}
1709 >            try {
1710 >                q.remove();
1711 >                shouldThrow();
1712 >            } catch (NoSuchElementException success) {}
1713 >        } catch (InterruptedException fail) { threadUnexpectedException(fail); }
1714 >    }
1715 >
1716 >    void assertSerialEquals(Object x, Object y) {
1717 >        assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1718 >    }
1719 >
1720 >    void assertNotSerialEquals(Object x, Object y) {
1721 >        assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1722 >    }
1723 >
1724 >    byte[] serialBytes(Object o) {
1725 >        try {
1726 >            ByteArrayOutputStream bos = new ByteArrayOutputStream();
1727 >            ObjectOutputStream oos = new ObjectOutputStream(bos);
1728 >            oos.writeObject(o);
1729 >            oos.flush();
1730 >            oos.close();
1731 >            return bos.toByteArray();
1732 >        } catch (Throwable fail) {
1733 >            threadUnexpectedException(fail);
1734 >            return new byte[0];
1735 >        }
1736 >    }
1737 >
1738 >    @SuppressWarnings("unchecked")
1739 >    <T> T serialClone(T o) {
1740 >        try {
1741 >            ObjectInputStream ois = new ObjectInputStream
1742 >                (new ByteArrayInputStream(serialBytes(o)));
1743 >            T clone = (T) ois.readObject();
1744 >            assertSame(o.getClass(), clone.getClass());
1745 >            return clone;
1746 >        } catch (Throwable fail) {
1747 >            threadUnexpectedException(fail);
1748 >            return null;
1749 >        }
1750 >    }
1751 >
1752 >    public void assertThrows(Class<? extends Throwable> expectedExceptionClass,
1753 >                             Runnable... throwingActions) {
1754 >        for (Runnable throwingAction : throwingActions) {
1755 >            boolean threw = false;
1756 >            try { throwingAction.run(); }
1757 >            catch (Throwable t) {
1758 >                threw = true;
1759 >                if (!expectedExceptionClass.isInstance(t)) {
1760 >                    AssertionFailedError afe =
1761 >                        new AssertionFailedError
1762 >                        ("Expected " + expectedExceptionClass.getName() +
1763 >                         ", got " + t.getClass().getName());
1764 >                    afe.initCause(t);
1765 >                    threadUnexpectedException(afe);
1766 >                }
1767              }
1768 +            if (!threw)
1769 +                shouldThrow(expectedExceptionClass.getName());
1770          }
1771      }
1772 <    
1772 >
1773 >    public void assertIteratorExhausted(Iterator<?> it) {
1774 >        try {
1775 >            it.next();
1776 >            shouldThrow();
1777 >        } catch (NoSuchElementException success) {}
1778 >        assertFalse(it.hasNext());
1779 >    }
1780   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines