ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.159
Committed: Sun Oct 4 00:30:50 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.158: +9 -5 lines
Log Message:
rejigger pool closing infrastructure

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