ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.172
Committed: Fri Oct 9 01:26:36 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.171: +0 -3 lines
Log Message:
delete minor oops

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