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.9 by dl, Thu Dec 4 20:54:46 2003 UTC vs.
Revision 1.111 by dl, Sun Jul 21 22:24:18 2013 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines