ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.128
Committed: Fri Feb 27 22:06:24 2015 UTC (9 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.127: +34 -36 lines
Log Message:
catch clause readability

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