ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.146
Committed: Fri Sep 25 23:32:15 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.145: +17 -6 lines
Log Message:
look much more aggressively for leaked threads in tearDown()

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