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