ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.175
Committed: Sun Oct 11 23:07:44 2015 UTC (8 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.174: +12 -12 lines
Log Message:
comment out esoteric debugging diagnostics

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