ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.105
Committed: Thu Mar 21 19:06:54 2013 UTC (11 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.104: +1 -0 lines
Log Message:
test new map methods

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