ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.98
Committed: Sun Feb 3 06:20:32 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.97: +23 -12 lines
Log Message:
better method names

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     };
291     addNamedTestClasses(suite, java8TestClassNames);
292 jsr166 1.97 }
293 jsr166 1.98
294 jsr166 1.97 return suite;
295 dl 1.6 }
296    
297 dl 1.1
298 dl 1.2 public static long SHORT_DELAY_MS;
299     public static long SMALL_DELAY_MS;
300     public static long MEDIUM_DELAY_MS;
301     public static long LONG_DELAY_MS;
302    
303    
304     /**
305 jsr166 1.27 * Returns the shortest timed delay. This could
306 dl 1.15 * be reimplemented to use for example a Property.
307 jsr166 1.27 */
308 dl 1.2 protected long getShortDelay() {
309 dl 1.21 return 50;
310 dl 1.2 }
311    
312     /**
313 jsr166 1.27 * Sets delays as multiples of SHORT_DELAY.
314 dl 1.2 */
315 jsr166 1.43 protected void setDelays() {
316 dl 1.2 SHORT_DELAY_MS = getShortDelay();
317 jsr166 1.53 SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
318 dl 1.2 MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
319 jsr166 1.71 LONG_DELAY_MS = SHORT_DELAY_MS * 200;
320 dl 1.2 }
321    
322 dl 1.1 /**
323 jsr166 1.81 * Returns a timeout in milliseconds to be used in tests that
324     * verify that operations block or time out.
325     */
326     long timeoutMillis() {
327     return SHORT_DELAY_MS / 4;
328     }
329    
330     /**
331     * Returns a new Date instance representing a time delayMillis
332     * milliseconds in the future.
333     */
334     Date delayedDate(long delayMillis) {
335 jsr166 1.84 return new Date(System.currentTimeMillis() + delayMillis);
336 jsr166 1.81 }
337    
338     /**
339 jsr166 1.53 * The first exception encountered if any threadAssertXXX method fails.
340 dl 1.1 */
341 jsr166 1.53 private final AtomicReference<Throwable> threadFailure
342     = new AtomicReference<Throwable>(null);
343 dl 1.1
344     /**
345 jsr166 1.53 * Records an exception so that it can be rethrown later in the test
346     * harness thread, triggering a test case failure. Only the first
347     * failure is recorded; subsequent calls to this method from within
348     * the same test have no effect.
349 dl 1.1 */
350 jsr166 1.53 public void threadRecordFailure(Throwable t) {
351     threadFailure.compareAndSet(null, t);
352     }
353    
354 jsr166 1.27 public void setUp() {
355 dl 1.2 setDelays();
356 dl 1.1 }
357    
358     /**
359 jsr166 1.85 * Extra checks that get done for all test cases.
360     *
361 jsr166 1.53 * Triggers test case failure if any thread assertions have failed,
362     * by rethrowing, in the test harness thread, any exception recorded
363     * earlier by threadRecordFailure.
364 jsr166 1.85 *
365     * Triggers test case failure if interrupt status is set in the main thread.
366 jsr166 1.53 */
367     public void tearDown() throws Exception {
368 jsr166 1.70 Throwable t = threadFailure.getAndSet(null);
369 jsr166 1.53 if (t != null) {
370     if (t instanceof Error)
371     throw (Error) t;
372     else if (t instanceof RuntimeException)
373     throw (RuntimeException) t;
374     else if (t instanceof Exception)
375     throw (Exception) t;
376 jsr166 1.57 else {
377     AssertionFailedError afe =
378     new AssertionFailedError(t.toString());
379     afe.initCause(t);
380     throw afe;
381     }
382 jsr166 1.53 }
383 jsr166 1.85
384     if (Thread.interrupted())
385     throw new AssertionFailedError("interrupt status set in main thread");
386 dl 1.1 }
387    
388 dl 1.5 /**
389 jsr166 1.53 * Just like fail(reason), but additionally recording (using
390 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
391     * the current testcase will fail.
392 jsr166 1.27 */
393 dl 1.1 public void threadFail(String reason) {
394 jsr166 1.53 try {
395     fail(reason);
396 jsr166 1.57 } catch (AssertionFailedError t) {
397 jsr166 1.53 threadRecordFailure(t);
398     fail(reason);
399     }
400 dl 1.1 }
401    
402 dl 1.5 /**
403 jsr166 1.53 * Just like assertTrue(b), but additionally recording (using
404 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
405     * the current testcase will fail.
406 jsr166 1.27 */
407 dl 1.1 public void threadAssertTrue(boolean b) {
408 jsr166 1.53 try {
409 dl 1.1 assertTrue(b);
410 jsr166 1.57 } catch (AssertionFailedError t) {
411 jsr166 1.53 threadRecordFailure(t);
412     throw t;
413 dl 1.1 }
414     }
415 dl 1.5
416     /**
417 jsr166 1.53 * Just like assertFalse(b), but additionally recording (using
418 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
419     * the current testcase will fail.
420 jsr166 1.27 */
421 dl 1.1 public void threadAssertFalse(boolean b) {
422 jsr166 1.53 try {
423 dl 1.1 assertFalse(b);
424 jsr166 1.57 } catch (AssertionFailedError t) {
425 jsr166 1.53 threadRecordFailure(t);
426     throw t;
427 dl 1.1 }
428     }
429 dl 1.5
430     /**
431 jsr166 1.53 * Just like assertNull(x), but additionally recording (using
432 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
433     * the current testcase will fail.
434 jsr166 1.27 */
435 dl 1.1 public void threadAssertNull(Object x) {
436 jsr166 1.53 try {
437 dl 1.1 assertNull(x);
438 jsr166 1.57 } catch (AssertionFailedError t) {
439 jsr166 1.53 threadRecordFailure(t);
440     throw t;
441 dl 1.1 }
442     }
443 dl 1.5
444     /**
445 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
446 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
447     * the current testcase will fail.
448 jsr166 1.27 */
449 dl 1.1 public void threadAssertEquals(long x, long y) {
450 jsr166 1.53 try {
451 dl 1.1 assertEquals(x, y);
452 jsr166 1.57 } catch (AssertionFailedError t) {
453 jsr166 1.53 threadRecordFailure(t);
454     throw t;
455 dl 1.1 }
456     }
457 dl 1.5
458     /**
459 jsr166 1.53 * Just like assertEquals(x, y), but additionally recording (using
460 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
461     * the current testcase will fail.
462 jsr166 1.27 */
463 dl 1.1 public void threadAssertEquals(Object x, Object y) {
464 jsr166 1.53 try {
465 dl 1.1 assertEquals(x, y);
466 jsr166 1.57 } catch (AssertionFailedError t) {
467 jsr166 1.53 threadRecordFailure(t);
468     throw t;
469 jsr166 1.57 } catch (Throwable t) {
470     threadUnexpectedException(t);
471 dl 1.1 }
472     }
473    
474 dl 1.5 /**
475 jsr166 1.53 * Just like assertSame(x, y), but additionally recording (using
476 jsr166 1.57 * threadRecordFailure) any AssertionFailedError thrown, so that
477     * the current testcase will fail.
478 jsr166 1.52 */
479     public void threadAssertSame(Object x, Object y) {
480 jsr166 1.53 try {
481 jsr166 1.52 assertSame(x, y);
482 jsr166 1.57 } catch (AssertionFailedError t) {
483 jsr166 1.53 threadRecordFailure(t);
484     throw t;
485 jsr166 1.52 }
486     }
487    
488     /**
489 jsr166 1.53 * Calls threadFail with message "should throw exception".
490 jsr166 1.33 */
491 dl 1.3 public void threadShouldThrow() {
492 jsr166 1.53 threadFail("should throw exception");
493 dl 1.3 }
494    
495 dl 1.5 /**
496 jsr166 1.53 * Calls threadFail with message "should throw" + exceptionName.
497 jsr166 1.40 */
498     public void threadShouldThrow(String exceptionName) {
499 jsr166 1.53 threadFail("should throw " + exceptionName);
500 dl 1.3 }
501    
502 dl 1.31 /**
503 jsr166 1.57 * Records the given exception using {@link #threadRecordFailure},
504     * then rethrows the exception, wrapping it in an
505     * AssertionFailedError if necessary.
506 dl 1.31 */
507 jsr166 1.53 public void threadUnexpectedException(Throwable t) {
508     threadRecordFailure(t);
509     t.printStackTrace();
510     if (t instanceof RuntimeException)
511     throw (RuntimeException) t;
512     else if (t instanceof Error)
513     throw (Error) t;
514     else {
515 jsr166 1.57 AssertionFailedError afe =
516     new AssertionFailedError("unexpected exception: " + t);
517 jsr166 1.82 afe.initCause(t);
518 jsr166 1.57 throw afe;
519 jsr166 1.55 }
520 dl 1.31 }
521 dl 1.3
522 dl 1.1 /**
523 jsr166 1.81 * Delays, via Thread.sleep, for the given millisecond delay, but
524 dl 1.76 * if the sleep is shorter than specified, may re-sleep or yield
525     * until time elapses.
526     */
527 jsr166 1.81 static void delay(long millis) throws InterruptedException {
528 dl 1.76 long startTime = System.nanoTime();
529 jsr166 1.80 long ns = millis * 1000 * 1000;
530 dl 1.76 for (;;) {
531 jsr166 1.80 if (millis > 0L)
532     Thread.sleep(millis);
533 dl 1.76 else // too short to sleep
534     Thread.yield();
535     long d = ns - (System.nanoTime() - startTime);
536     if (d > 0L)
537 jsr166 1.80 millis = d / (1000 * 1000);
538 dl 1.76 else
539     break;
540     }
541     }
542    
543     /**
544 jsr166 1.53 * Waits out termination of a thread pool or fails doing so.
545 dl 1.1 */
546 jsr166 1.81 void joinPool(ExecutorService exec) {
547 dl 1.1 try {
548     exec.shutdown();
549 jsr166 1.54 assertTrue("ExecutorService did not terminate in a timely manner",
550 jsr166 1.71 exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
551 jsr166 1.33 } catch (SecurityException ok) {
552 dl 1.22 // Allowed in case test doesn't have privs
553 jsr166 1.33 } catch (InterruptedException ie) {
554 jsr166 1.44 fail("Unexpected InterruptedException");
555 dl 1.1 }
556     }
557    
558 jsr166 1.78 /**
559 jsr166 1.95 * A debugging tool to print all stack traces, as jstack does.
560     */
561 jsr166 1.96 static void printAllStackTraces() {
562     for (ThreadInfo info :
563     ManagementFactory.getThreadMXBean()
564     .dumpAllThreads(true, true))
565     System.err.print(info);
566 jsr166 1.95 }
567    
568     /**
569 jsr166 1.81 * Checks that thread does not terminate within the default
570     * millisecond delay of {@code timeoutMillis()}.
571     */
572     void assertThreadStaysAlive(Thread thread) {
573     assertThreadStaysAlive(thread, timeoutMillis());
574     }
575    
576     /**
577 jsr166 1.80 * Checks that thread does not terminate within the given millisecond delay.
578 jsr166 1.78 */
579 jsr166 1.81 void assertThreadStaysAlive(Thread thread, long millis) {
580 jsr166 1.78 try {
581 jsr166 1.80 // No need to optimize the failing case via Thread.join.
582     delay(millis);
583 jsr166 1.78 assertTrue(thread.isAlive());
584     } catch (InterruptedException ie) {
585     fail("Unexpected InterruptedException");
586     }
587     }
588 dl 1.5
589     /**
590 jsr166 1.90 * Checks that the threads do not terminate within the default
591     * millisecond delay of {@code timeoutMillis()}.
592     */
593     void assertThreadsStayAlive(Thread... threads) {
594     assertThreadsStayAlive(timeoutMillis(), threads);
595     }
596    
597     /**
598     * Checks that the threads do not terminate within the given millisecond delay.
599     */
600     void assertThreadsStayAlive(long millis, Thread... threads) {
601     try {
602     // No need to optimize the failing case via Thread.join.
603     delay(millis);
604     for (Thread thread : threads)
605     assertTrue(thread.isAlive());
606     } catch (InterruptedException ie) {
607     fail("Unexpected InterruptedException");
608     }
609     }
610    
611     /**
612 jsr166 1.83 * Checks that future.get times out, with the default timeout of
613     * {@code timeoutMillis()}.
614     */
615     void assertFutureTimesOut(Future future) {
616     assertFutureTimesOut(future, timeoutMillis());
617     }
618    
619     /**
620     * Checks that future.get times out, with the given millisecond timeout.
621     */
622     void assertFutureTimesOut(Future future, long timeoutMillis) {
623     long startTime = System.nanoTime();
624     try {
625     future.get(timeoutMillis, MILLISECONDS);
626     shouldThrow();
627     } catch (TimeoutException success) {
628     } catch (Exception e) {
629     threadUnexpectedException(e);
630     } finally { future.cancel(true); }
631     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
632     }
633    
634     /**
635 jsr166 1.53 * Fails with message "should throw exception".
636 jsr166 1.27 */
637 dl 1.3 public void shouldThrow() {
638     fail("Should throw exception");
639     }
640    
641 dl 1.5 /**
642 jsr166 1.53 * Fails with message "should throw " + exceptionName.
643 jsr166 1.40 */
644     public void shouldThrow(String exceptionName) {
645     fail("Should throw " + exceptionName);
646     }
647    
648     /**
649 dl 1.1 * The number of elements to place in collections, arrays, etc.
650     */
651 jsr166 1.45 public static final int SIZE = 20;
652 dl 1.1
653     // Some convenient Integer constants
654    
655 jsr166 1.47 public static final Integer zero = new Integer(0);
656     public static final Integer one = new Integer(1);
657     public static final Integer two = new Integer(2);
658     public static final Integer three = new Integer(3);
659 jsr166 1.45 public static final Integer four = new Integer(4);
660     public static final Integer five = new Integer(5);
661 jsr166 1.47 public static final Integer six = new Integer(6);
662 jsr166 1.45 public static final Integer seven = new Integer(7);
663     public static final Integer eight = new Integer(8);
664 jsr166 1.47 public static final Integer nine = new Integer(9);
665 jsr166 1.45 public static final Integer m1 = new Integer(-1);
666     public static final Integer m2 = new Integer(-2);
667     public static final Integer m3 = new Integer(-3);
668 jsr166 1.47 public static final Integer m4 = new Integer(-4);
669     public static final Integer m5 = new Integer(-5);
670     public static final Integer m6 = new Integer(-6);
671 jsr166 1.45 public static final Integer m10 = new Integer(-10);
672 dl 1.7
673    
674     /**
675 jsr166 1.49 * Runs Runnable r with a security policy that permits precisely
676     * the specified permissions. If there is no current security
677     * manager, the runnable is run twice, both with and without a
678     * security manager. We require that any security manager permit
679     * getPolicy/setPolicy.
680     */
681     public void runWithPermissions(Runnable r, Permission... permissions) {
682     SecurityManager sm = System.getSecurityManager();
683     if (sm == null) {
684     r.run();
685 jsr166 1.93 }
686     runWithSecurityManagerWithPermissions(r, permissions);
687     }
688    
689     /**
690     * Runs Runnable r with a security policy that permits precisely
691     * the specified permissions. If there is no current security
692     * manager, a temporary one is set for the duration of the
693     * Runnable. We require that any security manager permit
694     * getPolicy/setPolicy.
695     */
696     public void runWithSecurityManagerWithPermissions(Runnable r,
697     Permission... permissions) {
698     SecurityManager sm = System.getSecurityManager();
699     if (sm == null) {
700 jsr166 1.49 Policy savedPolicy = Policy.getPolicy();
701     try {
702     Policy.setPolicy(permissivePolicy());
703     System.setSecurityManager(new SecurityManager());
704 jsr166 1.93 runWithSecurityManagerWithPermissions(r, permissions);
705 jsr166 1.49 } finally {
706     System.setSecurityManager(null);
707     Policy.setPolicy(savedPolicy);
708     }
709     } else {
710     Policy savedPolicy = Policy.getPolicy();
711     AdjustablePolicy policy = new AdjustablePolicy(permissions);
712     Policy.setPolicy(policy);
713    
714     try {
715     r.run();
716     } finally {
717     policy.addPermission(new SecurityPermission("setPolicy"));
718     Policy.setPolicy(savedPolicy);
719     }
720     }
721     }
722    
723     /**
724     * Runs a runnable without any permissions.
725     */
726     public void runWithoutPermissions(Runnable r) {
727     runWithPermissions(r);
728     }
729    
730     /**
731 dl 1.7 * A security policy where new permissions can be dynamically added
732     * or all cleared.
733     */
734 jsr166 1.45 public static class AdjustablePolicy extends java.security.Policy {
735 dl 1.7 Permissions perms = new Permissions();
736 jsr166 1.49 AdjustablePolicy(Permission... permissions) {
737     for (Permission permission : permissions)
738     perms.add(permission);
739     }
740 dl 1.7 void addPermission(Permission perm) { perms.add(perm); }
741     void clearPermissions() { perms = new Permissions(); }
742 jsr166 1.42 public PermissionCollection getPermissions(CodeSource cs) {
743     return perms;
744     }
745     public PermissionCollection getPermissions(ProtectionDomain pd) {
746     return perms;
747     }
748     public boolean implies(ProtectionDomain pd, Permission p) {
749     return perms.implies(p);
750     }
751     public void refresh() {}
752 jsr166 1.93 public String toString() {
753     List<Permission> ps = new ArrayList<Permission>();
754     for (Enumeration<Permission> e = perms.elements(); e.hasMoreElements();)
755     ps.add(e.nextElement());
756     return "AdjustablePolicy with permissions " + ps;
757     }
758 dl 1.7 }
759 dl 1.1
760 jsr166 1.38 /**
761 jsr166 1.49 * Returns a policy containing all the permissions we ever need.
762     */
763     public static Policy permissivePolicy() {
764     return new AdjustablePolicy
765     // Permissions j.u.c. needs directly
766     (new RuntimePermission("modifyThread"),
767     new RuntimePermission("getClassLoader"),
768     new RuntimePermission("setContextClassLoader"),
769     // Permissions needed to change permissions!
770     new SecurityPermission("getPolicy"),
771     new SecurityPermission("setPolicy"),
772     new RuntimePermission("setSecurityManager"),
773     // Permissions needed by the junit test harness
774     new RuntimePermission("accessDeclaredMembers"),
775     new PropertyPermission("*", "read"),
776     new java.io.FilePermission("<<ALL FILES>>", "read"));
777     }
778    
779     /**
780 jsr166 1.60 * Sleeps until the given time has elapsed.
781     * Throws AssertionFailedError if interrupted.
782     */
783     void sleep(long millis) {
784     try {
785 dl 1.76 delay(millis);
786 jsr166 1.60 } catch (InterruptedException ie) {
787     AssertionFailedError afe =
788     new AssertionFailedError("Unexpected InterruptedException");
789     afe.initCause(ie);
790     throw afe;
791     }
792     }
793    
794     /**
795 jsr166 1.88 * Spin-waits up to the specified number of milliseconds for the given
796 jsr166 1.65 * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
797     */
798     void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
799 jsr166 1.88 long startTime = System.nanoTime();
800 jsr166 1.65 for (;;) {
801     Thread.State s = thread.getState();
802     if (s == Thread.State.BLOCKED ||
803     s == Thread.State.WAITING ||
804 jsr166 1.67 s == Thread.State.TIMED_WAITING)
805 jsr166 1.65 return;
806 jsr166 1.67 else if (s == Thread.State.TERMINATED)
807     fail("Unexpected thread termination");
808 jsr166 1.88 else if (millisElapsedSince(startTime) > timeoutMillis) {
809 jsr166 1.67 threadAssertTrue(thread.isAlive());
810     return;
811     }
812 jsr166 1.65 Thread.yield();
813     }
814     }
815    
816     /**
817 jsr166 1.75 * Waits up to LONG_DELAY_MS for the given thread to enter a wait
818     * state: BLOCKED, WAITING, or TIMED_WAITING.
819     */
820     void waitForThreadToEnterWaitState(Thread thread) {
821     waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
822     }
823    
824     /**
825 jsr166 1.66 * Returns the number of milliseconds since time given by
826     * startNanoTime, which must have been previously returned from a
827     * call to {@link System.nanoTime()}.
828     */
829     long millisElapsedSince(long startNanoTime) {
830     return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
831     }
832 jsr166 1.68
833 jsr166 1.66 /**
834 jsr166 1.58 * Returns a new started daemon Thread running the given runnable.
835 jsr166 1.38 */
836     Thread newStartedThread(Runnable runnable) {
837     Thread t = new Thread(runnable);
838 jsr166 1.58 t.setDaemon(true);
839 jsr166 1.38 t.start();
840     return t;
841     }
842 dl 1.1
843 jsr166 1.59 /**
844     * Waits for the specified time (in milliseconds) for the thread
845     * to terminate (using {@link Thread#join(long)}), else interrupts
846     * the thread (in the hope that it may terminate later) and fails.
847     */
848     void awaitTermination(Thread t, long timeoutMillis) {
849     try {
850     t.join(timeoutMillis);
851     } catch (InterruptedException ie) {
852     threadUnexpectedException(ie);
853     } finally {
854 jsr166 1.83 if (t.getState() != Thread.State.TERMINATED) {
855 jsr166 1.59 t.interrupt();
856     fail("Test timed out");
857     }
858     }
859     }
860    
861 jsr166 1.75 /**
862     * Waits for LONG_DELAY_MS milliseconds for the thread to
863     * terminate (using {@link Thread#join(long)}), else interrupts
864     * the thread (in the hope that it may terminate later) and fails.
865     */
866     void awaitTermination(Thread t) {
867     awaitTermination(t, LONG_DELAY_MS);
868     }
869    
870 dl 1.1 // Some convenient Runnable classes
871    
872 jsr166 1.45 public abstract class CheckedRunnable implements Runnable {
873     protected abstract void realRun() throws Throwable;
874 jsr166 1.35
875     public final void run() {
876     try {
877     realRun();
878     } catch (Throwable t) {
879     threadUnexpectedException(t);
880     }
881     }
882     }
883    
884 jsr166 1.45 public abstract class RunnableShouldThrow implements Runnable {
885     protected abstract void realRun() throws Throwable;
886 jsr166 1.40
887     final Class<?> exceptionClass;
888    
889     <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
890     this.exceptionClass = exceptionClass;
891     }
892    
893     public final void run() {
894     try {
895     realRun();
896     threadShouldThrow(exceptionClass.getSimpleName());
897     } catch (Throwable t) {
898     if (! exceptionClass.isInstance(t))
899     threadUnexpectedException(t);
900     }
901     }
902     }
903    
904 jsr166 1.45 public abstract class ThreadShouldThrow extends Thread {
905     protected abstract void realRun() throws Throwable;
906 jsr166 1.40
907     final Class<?> exceptionClass;
908    
909     <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
910     this.exceptionClass = exceptionClass;
911     }
912    
913     public final void run() {
914     try {
915     realRun();
916     threadShouldThrow(exceptionClass.getSimpleName());
917     } catch (Throwable t) {
918     if (! exceptionClass.isInstance(t))
919     threadUnexpectedException(t);
920     }
921     }
922     }
923    
924 jsr166 1.45 public abstract class CheckedInterruptedRunnable implements Runnable {
925     protected abstract void realRun() throws Throwable;
926 jsr166 1.35
927     public final void run() {
928     try {
929     realRun();
930 jsr166 1.40 threadShouldThrow("InterruptedException");
931 jsr166 1.35 } catch (InterruptedException success) {
932 jsr166 1.81 threadAssertFalse(Thread.interrupted());
933 jsr166 1.35 } catch (Throwable t) {
934     threadUnexpectedException(t);
935     }
936     }
937     }
938    
939 jsr166 1.45 public abstract class CheckedCallable<T> implements Callable<T> {
940     protected abstract T realCall() throws Throwable;
941 jsr166 1.35
942     public final T call() {
943     try {
944     return realCall();
945     } catch (Throwable t) {
946     threadUnexpectedException(t);
947 jsr166 1.53 return null;
948 jsr166 1.35 }
949 jsr166 1.40 }
950     }
951    
952 jsr166 1.53 public abstract class CheckedInterruptedCallable<T>
953     implements Callable<T> {
954 jsr166 1.45 protected abstract T realCall() throws Throwable;
955 jsr166 1.40
956     public final T call() {
957     try {
958     T result = realCall();
959     threadShouldThrow("InterruptedException");
960     return result;
961     } catch (InterruptedException success) {
962 jsr166 1.81 threadAssertFalse(Thread.interrupted());
963 jsr166 1.40 } catch (Throwable t) {
964     threadUnexpectedException(t);
965     }
966     return null;
967 jsr166 1.35 }
968     }
969    
970 jsr166 1.45 public static class NoOpRunnable implements Runnable {
971 dl 1.1 public void run() {}
972     }
973    
974 jsr166 1.45 public static class NoOpCallable implements Callable {
975 dl 1.1 public Object call() { return Boolean.TRUE; }
976 dl 1.10 }
977    
978 jsr166 1.45 public static final String TEST_STRING = "a test string";
979 dl 1.10
980 jsr166 1.45 public static class StringTask implements Callable<String> {
981 dl 1.10 public String call() { return TEST_STRING; }
982     }
983    
984 jsr166 1.48 public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
985     return new CheckedCallable<String>() {
986 jsr166 1.64 protected String realCall() {
987 jsr166 1.48 try {
988     latch.await();
989     } catch (InterruptedException quittingTime) {}
990     return TEST_STRING;
991     }};
992     }
993    
994 jsr166 1.73 public Runnable awaiter(final CountDownLatch latch) {
995     return new CheckedRunnable() {
996     public void realRun() throws InterruptedException {
997 jsr166 1.79 await(latch);
998 jsr166 1.73 }};
999     }
1000    
1001 jsr166 1.79 public void await(CountDownLatch latch) {
1002     try {
1003     assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
1004     } catch (Throwable t) {
1005     threadUnexpectedException(t);
1006     }
1007     }
1008    
1009 jsr166 1.89 public void await(Semaphore semaphore) {
1010     try {
1011     assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
1012     } catch (Throwable t) {
1013     threadUnexpectedException(t);
1014     }
1015     }
1016    
1017 jsr166 1.81 // /**
1018     // * Spin-waits up to LONG_DELAY_MS until flag becomes true.
1019     // */
1020     // public void await(AtomicBoolean flag) {
1021     // await(flag, LONG_DELAY_MS);
1022     // }
1023    
1024     // /**
1025     // * Spin-waits up to the specified timeout until flag becomes true.
1026     // */
1027     // public void await(AtomicBoolean flag, long timeoutMillis) {
1028     // long startTime = System.nanoTime();
1029     // while (!flag.get()) {
1030     // if (millisElapsedSince(startTime) > timeoutMillis)
1031     // throw new AssertionFailedError("timed out");
1032     // Thread.yield();
1033     // }
1034     // }
1035    
1036 jsr166 1.45 public static class NPETask implements Callable<String> {
1037 dl 1.10 public String call() { throw new NullPointerException(); }
1038     }
1039    
1040 jsr166 1.45 public static class CallableOne implements Callable<Integer> {
1041 dl 1.10 public Integer call() { return one; }
1042 dl 1.1 }
1043    
1044 jsr166 1.45 public class ShortRunnable extends CheckedRunnable {
1045     protected void realRun() throws Throwable {
1046 dl 1.76 delay(SHORT_DELAY_MS);
1047 dl 1.1 }
1048     }
1049    
1050 jsr166 1.45 public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
1051     protected void realRun() throws InterruptedException {
1052 dl 1.76 delay(SHORT_DELAY_MS);
1053 dl 1.1 }
1054     }
1055    
1056 jsr166 1.45 public class SmallRunnable extends CheckedRunnable {
1057     protected void realRun() throws Throwable {
1058 dl 1.76 delay(SMALL_DELAY_MS);
1059 dl 1.1 }
1060     }
1061    
1062 jsr166 1.45 public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
1063     protected void realRun() {
1064 dl 1.6 try {
1065 dl 1.76 delay(SMALL_DELAY_MS);
1066 jsr166 1.44 } catch (InterruptedException ok) {}
1067 dl 1.6 }
1068     }
1069    
1070 jsr166 1.45 public class SmallCallable extends CheckedCallable {
1071     protected Object realCall() throws InterruptedException {
1072 dl 1.76 delay(SMALL_DELAY_MS);
1073 dl 1.1 return Boolean.TRUE;
1074     }
1075     }
1076    
1077 jsr166 1.45 public class MediumRunnable extends CheckedRunnable {
1078     protected void realRun() throws Throwable {
1079 dl 1.76 delay(MEDIUM_DELAY_MS);
1080 dl 1.1 }
1081     }
1082    
1083 jsr166 1.45 public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
1084     protected void realRun() throws InterruptedException {
1085 dl 1.76 delay(MEDIUM_DELAY_MS);
1086 dl 1.1 }
1087     }
1088    
1089 jsr166 1.63 public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
1090     return new CheckedRunnable() {
1091     protected void realRun() {
1092     try {
1093 dl 1.76 delay(timeoutMillis);
1094 jsr166 1.63 } catch (InterruptedException ok) {}
1095     }};
1096     }
1097    
1098 jsr166 1.45 public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
1099     protected void realRun() {
1100 dl 1.1 try {
1101 dl 1.76 delay(MEDIUM_DELAY_MS);
1102 jsr166 1.44 } catch (InterruptedException ok) {}
1103 dl 1.1 }
1104     }
1105 dl 1.5
1106 jsr166 1.45 public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
1107     protected void realRun() {
1108 dl 1.12 try {
1109 dl 1.76 delay(LONG_DELAY_MS);
1110 jsr166 1.44 } catch (InterruptedException ok) {}
1111 dl 1.12 }
1112     }
1113    
1114 dl 1.5 /**
1115     * For use as ThreadFactory in constructors
1116     */
1117 jsr166 1.45 public static class SimpleThreadFactory implements ThreadFactory {
1118 jsr166 1.33 public Thread newThread(Runnable r) {
1119 dl 1.5 return new Thread(r);
1120 jsr166 1.27 }
1121 dl 1.5 }
1122    
1123 jsr166 1.61 public interface TrackedRunnable extends Runnable {
1124     boolean isDone();
1125     }
1126    
1127     public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
1128     return new TrackedRunnable() {
1129     private volatile boolean done = false;
1130     public boolean isDone() { return done; }
1131     public void run() {
1132     try {
1133 dl 1.76 delay(timeoutMillis);
1134 jsr166 1.61 done = true;
1135     } catch (InterruptedException ok) {}
1136     }
1137     };
1138     }
1139    
1140 jsr166 1.45 public static class TrackedShortRunnable implements Runnable {
1141     public volatile boolean done = false;
1142 dl 1.5 public void run() {
1143     try {
1144 dl 1.76 delay(SHORT_DELAY_MS);
1145 jsr166 1.61 done = true;
1146     } catch (InterruptedException ok) {}
1147     }
1148     }
1149    
1150     public static class TrackedSmallRunnable implements Runnable {
1151     public volatile boolean done = false;
1152     public void run() {
1153     try {
1154 dl 1.76 delay(SMALL_DELAY_MS);
1155 dl 1.5 done = true;
1156 jsr166 1.44 } catch (InterruptedException ok) {}
1157 dl 1.6 }
1158     }
1159    
1160 jsr166 1.45 public static class TrackedMediumRunnable implements Runnable {
1161     public volatile boolean done = false;
1162 dl 1.6 public void run() {
1163     try {
1164 dl 1.76 delay(MEDIUM_DELAY_MS);
1165 dl 1.6 done = true;
1166 jsr166 1.44 } catch (InterruptedException ok) {}
1167 dl 1.6 }
1168     }
1169    
1170 jsr166 1.45 public static class TrackedLongRunnable implements Runnable {
1171     public volatile boolean done = false;
1172 dl 1.6 public void run() {
1173     try {
1174 dl 1.76 delay(LONG_DELAY_MS);
1175 dl 1.6 done = true;
1176 jsr166 1.44 } catch (InterruptedException ok) {}
1177 dl 1.6 }
1178     }
1179    
1180 jsr166 1.45 public static class TrackedNoOpRunnable implements Runnable {
1181     public volatile boolean done = false;
1182 dl 1.6 public void run() {
1183     done = true;
1184 dl 1.5 }
1185     }
1186    
1187 jsr166 1.45 public static class TrackedCallable implements Callable {
1188     public volatile boolean done = false;
1189 dl 1.5 public Object call() {
1190     try {
1191 dl 1.76 delay(SMALL_DELAY_MS);
1192 dl 1.5 done = true;
1193 jsr166 1.44 } catch (InterruptedException ok) {}
1194 dl 1.5 return Boolean.TRUE;
1195     }
1196     }
1197 dl 1.14
1198 jsr166 1.53 /**
1199     * Analog of CheckedRunnable for RecursiveAction
1200     */
1201     public abstract class CheckedRecursiveAction extends RecursiveAction {
1202     protected abstract void realCompute() throws Throwable;
1203    
1204     public final void compute() {
1205     try {
1206     realCompute();
1207     } catch (Throwable t) {
1208     threadUnexpectedException(t);
1209     }
1210     }
1211     }
1212    
1213     /**
1214     * Analog of CheckedCallable for RecursiveTask
1215     */
1216     public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
1217     protected abstract T realCompute() throws Throwable;
1218    
1219     public final T compute() {
1220     try {
1221     return realCompute();
1222     } catch (Throwable t) {
1223     threadUnexpectedException(t);
1224     return null;
1225     }
1226     }
1227     }
1228 dl 1.5
1229     /**
1230     * For use as RejectedExecutionHandler in constructors
1231     */
1232 jsr166 1.45 public static class NoOpREHandler implements RejectedExecutionHandler {
1233 jsr166 1.35 public void rejectedExecution(Runnable r,
1234     ThreadPoolExecutor executor) {}
1235 dl 1.5 }
1236 jsr166 1.27
1237 jsr166 1.60 /**
1238 jsr166 1.86 * A CyclicBarrier that uses timed await and fails with
1239     * AssertionFailedErrors instead of throwing checked exceptions.
1240 jsr166 1.60 */
1241     public class CheckedBarrier extends CyclicBarrier {
1242     public CheckedBarrier(int parties) { super(parties); }
1243    
1244     public int await() {
1245     try {
1246 jsr166 1.86 return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
1247     } catch (TimeoutException e) {
1248     throw new AssertionFailedError("timed out");
1249 jsr166 1.60 } catch (Exception e) {
1250     AssertionFailedError afe =
1251     new AssertionFailedError("Unexpected exception: " + e);
1252     afe.initCause(e);
1253     throw afe;
1254     }
1255     }
1256     }
1257    
1258 jsr166 1.81 void checkEmpty(BlockingQueue q) {
1259 jsr166 1.72 try {
1260     assertTrue(q.isEmpty());
1261     assertEquals(0, q.size());
1262     assertNull(q.peek());
1263     assertNull(q.poll());
1264     assertNull(q.poll(0, MILLISECONDS));
1265     assertEquals(q.toString(), "[]");
1266     assertTrue(Arrays.equals(q.toArray(), new Object[0]));
1267     assertFalse(q.iterator().hasNext());
1268     try {
1269     q.element();
1270     shouldThrow();
1271     } catch (NoSuchElementException success) {}
1272     try {
1273     q.iterator().next();
1274     shouldThrow();
1275     } catch (NoSuchElementException success) {}
1276     try {
1277     q.remove();
1278     shouldThrow();
1279     } catch (NoSuchElementException success) {}
1280     } catch (InterruptedException ie) {
1281     threadUnexpectedException(ie);
1282     }
1283     }
1284    
1285 jsr166 1.91 void assertSerialEquals(Object x, Object y) {
1286     assertTrue(Arrays.equals(serialBytes(x), serialBytes(y)));
1287     }
1288    
1289     void assertNotSerialEquals(Object x, Object y) {
1290     assertFalse(Arrays.equals(serialBytes(x), serialBytes(y)));
1291     }
1292    
1293     byte[] serialBytes(Object o) {
1294 jsr166 1.79 try {
1295     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1296     ObjectOutputStream oos = new ObjectOutputStream(bos);
1297     oos.writeObject(o);
1298     oos.flush();
1299     oos.close();
1300 jsr166 1.91 return bos.toByteArray();
1301     } catch (Throwable t) {
1302     threadUnexpectedException(t);
1303     return new byte[0];
1304     }
1305     }
1306    
1307     @SuppressWarnings("unchecked")
1308     <T> T serialClone(T o) {
1309     try {
1310 jsr166 1.87 ObjectInputStream ois = new ObjectInputStream
1311 jsr166 1.91 (new ByteArrayInputStream(serialBytes(o)));
1312 jsr166 1.87 T clone = (T) ois.readObject();
1313     assertSame(o.getClass(), clone.getClass());
1314     return clone;
1315 jsr166 1.79 } catch (Throwable t) {
1316     threadUnexpectedException(t);
1317     return null;
1318     }
1319     }
1320 dl 1.1 }