ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.270
Committed: Sun Sep 29 20:18:35 2019 UTC (4 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.269: +8 -1 lines
Log Message:
add T chooseRandomly(List<T> choices)

File Contents

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