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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines