ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.130
Committed: Tue Apr 21 05:00:23 2015 UTC (9 years ago) by jsr166
Branch: MAIN
Changes since 1.129: +1 -4 lines
Log Message:
atLeastJava9 can finally use java.class.version

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