ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.104
Committed: Thu Mar 21 00:26:43 2013 UTC (11 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.103: +5 -4 lines
Log Message:
CountedCompleters

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