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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines