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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines