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.26 by dl, Thu Mar 31 15:24:29 2005 UTC vs.
Revision 1.216 by jsr166, Wed Jan 4 06:09:58 2017 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines