ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.125
Committed: Thu Jan 15 18:58:07 2015 UTC (9 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.124: +1 -1 lines
Log Message:
use correct tense for javadoc

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