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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines