ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/JSR166TestCase.java
Revision: 1.254
Committed: Wed Apr 24 17:36:09 2019 UTC (5 years ago) by jsr166
Branch: MAIN
Changes since 1.253: +1 -0 lines
Log Message:
Add HashtableTest, leveraging MapTest infrastructure

File Contents

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