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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines