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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines