ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.256
Committed: Sun Aug 11 22:29:26 2019 UTC (4 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.255: +7 -0 lines
Log Message:
more assertions; more interleavings

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