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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines