ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.220
Committed: Sat Mar 11 17:33:32 2017 UTC (7 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.219: +4 -5 lines
Log Message:
fix unused imports reported by errorprone [RemoveUnusedImports]

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