ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.110
Committed: Sun Jul 14 22:39:31 2013 UTC (10 years, 9 months ago) by jsr166
Branch: MAIN
Changes since 1.109: +1 -1 lines
Log Message:
register SplittableRandomTest as a jdk8+ test

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