ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.115
Committed: Wed May 14 21:06:38 2014 UTC (9 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.114: +17 -0 lines
Log Message:
add support for jdk9+ tests

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