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.33 by jsr166, Fri Jul 31 23:37:31 2009 UTC vs.
Revision 1.93 by jsr166, Sun Dec 16 17:22:42 2012 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines