ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.273
Committed: Wed Jan 27 02:13:22 2021 UTC (3 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.272: +1 -1 lines
Log Message:
typo

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