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.16 by dl, Wed Jan 7 01:02:17 2004 UTC vs.
Revision 1.87 by jsr166, Mon May 30 22:53:21 2011 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines