ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.97
Committed: Fri Feb 1 19:07:36 2013 UTC (11 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.96: +32 -1 lines
Log Message:
add support for conditional jdk8 tests

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