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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines