ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.102
Committed: Wed Feb 6 19:55:06 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.101: +2 -1 lines
Log Message:
Add CompletableFutureTest

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