ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.171
Committed: Thu Oct 8 23:06:01 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.170: +14 -0 lines
Log Message:
add even more debugging info to wedged test detection

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