ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.149
Committed: Sat Oct 3 16:57:25 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.148: +11 -1 lines
Log Message:
add PoolCloser for better test hygiene

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