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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines