ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.131
Committed: Sat Apr 25 04:55:30 2015 UTC (9 years ago) by jsr166
Branch: MAIN
Changes since 1.130: +19 -8 lines
Log Message:
improve main methods; respect system properties; actually fail if a test fails

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