ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.274
Committed: Tue Mar 22 16:26:19 2022 UTC (2 years, 1 month ago) by dl
Branch: MAIN
Changes since 1.273: +23 -7 lines
Log Message:
Test additions

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