ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.99
Committed: Tue Feb 5 03:39:34 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.98: +1 -0 lines
Log Message:
add ForkJoinPool8Test

File Contents

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